Inheritance: use trait Webiny\Component\Mongo\MongoTrait, use trait Webiny\Component\StdLib\ComponentTrait, use trait Webiny\Component\StdLib\SingletonTrait, use trait Webiny\Component\ServiceManager\ServiceManagerTrait, use trait Webiny\Component\StdLib\StdLibTrait
コード例 #1
0
ファイル: MaxMindGeoLite2.php プロジェクト: webiny/geoip
 /**
  * Base constructor.
  *
  * @param string $config Path to the MaxMind configuration.
  *
  * @throws \Webiny\Component\StdLib\Exception\Exception
  */
 public function __construct($config)
 {
     $config = \Webiny\Component\Config\Config::getInstance()->yaml($config);
     // bootstrap
     Mongo::setConfig(['Mongo' => $config->get('Mongo', null, true)]);
     Entity::setConfig(['Entity' => $config->get('Entity', null, true)]);
 }
コード例 #2
0
 public function __construct($entityClass, $entityCollection, $conditions, $order, $limit, $offset)
 {
     // Convert boolean strings to boolean
     foreach ($conditions as &$condition) {
         if (is_scalar($condition) && (strtolower($condition) === 'true' || strtolower($condition) === 'false')) {
             $condition = StdObjectWrapper::toBool($condition);
         }
     }
     $this->entityClass = $entityClass;
     $this->collectionName = $entityCollection;
     $this->conditions = $conditions;
     $this->order = $order;
     $this->offset = $offset;
     $this->limit = $limit;
     $this->cursor = Entity::getInstance()->getDatabase()->find($this->collectionName, $this->conditions)->sort($this->order)->skip($this->offset)->limit($this->limit);
 }
コード例 #3
0
ファイル: Install.php プロジェクト: webiny/geoip
 /**
  * Runs the installation.
  *
  * @throws \Webiny\Component\StdLib\Exception\Exception
  */
 public function runInstaller($configFile)
 {
     // bootstrap
     $this->config = Config::getInstance()->yaml($configFile);
     Mongo::setConfig(['Mongo' => $this->config->get('Mongo', null, true)]);
     Entity::setConfig(['Entity' => $this->config->get('Entity', null, true)]);
     /**
      * @var $mongo Mongo
      */
     $this->mongo = $this->mongo($this->config->Entity->Database);
     // import process
     $this->downloadDatabase();
     $this->unpackDatabase();
     $this->importLocations();
     //$this->importIp4CityBlock();
     //$this->importIp6CityBlock();
     echo "\nImport has finished.";
     die;
 }
コード例 #4
0
 /**
  * Add item to this entity collection<br>
  * NOTE: you need to call save() on parent entity to actually insert link into database
  *
  * @param array|\Webiny\Component\Entity\EntityAbstract $item
  *
  * @throws \Webiny\Component\Entity\EntityException
  * @return $this
  */
 public function add($item)
 {
     if ($this->isInstanceOf($item, '\\Webiny\\Component\\Entity\\EntityAbstract')) {
         $item = [$item];
     }
     /**
      * Validate items
      */
     foreach ($item as $i) {
         if (!$this->isInstanceOf($i, $this->getEntity()) && !Entity::getInstance()->getDatabase()->isMongoId($i)) {
             throw new EntityException(EntityException::INVALID_MANY2MANY_VALUE, [$this->attribute, 'entity ID or instance of ' . $this->getEntity() . ' or null', get_class($i)]);
         }
     }
     /**
      * Assign items
      */
     foreach ($item as $i) {
         $this->addedItems[] = $i;
     }
     return $this;
 }
