public function on(EntityInterface $entity) : self { $exception = new self(sprintf('More than one relationship found on "%s::%s"', $entity->class(), $this->child->relationship()->property())); $exception->child = $this->child; $exception->entity = $entity; return $exception; }
private function isValidProperty(string $property, EntityInterface $meta) : bool { if ($meta->properties()->contains($property)) { return true; } $property = new Str($property); if (!$property->match('/[a-zA-Z]+(\\.[a-zA-Z]+)+/')) { return false; } $pieces = $property->split('.'); $piece = (string) $pieces->get(0); if (!$meta->children()->contains($piece)) { return false; } $child = $meta->children()->get($piece); $relationship = $child->relationship(); switch ($pieces->count()) { case 2: return $relationship->properties()->contains((string) $pieces->get(1)); case 3: $subPiece = (string) $pieces->get(1); if (!$relationship->childProperty() === $subPiece) { return false; } return $child->properties()->contains((string) $pieces->get(2)); } return false; }
private function isValidProperty(string $property, EntityInterface $meta) : bool { if ($meta->properties()->contains($property)) { return true; } return $meta->startNode()->property() === $property || $meta->endNode()->property() === $property; }
/** * Get value of primary key for given entity * @param \Spot\Entity\EntityInterface $entity Instance of an entity to find the primary key of * @return mixed */ public function getPrimaryKeyValues(EntityInterface $entity) { $values = []; foreach ($this->getPrimaryKeys($entity->toString()) as $pk) { $values[$pk] = $entity->get($pk); } return $values; }
private function makeEntity(EntityInterface $meta, CollectionInterface $data) { $identity = $this->generators->get($meta->identity()->type())->for($data->get($meta->identity()->property())); if ($this->entities->contains($identity)) { return $this->entities->get($identity); } $entity = $this->resolver->get($meta)->make($identity, $meta, $data); $this->entities = $this->entities->push($identity, $entity, Container::STATE_MANAGED); return $entity; }
/** * Return the factory for the given entity definition * * @param EntityInterface $meta * * @return EntityFactoryInterface */ public function get(EntityInterface $meta) : EntityFactoryInterface { $class = (string) $meta->factory(); if ($this->mapping->contains($class)) { return $this->mapping->get($class); } $factory = new $class(); $this->register($factory); return $factory; }
/** * {@inheritdoc} */ public function translate(EntityInterface $meta, SpecificationInterface $specification) : IdentityMatch { try { $mapping = (new RelationshipPropertyMatchVisitor($meta))->visit($specification); $query = $this->addProperties($this->addProperties($this->addProperties((new Query())->match('start'), 'start', $mapping)->linkedTo('end'), 'end', $mapping)->through((string) $meta->type(), 'entity', Relationship::RIGHT), 'entity', $mapping); } catch (SpecificationNotApplicableAsPropertyMatchException $e) { $condition = (new RelationshipCypherVisitor($meta))->visit($specification); $query = (new Query())->match('start')->linkedTo('end')->through((string) $meta->type(), 'entity', Relationship::RIGHT)->where($condition->get(0))->withParameters($condition->get(1)->toPrimitive()); } return new IdentityMatch($query->return('start', 'end', 'entity'), (new Map('string', EntityInterface::class))->put('entity', $meta)); }
/** * Setting an entity object. * * This can be simplified even further, by not accepting an entity name but use the name of the object. I choose * not to do that, to be more consistent in this example. In production code I probably would, however. * * @param $entityName * @param \EntityInterface $object * @return IdentityMap */ public function set($entityName, EntityInterface $object) { if (isset($this->container[$entityName][$object->getId()])) { // At this point, the key already exists, this might be something we want to act against. // To keep it simple, I don't do anything in this example. } // Define an entry, based on the entity name, and the ID (primary key) of the entity $this->container[$entityName][$object->getId()] = $object; // Return this, so that we can easily chain set calls. (Fluent interface) return $this; }
/** * {@inheritdoc} */ public function translate(EntityInterface $meta, IdentityInterface $identity) : IdentityMatch { $query = (new Query())->match('entity', $meta->labels()->toPrimitive())->withProperty($meta->identity()->property(), '{entity_identity}')->withParameter('entity_identity', $identity->value())->with('entity'); $variables = new Set('string'); $meta->children()->foreach(function (string $property, ValueObject $child) use(&$query, &$variables) { $relName = (new Str('entity_'))->append($property); $childName = $relName->append('_')->append($child->relationship()->childProperty()); $variables = $variables->add((string) $relName)->add((string) $childName); $query = $query->match('entity')->linkedTo((string) $childName, $child->labels()->toPrimitive())->through((string) $child->relationship()->type(), (string) $relName, Relationship::LEFT); }); return new IdentityMatch($query->return('entity', ...$variables->toPrimitive()), (new Map('string', EntityInterface::class))->put('entity', $meta)); }
/** * {@inheritdoc} */ public function extract($entity, EntityInterface $meta) : CollectionInterface { if (!$meta instanceof Aggregate) { throw new InvalidArgumentException(); } $data = $this->extractProperties($entity, $meta->properties()); $data = $data->set($id = $meta->identity()->property(), (new ReflectionObject($entity))->extract([$id])->get($id)->value()); $meta->children()->foreach(function (string $property, ValueObject $child) use(&$data, $entity) { $data = $data->set($property, $this->extractRelationship($child, $entity)); }); return $data; }
/** * {@inheritdoc} */ public function extract($entity, EntityInterface $meta) : CollectionInterface { if (!$meta instanceof Relationship) { throw new InvalidArgumentException(); } $refl = new ReflectionObject($entity); $data = $refl->extract([$id = $meta->identity()->property(), $start = $meta->startNode()->property(), $end = $meta->endNode()->property()]); $data = $data->set($id, $data->get($id)->value())->set($start, $data->get($start)->value())->set($end, $data->get($end)->value()); $meta->properties()->foreach(function (string $name, Property $property) use(&$data, $refl) { $data = $data->set($name, $property->type()->forDatabase($refl->extract([$name])->get($name))); }); return $data; }
/** * {@inheritdoc} */ public function make(IdentityInterface $identity, EntityInterface $meta, CollectionInterface $data) { if (!$meta instanceof Relationship) { throw new InvalidArgumentException(); } $reflection = (new ReflectionClass((string) $meta->class()))->withProperty($meta->identity()->property(), $identity)->withProperty($meta->startNode()->property(), $this->generators->get($meta->startNode()->type())->for($data->get($meta->startNode()->property())))->withProperty($meta->endNode()->property(), $this->generators->get($meta->endNode()->type())->for($data->get($meta->endNode()->property()))); $meta->properties()->foreach(function (string $name, Property $property) use(&$reflection, $data) { if ($property->type()->isNullable() && !$data->hasKey($name)) { return; } $reflection = $reflection->withProperty($name, $property->type()->fromDatabase($data->get($name))); }); return $reflection->buildObject(); }
/** * Update record. * * @param EntityInterface $entity * @return mixed Returns either `FALSE` or {@see \odTimeTracker\Model\ActivityEntity}. */ public function update(EntityInterface $entity) { $sql = <<<EOT UPDATE `{$this->tableName}` SET \t`ProjectId` = :projectId , \t`Name` = :name , \t`Description` = :description , \t`Tags` = :tags , \t`Started` = :started , \t`Stopped` = :stopped WHERE `ActivityId` = :id EOT; $stmt = $this->pdo->prepare($sql); $stmt->bindParam(':id', $entity->getActivityId(), \PDO::PARAM_INT); $stmt->bindParam(':projectId', $entity->getProjectId(), \PDO::PARAM_INT); $stmt->bindParam(':name', $entity->getName(), \PDO::PARAM_STR); $stmt->bindParam(':description', $entity->getDescription(), \PDO::PARAM_STR); $stmt->bindParam(':tags', $entity->getTags(), \PDO::PARAM_STR); $stmt->bindParam(':started', $entity->getStartedRfc3339(), \PDO::PARAM_STR); $stmt->bindParam(':stopped', $entity->getStoppedRfc3339(), \PDO::PARAM_STR); $res = $stmt->execute(); if ($res === false || $stmt->rowCount() !== 1) { return false; } return $entity; }
/** * Compile all permissions using the managed entities permissions as static overrides * * @access private * @return void */ private function refresh() { foreach ($this->entity->getPermissions() as $target => $permissions) { $this->permissions[strtolower($target)] = array_map('strtolower', $permissions); } foreach ($this->permissions as $target => $permissions) { $this->permissions[$target] = array_unique($permissions); } }
private function translateRelationship($identity, EntityInterface $meta, ResultInterface $result) : CollectionInterface { $relationship = $result->relationships()->filter(function (RelationshipInterface $relationship) use($identity, $meta) { $id = $meta->identity()->property(); $properties = $relationship->properties(); return $properties->hasKey($id) && $properties->get($id) === $identity; })->first(); $data = (new Collection([]))->set($meta->identity()->property(), $relationship->properties()->get($meta->identity()->property()))->set($meta->startNode()->property(), $result->nodes()->get($relationship->startNode()->value())->properties()->get($meta->startNode()->target()))->set($meta->endNode()->property(), $result->nodes()->get($relationship->endNode()->value())->properties()->get($meta->endNode()->target())); $meta->properties()->foreach(function (string $name, Property $property) use(&$data, $relationship) { if ($property->type()->isNullable() && !$relationship->properties()->hasKey($name)) { return; } $data = $data->set($name, $relationship->properties()->get($name)); }); return $data; }
/** * {@inheritdoc} */ public function translate(EntityInterface $meta, SpecificationInterface $specification) : IdentityMatch { $variables = new Set('string'); try { $mapping = (new AggregatePropertyMatchVisitor($meta))->visit($specification); $query = $this->addProperties((new Query())->match('entity', $meta->labels()->toPrimitive()), 'entity', $mapping)->with('entity'); $meta->children()->foreach(function (string $property, ValueObject $child) use(&$query, $mapping, &$variables) { $relName = (new Str('entity_'))->append($property); $childName = $relName->append('_')->append($child->relationship()->childProperty()); $variables = $variables->add((string) $relName)->add((string) $childName); $query = $this->addProperties($this->addProperties($query->match('entity')->linkedTo((string) $childName, $child->labels()->toPrimitive()), (string) $childName, $mapping)->through((string) $child->relationship()->type(), (string) $relName, Relationship::LEFT), (string) $relName, $mapping); }); } catch (SpecificationNotApplicableAsPropertyMatchException $e) { $query = (new Query())->match('entity', $meta->labels()->toPrimitive())->with('entity'); $meta->children()->foreach(function (string $property, ValueObject $child) use(&$query, &$variables) { $relName = (new Str('entity_'))->append($property); $childName = $relName->append('_')->append($child->relationship()->childProperty()); $variables = $variables->add((string) $relName)->add((string) $childName); $query = $query->match('entity')->linkedTo((string) $childName, $child->labels()->toPrimitive())->through((string) $child->relationship()->type(), (string) $relName, Relationship::LEFT); }); $condition = (new AggregateCypherVisitor($meta))->visit($specification); $query = $query->where($condition->get(0))->withParameters($condition->get(1)->toPrimitive()); } return new IdentityMatch($query->return('entity', ...$variables->toPrimitive()), (new Map('string', EntityInterface::class))->put('entity', $meta)); }
/** * {@inheritdoc} */ public function make(IdentityInterface $identity, EntityInterface $meta, CollectionInterface $data) { if (!$meta instanceof Aggregate) { throw new InvalidArgumentException(); } $reflection = (new ReflectionClass((string) $meta->class()))->withProperty($meta->identity()->property(), $identity); $meta->properties()->foreach(function (string $name, Property $property) use(&$reflection, $data) { if ($property->type()->isNullable() && !$data->hasKey($name)) { return; } $reflection = $reflection->withProperty($name, $property->type()->fromDatabase($data->get($name))); }); $meta->children()->foreach(function (string $property, ValueObject $meta) use(&$reflection, $data) { $reflection = $reflection->withProperty($property, $this->buildChild($meta, $data)); }); return $reflection->buildObject(); }
private function translateNode($identity, EntityInterface $meta, ResultInterface $result) : CollectionInterface { $node = $result->nodes()->filter(function (NodeInterface $node) use($identity, $meta) { $id = $meta->identity()->property(); $properties = $node->properties(); return $properties->hasKey($id) && $properties->get($id) === $identity; })->first(); $data = (new Collection([]))->set($meta->identity()->property(), $node->properties()->get($meta->identity()->property())); $meta->properties()->foreach(function (string $name, Property $property) use(&$data, $node) { if ($property->type()->isNullable() && !$node->properties()->hasKey($name)) { return; } $data = $data->set($name, $node->properties()->get($name)); }); try { $meta->children()->foreach(function (string $name, ValueObject $meta) use(&$data, $node, $result) { $data = $data->set($name, $this->translateChild($meta, $result, $node)); }); } catch (MoreThanOneRelationshipFoundException $e) { throw $e->on($meta); } return $data; }
public function has(EntityInterface $entity) { return $this->hasEntity($entity->getId()); }
/** * {@inheritdoc} */ public function translate(EntityInterface $meta) : IdentityMatch { $query = (new Query())->match('start')->linkedTo('end')->through((string) $meta->type(), 'entity', Relationship::RIGHT)->return('start', 'end', 'entity'); return new IdentityMatch($query, (new Map('string', EntityInterface::class))->put('entity', $meta)); }
/** * {@inheritdoc} */ public function translate(EntityInterface $meta, IdentityInterface $identity) : IdentityMatch { $query = (new Query())->match('start')->linkedTo('end')->through((string) $meta->type(), 'entity', Relationship::RIGHT)->withProperty($meta->identity()->property(), '{entity_identity}')->withParameter('entity_identity', $identity->value())->return('start', 'end', 'entity'); return new IdentityMatch($query, (new Map('string', EntityInterface::class))->put('entity', $meta)); }
/** * Delete record. * * @param EntityInterface $entity * @return boolean */ public function delete(EntityInterface $entity) { return $this->deleteById($entity->getId()); }
public function remove(EntityInterface $entity) { if (isset($this->entities[$entity->uri()])) { unset($this->entities[$entity->uri()]); } }
/** * Удаление записи * @param EntityInterface $Entity * @return boolean */ public function delete(EntityInterface $Entity) { $result = false; $delete_key = $this->setSoftDeleteKey(); if ($delete_key > '' && $Entity->getId() > 0) { $result = $this->getAdapter()->update($this->getEntityTable(), [$delete_key => 1], "{$this->getPrimaryKey()} = '{$Entity->getId()}'"); } elseif ($Entity->getId() > 0) { if ($result = $this->getAdapter()->delete($this->getEntityTable(), $this->getPrimaryKey() . " = " . $Entity->getId())) { if (method_exists($this, 'onBeforeDelete')) { $result = $this->onBeforeDelete($Entity); } } } return $result; }
/** * @param array $primaryKey * @param EntityInterface $entity * @return boolean * @throws \PDOException */ private function updateExisting(array $primaryKey, EntityInterface $entity) { $query = 'UPDATE `' . $entity->getTableName() . '` SET'; foreach ($entity->getSetKeys() as $field) { $query .= '`' . $field . '` = '; $value = is_null($entity->get($field)) ? 'NULL, ' : '\'' . $entity->get($field) . '\', '; $query .= $value; } $query = substr($query, 0, -2); $query .= ' WHERE '; foreach ($primaryKey as $idx => $key) { $query .= '`' . $idx . '` = \'' . $key . '\' AND '; } $query = substr($query, 0, -5); $query .= ';'; $query = $this->pdo->getPdo()->query($query); if (!$query) { $errorInfo = $this->pdo->getPdo()->errorInfo(); throw new \PDOException($errorInfo[2], $errorInfo[0]); } return $query->execute(); }
/** * DElete entity from DB * @param EntityInterface $entity * @return $this */ public function delete(EntityInterface $entity) { $entity->delete(); return $this; }
/** * Exibe a documentação automática para Entidades. * * Contém os métodos mágicos e é exibida quando o segundo parâmetro enviados ao * phpunit é --stderr desde que o método setUpBeforeClass() do teste seja * implementado conforme exemplo a seguir * * <code> * //... * public static function setUpBeforeClass() * { * self::displayClassDocumentation(new Product()); * } * //... * </code> * * @param EntityInterface $entity [description] */ public static function displayClassDocumentation($entity) { global $argv; if (count($argv) <= 1 || $argv[1] !== '--stderr') { return false; } $docblock = Docblock::getInstance(); $docblock->setResourcesPath(static::getVarPath()); if ($entity instanceof EntityAbstract) { $json = json_encode($entity->toArray(), JSON_PRETTY_PRINT); echo $docblock->generate($entity->toDocBLock(), $json); } else { echo $docblock->generate(); } }
/** * Renders linked resource object. * @param EntityInterface $entity * @param EntityInterface $subEntity * @param Relation $relation * @return array */ protected function renderLinkedResourceObject(EntityInterface $entity, EntityInterface $subEntity, Relation $relation) { $resourceObject = array(); $resourceObject['id'] = (string) $subEntity->getId(); if ($this->attachResourceObjectHref) { $binds = array($this->collectionName => $entity->getId(), $relation->getCollectionName() => $subEntity->getId()); $href = $this->prepareHref($relation->getHref(), $binds); $resourceObject['href'] = $href; } $resourceObject += $subEntity->toArray(); return $resourceObject; }