protected function createComponentPagination() : Nette\Application\UI\Multiplier { return new Nette\Application\UI\Multiplier(function ($key) : Ytnuk\Orm\Pagination\Control { $control = new Ytnuk\Orm\Pagination\Control($this->entity->getValue($key), is_array(static::$itemsPerPage) ? static::$itemsPerPage[$key] ?? self::$itemsPerPage : static::$itemsPerPage); if ($this->storage) { $control->setCacheStorage($this->storage); } return $control; }); }
/** * Converts IEntity to array * @param IEntity $entity * @param int $type * @param int $recursionLevel * @return array|null */ public static function toArray(IEntity $entity, $type = IEntity::TO_ARRAY_RELATIONSHIP_AS_IS, $recursionLevel = 0) { if ($recursionLevel >= static::$maxRecursionLevel) { return NULL; } $return = []; $metadata = $entity->getMetadata(); foreach ($metadata->getStorageProperties() as $name) { if ($name === 'id' && !$entity->isPersisted()) { $value = NULL; } elseif ($type !== IEntity::TO_ARRAY_LOADED_RELATIONSHIP_AS_IS) { $value = $entity->getValue($name); } else { $property = $entity->getProperty($name); if ($property instanceof IRelationshipContainer) { if (!$property->isLoaded()) { $value = $property->getPrimaryValue(); } else { $value = $entity->getValue($name); } } elseif ($property instanceof IRelationshipCollection) { if (!$property->isLoaded()) { continue; } else { $value = $entity->getValue($name); } } else { $value = $entity->getValue($name); } } if ($value instanceof IEntity) { if ($type === IEntity::TO_ARRAY_RELATIONSHIP_AS_ID) { $value = $value->id; } elseif ($type === IEntity::TO_ARRAY_RELATIONSHIP_AS_ARRAY) { $value = static::toArray($value, $type, $recursionLevel + 1); } } elseif ($value instanceof IRelationshipCollection) { if ($type === IEntity::TO_ARRAY_RELATIONSHIP_AS_ID) { $collection = []; foreach ($value as $collectionEntity) { $collection[] = $collectionEntity->id; } $value = $collection; } elseif ($type === IEntity::TO_ARRAY_RELATIONSHIP_AS_ARRAY) { $collection = []; foreach ($value as $collectionEntity) { $collection[] = static::toArray($collectionEntity, $type, $recursionLevel + 1); } $value = $collection; } } $return[$name] = $value; } return $return; }
protected function getPrimaryValue() { if (!$this->primaryValue && $this->value && $this->value->isPersisted()) { $this->primaryValue = $this->value->getValue('id'); } return $this->primaryValue; }
public function remove(IEntity $parent, array $remove) { $id = $parent->getValue('id'); $data =& $this->mapper->getRelationshipDataStorage($this->metadata->name); foreach ($remove as $removeId) { unset($data[$id][$removeId]); } }
protected function createComponentTranslates(Nextras\Orm\Entity\Reflection\PropertyMetadata $metadata) : Nette\Forms\Container { $translates = $this->addContainer($metadata->name); $localeRepository = $this->model->getRepositoryForEntity(Ytnuk\Translation\Locale\Entity::class); self::$locales ?: (self::$locales = $localeRepository->findAll()->fetchPairs(current($localeRepository->getEntityMetadata()->getPrimaryKey()))); $collection = array_combine(array_map(function (Ytnuk\Translation\Translate\Entity $entity) { return $entity->getRawValue('locale'); }, $collection = iterator_to_array($this->entity->getValue($metadata->name))), $collection); array_walk(self::$locales, function (Ytnuk\Translation\Locale\Entity $locale) use($translates, $collection) { $translate = $collection[$locale->id] ?? new Ytnuk\Translation\Translate\Entity(); $translates->addComponent($component = $this->form->createComponent($translate), $locale->id); if ($component instanceof Nette\Forms\Container) { $component->setCurrentGroup($translates->getCurrentGroup()); $value = $component['value']; if ($value instanceof Nette\Forms\Controls\BaseControl) { $value->caption = NULL; $value->setRequired(FALSE); } unset($component['locale']); $component->addHidden('locale', $locale->id)->setOption('entity', $locale); } }); $parent = $this->lookup(parent::class, FALSE); if ($parent instanceof parent) { $translates->getCurrentGroup()->setOption('label', $parent->formatPropertyLabel($parent->getMetadata()->getProperty($this->getName()))); if (!$parent->getMetadata()->getProperty($this->name)->isNullable && ($containers = iterator_to_array($translates->getComponents(FALSE, Nette\Forms\Container::class)))) { foreach ($containers as $key => $container) { $value = $container['value'] ?? NULL; if ($value instanceof Nette\Forms\Controls\BaseControl) { foreach (array_diff_key($containers, array_flip([$key])) as $sibling) { $value = $value->addConditionOn($sibling['value'], ~Nette\Forms\Form::FILLED); } $value->setRequired(); } } } } return $translates; }
/** * Returns entity relationships as array, 0 => prePersist, 1 => postPersist * @param IEntity $entity * @return array */ public static function getLoadedRelationships(IEntity $entity) { $isPersisted = $entity->isPersisted(); $return = [[], []]; foreach ($entity->getMetadata()->getProperties() as $propertyMeta) { if ($propertyMeta->relationship === NULL) { continue; } $name = $propertyMeta->name; $rawValue = $entity->getRawProperty($name); if (!is_object($rawValue) && ($propertyMeta->isNullable || $isPersisted)) { continue; } $property = $entity->getProperty($name); if ($property instanceof IRelationshipContainer) { if (!$property->isLoaded() && $isPersisted) { continue; } $value = $entity->getValue($name); if ($value) { if ($propertyMeta->relationship->type === PropertyRelationshipMetadata::ONE_HAS_ONE_DIRECTED && !$propertyMeta->relationship->isMain) { $return[1][$name] = $value; } else { $return[0][$name] = $value; } } } elseif ($property instanceof IRelationshipCollection) { if (!$property->isLoaded() && $isPersisted) { continue; } $value = $entity->getValue($name); if ($value) { $return[1][$name] = $value; } } } return $return; }
/** * Converts IEntity to array * @param IEntity $entity * @param int $type * @param int $recursionLevel * @return array|null */ public static function toArray(IEntity $entity, $type = IEntity::TO_ARRAY_RELATIONSHIP_AS_IS, $recursionLevel = 0) { if ($recursionLevel >= static::$maxRecursionLevel) { return null; } $return = []; $metadata = $entity->getMetadata(); foreach ($metadata->getProperties() as $name => $metadataProperty) { if (!$entity->hasValue($name)) { $value = null; } else { $value = $entity->getValue($name); } if ($value instanceof IEntity) { if ($type === IEntity::TO_ARRAY_RELATIONSHIP_AS_ID) { $value = $value->getValue('id'); } elseif ($type === IEntity::TO_ARRAY_RELATIONSHIP_AS_ARRAY) { $value = static::toArray($value, $type, $recursionLevel + 1); } } elseif ($value instanceof IRelationshipCollection) { if ($type === IEntity::TO_ARRAY_RELATIONSHIP_AS_ID) { $collection = []; foreach ($value as $collectionEntity) { $collection[] = $collectionEntity->getValue('id'); } $value = $collection; } elseif ($type === IEntity::TO_ARRAY_RELATIONSHIP_AS_ARRAY) { $collection = []; foreach ($value as $collectionEntity) { $collection[] = static::toArray($collectionEntity, $type, $recursionLevel + 1); } $value = $collection; } } $return[$name] = $value; } return $return; }
protected function createComponentOneHasMany(Nextras\Orm\Entity\Reflection\PropertyMetadata $metadata, int $forceDefault = 0) : Kdyby\Replicator\Container { $repository = $this->model->getRepository($metadata->relationship->repository); $collection = $this->entity->getValue($metadata->name)->get()->fetchPairs(current($repository->getEntityMetadata()->getPrimaryKey())); $replicator = new Kdyby\Replicator\Container(function (Nette\Forms\Container $container) use($metadata, $repository, $collection) { $replicator = $container->parent; $name = $container->getName(); unset($container->parent[$name]); if (!($entity = $collection[$name] ?? NULL)) { $entityClassName = $repository->getEntityMetadata()->getClassName(); $entity = new $entityClassName(); } $replicator->addComponent($container = $this->form->createComponent($entity), $name); if ($container instanceof Nette\Forms\Container) { call_user_func([$container->addSubmit('delete', $this->formatPropertyAction($metadata, 'delete')), 'addRemoveOnClick'], function (Kdyby\Replicator\Container $replicator, self $container) { $container->removeEntity(TRUE); }); } }); $add = $replicator->addSubmit('add', $this->formatPropertyAction($metadata, 'add')); call_user_func([$add, 'addCreateOnClick']); $add->setValidationScope([$replicator]); $replicator->setCurrentGroup($this->getForm()->addGroup($this->prefixPropertyGroup($metadata), FALSE)->add($add)); $this[$metadata->name] = $replicator; if ($createDefault = max(count($collection), $forceDefault)) { if (!$this->getForm()->isSubmitted()) { $count = 0; while ($count++ < $createDefault) { $replicator->createOne(key($collection)); next($collection); } } elseif ($forceDefault) { while (iterator_count($replicator->getContainers()) < $createDefault) { $replicator->createOne(); } } } if ($add->isSubmittedBy()) { $isValid = TRUE; if ($scope = $add->getValidationScope()) { $isValid = !array_filter($scope, function (Nette\Forms\Container $container) { return !$container->isValid(); }); } if ($isValid) { $add->setValidationScope(FALSE); } $add->click(); $add->onClick = []; } $containers = []; foreach ($replicator->getContainers() as $container) { $delete = $container['delete'] ?? NULL; if ($delete instanceof Nette\Forms\Controls\SubmitButton && !$delete->isSubmittedBy()) { $containers[$container->name] = $container; } } if (count($containers) <= $forceDefault) { array_map(function (self $container) { unset($container['delete']); }, $containers); } else { $persistedContainers = array_filter($containers, function (self $container) { return $container->getEntity()->isPersisted(); }); if (count($persistedContainers) <= $forceDefault) { array_map(function (self $container) { unset($container['delete']); }, $persistedContainers); } } foreach ($containers as $key => $container) { if ($container instanceof Nette\ComponentModel\IContainer) { foreach ($container->getComponents(FALSE, Nette\Forms\Controls\BaseControl::class) as $control) { if ($control instanceof Nette\Forms\Controls\BaseControl && ($unique = $control->getOption('unique'))) { foreach (array_diff_key($containers, [$key => $container]) as $sibling) { $condition = $control->addCondition(Nette\Forms\Form::FILLED); if (is_string($unique) && isset($sibling[$unique]) && ($uniqueControl = $container[$unique] ?? NULL)) { if ($uniqueControl instanceof Nette\Forms\IControl) { $condition = $condition->addConditionOn($uniqueControl, Nette\Forms\Form::EQUAL, $sibling[$unique]); } } $condition->addRule(Nette\Forms\Form::NOT_EQUAL, NULL, $sibling[$control->name]); } } } } } return $replicator; }
protected function buildList(IEntity $parent, array $entries) { if (!$this->metadata->relationship->isMain) { throw new LogicException('ManyHasMany relationship has to be persited in the primary mapper.'); } $list = []; $primaryId = $parent->getValue('id'); foreach ($entries as $id) { $list[] = [$this->primaryKeyFrom => $primaryId, $this->primaryKeyTo => $id]; } return $list; }
/** * @param IEntity $entity * @param PropertyMetadata[] $metadata * @parma IModel $model * @param array $pre */ private static function setNulls($entity, array $metadata, IModel $model, array &$pre) { foreach ($metadata as $propertyMeta) { $type = $propertyMeta->relationship->type; $name = $propertyMeta->name; $reverseRepository = $model->getRepository($propertyMeta->relationship->repository); $reverseProperty = $propertyMeta->relationship->property ? $reverseRepository->getEntityMetadata()->getProperty($propertyMeta->relationship->property) : null; if ($type === Relationship::MANY_HAS_MANY) { /** @var ManyHasMany $property */ $property = $entity->getProperty($name); $pre[] = $property; if ($reverseProperty !== null) { foreach ($property as $reverseEntity) { $pre[] = $reverseEntity->getProperty($reverseProperty->name); } } $entity->setValue($name, []); } elseif ($type === Relationship::MANY_HAS_ONE || $type === Relationship::ONE_HAS_ONE && $propertyMeta->relationship->isMain) { /** @var ManyHasOne|OneHasOne $property */ $property = $entity->getProperty($name); if ($reverseProperty !== null && $entity->hasValue($name)) { $pre[] = $entity->getValue($name)->getProperty($reverseProperty->name); } $property->set(null, true); } else { // $type === Relationship::ONE_HAS_MANY or // $type === Relationship::ONE_HAS_ONE && !$isMain if (!$entity->hasValue($name) || $reverseProperty === null) { continue; } if ($reverseProperty->isNullable) { if ($type === Relationship::ONE_HAS_MANY) { foreach ($entity->getValue($name) as $subValue) { $pre[] = $subValue; } $entity->setValue($name, []); } else { $pre[] = $entity->getValue($name); $entity->getProperty($name)->set(null, true); } } else { if ($type === Relationship::ONE_HAS_MANY && $entity->getValue($name)->count() === 0) { continue; } $entityClass = get_class($entity); $reverseEntityClass = $propertyMeta->relationship->entity; $primaryValue = $entity->getValue('id'); $primaryValue = is_array($primaryValue) ? '[' . implode(', ', $primaryValue) . ']' : $primaryValue; throw new InvalidStateException("Cannot remove {$entityClass}::\$id={$primaryValue} because {$reverseEntityClass}::\${$reverseProperty->name} cannot be a null."); } } } }
protected function executeCounts(DbalCollection $collection, IEntity $parent) { $builder = $collection->getQueryBuilder(); $preloadIterator = $parent->getPreloadContainer(); $values = $preloadIterator ? $preloadIterator->getPreloadValues('id') : [$parent->getValue('id')]; $cacheKey = $this->calculateCacheKey($builder, $values); $data =& $this->cacheCounts[$cacheKey]; if ($data !== null) { return $data; } $data = $this->fetchCounts($builder, $values); return $data; }
protected function calculateCacheKey(QueryBuilder $builder, IEntityPreloadContainer $preloadIterator = NULL, IEntity $parent) { return md5($builder->getQuerySQL() . json_encode($builder->getQueryParameters()) . ($preloadIterator ? $preloadIterator->getIdentification() : json_encode($parent->getValue('id')))); }
protected function entityToArray(IEntity $entity) { $return = []; $metadata = $entity->getMetadata(); foreach ($metadata->getProperties() as $name => $metadataProperty) { if ($metadataProperty->isVirtual) { continue; } elseif ($metadataProperty->isPrimary && !$entity->hasValue($name)) { continue; } $property = $entity->getProperty($name); if ($property instanceof IRelationshipCollection) { continue; } if ($property instanceof IProperty) { $value = $property->getRawValue(); } else { $value = $entity->getValue($name); } $return[$name] = $value; } return $return; }
protected function entityToArray(IEntity $entity) { $return = []; $metadata = $entity->getMetadata(); foreach ($metadata->getProperties() as $name => $metadataProperty) { if ($metadataProperty->isVirtual) { continue; } if ($metadataProperty->relationship !== NULL) { $rel = $metadataProperty->relationship; $canSkip = $rel->type === PropertyRelationshipMetadata::ONE_HAS_MANY || $rel->type === PropertyRelationshipMetadata::MANY_HAS_MANY || $rel->type === PropertyRelationshipMetadata::ONE_HAS_ONE_DIRECTED && !$rel->isMain; if ($canSkip) { continue; } } $property = $entity->getProperty($name); if ($property instanceof IProperty) { $value = $property->getRawValue(); } else { $value = $entity->getValue($name); } $return[$name] = $value; } return $return; }
/** * @param IEntity $entity * @param PropertyMetadata[] $metadata * @parma IModel $model * @param array $pre */ private static function setNulls($entity, array $metadata, IModel $model, array &$pre) { foreach ($metadata as $propertyMeta) { $type = $propertyMeta->relationship->type; $name = $propertyMeta->name; if ($type === Relationship::MANY_HAS_MANY) { $entity->setValue($name, []); } elseif ($type === Relationship::MANY_HAS_ONE || $type === Relationship::ONE_HAS_ONE && $propertyMeta->relationship->isMain) { $entity->getProperty($name)->set(NULL, TRUE); } else { // $type === Relationship::ONE_HAS_MANY or // $type === Relationship::ONE_HAS_ONE && !$isPrimary $reverseRepository = $model->getRepository($propertyMeta->relationship->repository); $reverseProperty = $reverseRepository->getEntityMetadata()->getProperty($propertyMeta->relationship->property); if ($reverseProperty->isNullable) { if ($entity->hasValue($name)) { if ($type === Relationship::ONE_HAS_MANY) { foreach ($entity->getValue($name) as $subValue) { $pre[] = $subValue; } $entity->getValue($name)->set([]); } else { $pre[] = $entity->getValue($name); $entity->setValue($name, NULL); } } } else { $entityClass = get_class($entity); $reverseEntityClass = $propertyMeta->relationship->entity; $primaryValue = $entity->getValue('id'); $primaryValue = is_array($primaryValue) ? '[' . implode(', ', $primaryValue) . ']' : $primaryValue; throw new InvalidStateException("Cannot remove {$entityClass}::\$id={$primaryValue} because {$reverseEntityClass}::\${$reverseProperty->name} cannot be a null."); } } } }
public function getIterator(IEntity $parent, ICollection $collection) { $data = $collection->findBy(["this->{$this->joinStorageKey}->id" => $parent->getValue('id')])->fetchAll(); return new EntityIterator($data); }
protected static function addRelationshipToQueue(IEntity $entity, PropertyMetadata $propertyMeta, IModel $model) { $isPersisted = $entity->isPersisted(); $rawValue = $entity->getRawProperty($propertyMeta->name); if ($rawValue === null && ($propertyMeta->isNullable || $isPersisted)) { return; } elseif (!$entity->getProperty($propertyMeta->name)->isLoaded() && $isPersisted) { return; } $value = $entity->getValue($propertyMeta->name); $rel = $propertyMeta->relationship; if ($value instanceof IEntity && !$value->isPersisted() && ($rel->type !== Relationship::ONE_HAS_ONE || $rel->isMain)) { self::visitEntity($value, $model); } elseif ($value !== null) { self::$inputQueue[] = $value; } }
protected function entityToArray(IEntity $entity) { $return = []; $metadata = $entity->getMetadata(); foreach ($metadata->getProperties() as $name => $metadataProperty) { if ($metadataProperty->isVirtual) { continue; } elseif ($metadataProperty->isPrimary && ($entity->isPersisted() || !$entity->hasValue($name))) { continue; } elseif ($entity->isPersisted() && !$entity->isModified($name)) { continue; } if ($metadataProperty->relationship !== null) { $rel = $metadataProperty->relationship; $canSkip = $rel->type === Relationship::ONE_HAS_MANY || $rel->type === Relationship::MANY_HAS_MANY || $rel->type === Relationship::ONE_HAS_ONE && !$rel->isMain; if ($canSkip) { continue; } } $property = $entity->getProperty($name); if ($property instanceof IProperty) { $value = $property->getRawValue(); } else { $value = $entity->getValue($name); } $return[$name] = $value; } return $return; }
public function persist(IEntity $entity) { if (!$entity->isModified()) { $entity->id; } $this->beginTransaction(); $id = $entity->getValue('id', TRUE); $data = $entity->toArray(IEntity::TO_ARRAY_LOADED_RELATIONSHIP_AS_IS); $storageProperties = $entity->getMetadata()->getStorageProperties(); foreach ($data as $key => $value) { if (!in_array($key, $storageProperties, TRUE) || $value instanceof IRelationshipCollection) { unset($data[$key]); } if ($value instanceof IEntity) { $data[$key] = $value->id; } } unset($data['id']); $data = $this->getStorageReflection()->convertEntityToStorage($data); if (!$entity->isPersisted()) { $this->databaseContext->query('INSERT INTO ' . $this->getTableName() . ' ', $data); if ($id) { return $id; } else { return $this->databaseContext->getInsertId($this->databaseStructure->getPrimaryKeySequence($this->getTableName())); } } else { $primary = []; $id = (array) $id; foreach ($this->getStorageReflection()->getStoragePrimaryKey() as $key) { $primary[$key] = array_shift($id); } $this->databaseContext->query('UPDATE ' . $this->getTableName() . ' SET', $data, 'WHERE ?', $primary); return $entity->id; } }