コード例 #5
0
ファイル: EntityTest.php プロジェクト: Nkelliny/Framework
 public static function setUpBeforeClass()
 {
     Mongo::setConfig(realpath(__DIR__ . '/' . self::MONGO_CONFIG));
     Entity::setConfig(realpath(__DIR__ . '/' . self::CONFIG));
     /**
      * Make sure no collections exist
      */
     self::mongo()->dropCollection('Author');
     self::mongo()->dropCollection('Page');
     self::mongo()->dropCollection('Comment');
     self::mongo()->dropCollection('Label');
     self::mongo()->dropCollection('Label2Page');
     /**
      * Create some test entity instances
      */
     $page = new Page();
     $author = new Author();
     $comment = new Comment();
     $label = new Label();
     $label2 = new Label();
     /**
      * Try simple assignment (should trigger assign via magic method)
      */
     $author->name = 'Pavel Denisjuk';
     /**
      * Assign using regular way
      */
     $comment->getAttribute('text')->setValue('Best blog post ever!');
     $label->getAttribute('label')->setValue('marketing');
     $label2->getAttribute('label')->setValue('seo');
     $page->getAttribute('title')->setValue('First blog post');
     $page->getAttribute('publishOn')->setValue('2014-11-01');
     $page->getAttribute('remindOn')->setValue(time());
     $page->getAttribute('author')->setValue($author);
     $page->getAttribute('settings')->setValue(['key1' => 'value1', 'key2' => ['key3' => 'value3']]);
     $page->getAttribute('comments')->add($comment);
     $page->getAttribute('labels')->add([$label, $label2]);
     self::$page = $page;
 }
コード例 #6
0
ファイル: Many2OneAttribute.php プロジェクト: webiny/entity
 /**
  * Perform validation against given value
  *
  * @param $value
  *
  * @throws ValidationException
  * @return $this
  */
 protected function validate(&$value)
 {
     $mongoId = Entity::getInstance()->getDatabase()->isId($value);
     $abstractEntityClass = '\\Webiny\\Component\\Entity\\AbstractEntity';
     if (!$this->isNull($value) && !is_array($value) && !$this->isInstanceOf($value, $abstractEntityClass) && !$mongoId) {
         $this->expected('entity ID, instance of ' . $abstractEntityClass . ' or null', gettype($value));
     }
     return $this;
 }
コード例 #7
0
ファイル: bootstrap.php プロジェクト: Pavel910/Login
<?php

require_once '../vendor/autoload.php';
\Webiny\Component\Security\Security::setConfig('./securityConfig.yaml');
\Webiny\Component\Mongo\Mongo::setConfig('./mongoConfig.yaml');
\Webiny\Component\Entity\Entity::setConfig('./entityConfig.yaml');
$security = \Webiny\Component\Security\Security::getInstance();
$loginConfig = \Webiny\Component\Config\Config::getInstance()->yaml('./loginConfig.yaml');
$login = new \Webiny\Login\Login($security, $loginConfig);
コード例 #8
0
ファイル: Entity.php プロジェクト: Webiny/Framework
 protected static function postSetConfig()
 {
     // If attribute class maps are defined - set them into EntityAttributeBuilder
     $classMap = Entity::getConfig()->get('Attributes');
     if ($classMap) {
         $absClass = 'Webiny\\Component\\Entity\\Attribute\\AbstractAttribute';
         foreach ($classMap as $attr => $class) {
             if (!in_array($absClass, class_parents($class))) {
                 $message = 'Attribute class for attribute "%s" must extend %s';
                 throw new EntityException($message, [$attr, $absClass]);
             }
             EntityAttributeBuilder::$classMap[$attr] = $class;
         }
     }
 }
コード例 #9
0
ファイル: EntityPool.php プロジェクト: Nkelliny/Framework
 /**
  * Get entity database
  * @return \Webiny\Component\Mongo\Mongo
  */
 public function getDatabase()
 {
     return Entity::getInstance()->getDatabase();
 }
コード例 #10
0
ファイル: EntityCollection.php プロジェクト: webiny/entity
 /**
  * (PHP 5 &gt;= 5.0.0)<br/>
  * Retrieve an external iterator
  * @link http://php.net/manual/en/iteratoraggregate.getiterator.php
  * @return Traversable An instance of an object implementing <b>Iterator</b> or
  * <b>Traversable</b>
  */
 public function getIterator()
 {
     if ($this->loaded) {
         return new \ArrayIterator($this->value);
     }
     $dbItems = [];
     foreach ($this->data as $data) {
         $instance = new $this->entityClass();
         $data['__webiny_db__'] = true;
         $instance->populate($data);
         /**
          * Check if loaded instance is already in the pool and if yes - use the existing object
          */
         if ($itemInPool = Entity::getInstance()->get($this->entityClass, $instance->id)) {
             $dbItems[] = $itemInPool;
         } else {
             $dbItems[] = Entity::getInstance()->add($instance);
         }
     }
     $this->value += $dbItems;
     $this->loaded = true;
     if ($this->randomize) {
         shuffle($this->value);
     }
     return new \ArrayIterator($this->value);
 }
コード例 #11
0
 /**
  * Normalize given value to be a valid array of entity instances
  *
  * @param mixed $value
  *
  * @return array
  * @throws ValidationException
  */
 protected function normalizeValue($value)
 {
     if (is_null($value)) {
         return $value;
     }
     $entityClass = $this->getEntity();
     $entityCollectionClass = '\\Webiny\\Component\\Entity\\EntityCollection';
     // Validate Many2many attribute value
     if (!$this->isArray($value) && !$this->isArrayObject($value) && !$this->isInstanceOf($value, $entityCollectionClass)) {
         $exception = new ValidationException(ValidationException::DATA_TYPE, ['array, ArrayObject or EntityCollection', gettype($value)]);
         $exception->setAttribute($this->getName());
         throw $exception;
     }
     /* @var $entityAttribute One2ManyAttribute */
     $values = [];
     foreach ($value as $item) {
         $itemEntity = false;
         // $item can be an array of data, AbstractEntity or a simple mongo ID string
         if ($this->isInstanceOf($item, $entityClass)) {
             $itemEntity = $item;
         } elseif ($this->isArray($item) || $this->isArrayObject($item)) {
             $itemEntity = $entityClass::findById(isset($item['id']) ? $item['id'] : false);
         } elseif ($this->isString($item) && Entity::getInstance()->getDatabase()->isId($item)) {
             $itemEntity = $entityClass::findById($item);
         }
         // If instance was not found, create a new entity instance
         if (!$itemEntity) {
             $itemEntity = new $entityClass();
         }
         // If $item is an array - use it to populate the entity instance
         if ($this->isArray($item) || $this->isArrayObject($item)) {
             $itemEntity->populate($item);
         }
         $values[] = $itemEntity;
     }
     return new EntityCollection($this->getEntity(), $values);
 }
コード例 #12
0
ファイル: EntityTest.php プロジェクト: webiny/entity
 /**
  * Test onSet, onGet, onToDb and onToArray callbacks as well as setAfterPopulate (only useful in combination with onSet callback)
  */
 public function testOnCallbacks()
 {
     $entity = new Lib\EntityOnCallbacks();
     $entity->populate(['char' => 'value', 'number' => 12])->save();
     $this->assertEquals('get-db-get-set-12-value', $entity->char);
     Entity::getInstance()->reset();
     $entity = Lib\EntityOnCallbacks::findOne(['number' => 12]);
     $this->assertEquals('get-db-get-set-12-value', $entity->char);
     $this->assertEquals(120, $entity->number);
     $array = $entity->toArray();
     $this->assertEquals(['key' => 'value'], $array['char']);
 }
コード例 #13
0
ファイル: EntityCollection.php プロジェクト: Webiny/Framework
 /**
  * Count total number of items in collection
  *
  * TODO: unittest
  *
  * @return mixed
  */
 public function totalCount()
 {
     if (!isset($this->parameters['conditions'])) {
         return count($this->value);
     }
     if (!$this->totalCount) {
         $mongo = Entity::getInstance()->getDatabase();
         $entity = $this->entityClass;
         $this->totalCount = $mongo->count($entity::getEntityCollection(), $this->parameters['conditions']);
     }
     return $this->totalCount;
 }
コード例 #14
0
ファイル: AbstractAttribute.php プロジェクト: webiny/entity
 /**
  * Apply validator to given value
  *
  * @param string $validator
  * @param string $key
  * @param mixed  $value
  * @param array  $messages
  *
  * @throws ValidationException
  * @throws \Webiny\Component\StdLib\Exception\Exception
  */
 protected function applyValidator($validator, $key, $value, $messages = [])
 {
     try {
         if ($this->isString($validator)) {
             $params = $this->arr(explode(':', $validator));
             $vName = '';
             $validatorParams = [$this, $value, $params->removeFirst($vName)->val()];
             $validator = Entity::getInstance()->getValidator($vName);
             if (!$validator) {
                 throw new ValidationException('Validator does not exist');
             }
             $validator->validate(...$validatorParams);
         } elseif ($this->isCallable($validator)) {
             $vName = 'callable';
             $validator($value, $this);
         }
     } catch (ValidationException $e) {
         $msg = isset($messages[$vName]) ? $messages[$vName] : $e->getMessage();
         $ex = new ValidationException($msg);
         $ex->addError($key, $msg);
         throw $ex;
     }
 }
コード例 #15
0
 private function cleanUpRecords($newValues)
 {
     if (!$this->parent->exists()) {
         return;
     }
     $newIds = [];
     foreach ($newValues as $nv) {
         if (isset($nv['id']) && $nv['id'] != '') {
             $newIds[] = Entity::getInstance()->getDatabase()->id($nv['id']);
         }
     }
     $attrValues = $this->getValue();
     foreach ($attrValues as $r) {
         if (!in_array($r->id, $newIds)) {
             $r->delete();
         }
     }
 }
コード例 #16
0
 /**
  * Unlink given item (only removes the aggregation record)
  *
  * @param string|AbstractEntity $item
  *
  * @return bool
  */
 protected function unlinkItem($item)
 {
     // Convert instance to entity ID
     if ($item instanceof AbstractEntity) {
         $item = $item->id;
     }
     $sourceEntityId = $this->getParentEntity()->id;
     if ($this->isNull($sourceEntityId) || $this->isNull($item)) {
         return false;
     }
     $firstClassName = $this->extractClassName($this->getParentEntity());
     $secondClassName = $this->extractClassName($this->getEntity());
     $query = $this->arr([$firstClassName => $sourceEntityId, $secondClassName => $item])->sortKey()->val();
     $res = Entity::getInstance()->getDatabase()->delete($this->intermediateCollection, $query);
     return $res->getDeletedCount() == 1;
 }
コード例 #17
0
 /**
  * Perform validation against given value
  *
  * @param $value
  *
  * @throws ValidationException
  * @return $this
  */
 public function validate(&$value)
 {
     if (!$this->isNull($value) && !$this->isInstanceOf($value, '\\Webiny\\Component\\Entity\\EntityAbstract') && !Entity::getInstance()->getDatabase()->isMongoId($value)) {
         throw new ValidationException(ValidationException::ATTRIBUTE_VALIDATION_FAILED, [$this->attribute, 'entity ID, instance of \\Webiny\\Component\\Entity\\EntityAbstract or null', gettype($value)]);
     }
     return $this;
 }
コード例 #18
0
 /**
  * Unlink given item (only removes the aggregation record) and remove it from current loaded values
  *
  * @param Many2ManyAttribute    $attribute
  * @param string|EntityAbstract $item
  *
  * @return bool
  */
 public function unlink(Many2ManyAttribute $attribute, $item)
 {
     // Convert instance to entity ID
     if ($this->isInstanceOf($item, '\\Webiny\\Component\\Entity\\EntityAbstract')) {
         $item = $item->getId()->getValue();
     }
     $sourceEntityId = $attribute->getParentEntity()->getId()->getValue();
     if ($this->isNull($sourceEntityId) || $this->isNull($item)) {
         return;
     }
     $firstClassName = $this->extractClassName($attribute->getParentEntity());
     $secondClassName = $this->extractClassName($attribute->getEntity());
     $query = $this->arr([$firstClassName => $sourceEntityId, $secondClassName => $item])->sortKey()->val();
     $res = Entity::getInstance()->getDatabase()->remove($attribute->getIntermediateCollection(), $query);
     return $res['n'] == 1;
 }
コード例 #19
0
ファイル: One2ManyAttribute.php プロジェクト: webiny/entity
 private function cleanUpRecords($newValues)
 {
     if (!$this->parent->exists()) {
         return;
     }
     $newIds = [];
     foreach ($newValues as $nv) {
         if (isset($nv['id']) && $nv['id'] != '') {
             $newIds[] = Entity::getInstance()->getDatabase()->id($nv['id']);
         }
     }
     $where = ['_id' => ['$nin' => $newIds]];
     $where[$this->relatedAttribute] = $this->parent->id;
     $toRemove = call_user_func_array([$this->entityClass, 'find'], [$where]);
     foreach ($toRemove as $r) {
         $r->delete();
     }
 }