/** * @param $action * @param \Doctrine\ORM\Mapping\ClassMetadata $meta * @param $entity */ private function logEntityChange($action, \Doctrine\ORM\Mapping\ClassMetadata $meta, $entity) { $userToken = $this->container->get('security.context')->getToken(); if (null !== $userToken) { $this->logger->info('Entity "' . $meta->getTableName() . '" with id: ' . $meta->getFieldValue($entity, $meta->getSingleIdentifierFieldName()) . ' ' . $action . ' by: ' . $this->container->get('security.context')->getToken()->getUsername()); } }
/** * @param string $association * @return Collection * @throws UnexpectedValueException */ protected function getCollectionFromAssociation($association) { $collection = $this->metadata->getFieldValue($this->entity, $association); if ($collection === NULL) { $this->metadata->setFieldValue($this->entity, $association, $collection = new ArrayCollection()); } elseif (!$collection instanceof Collection) { throw UnexpectedValueException::notACollection($this->entity, $association); } return $collection; }
private function defaultDefsFromMetadata() { $defaultEntity = $this->getEntityMetadata()->newInstance(); $allFields = array_merge($this->metadata->getFieldNames(), $this->metadata->getAssociationNames()); foreach ($allFields as $fieldName) { if (!isset($this->fieldDefs[$fieldName])) { $defaultFieldValue = $this->metadata->getFieldValue($defaultEntity, $fieldName); if ($defaultFieldValue !== null) { $this->fieldDefs[$fieldName] = function () use($defaultFieldValue) { return $defaultFieldValue; }; } else { $this->fieldDefs[$fieldName] = function () { return null; }; } } } }
/** * Prepares the data changeset of an entity for database insertion. * * @param object $entity * @param boolean $isInsert Whether the preparation is for an INSERT (or UPDATE, if FALSE). * * return The reference to the data array. * @access private * * @author Etienne de Longeaux <*****@*****.**> */ private function _prepareData($entity, $isInsert = false) { $result = array(); $platform = $this->_conn->getDatabasePlatform(); $uow = $this->_em->getUnitOfWork(); foreach ($this->_reflFields as $field => $ReflectionProperty) { $newVal = $this->_class->getFieldValue($entity, $field); $columnName = $this->_class->getColumnName($field); if (isset($this->_class->associationMappings[$field])) { $assocMapping = $this->_class->associationMappings[$field]; // Only owning side of x-1 associations can have a FK column. if (!$assocMapping['isOwningSide']) { continue; } // Special case: One-one self-referencing of the same class with IDENTITY type key generation. if ($this->_class->isIdGeneratorIdentity() && $newVal !== null && $assocMapping['sourceEntity'] == $assocMapping['targetEntity']) { $oid = spl_object_hash($newVal); $isScheduledForInsert = $uow->isScheduledForInsert($newVal); if (isset($this->_queuedInserts[$oid]) || $isScheduledForInsert) { // The associated entity $newVal is not yet persisted, so we must // set $newVal = null, in order to insert a null value and schedule an // extra update on the UnitOfWork. $uow->scheduleExtraUpdate($entity, array($field => array(null, $newVal))); $newVal = null; } else { if ($isInsert && !$isScheduledForInsert && $uow->getEntityState($newVal) == UnitOfWork::STATE_MANAGED) { // $newVal is already fully persisted. // Schedule an extra update for it, so that the foreign key(s) are properly set. $uow->scheduleExtraUpdate($newVal, array($field => array(null, $entity))); } } } foreach ($assocMapping['sourceToTargetKeyColumns'] as $sourceColumn => $targetColumn) { if ($newVal === null) { $result[$sourceColumn] = null; } else { $otherClass = $this->_em->getClassMetadata($assocMapping['targetEntity']); $result[$sourceColumn] = $otherClass->reflFields[$otherClass->fieldNames[$targetColumn]]->getValue($newVal); } } } else { if ($newVal === null) { $result[$columnName] = null; } else { $result[$columnName] = Type::getType($this->_class->fieldMappings[$field]['type'])->convertToDatabaseValue($newVal, $platform); } } } return $result; }
/** * {@inheritdoc} */ public function writeItem(array $item) { $this->counter++; $entity = null; // If the table was not truncated to begin with, find current entities // first if (false === $this->truncate) { if ($this->index) { // If the table has a composite key if (!empty($this->compositeKey) && is_array($this->compositeKey)) { $composite = ''; foreach ($this->compositeKey as $key => $index) { $composite .= $item[$index]; } $value = $composite; } else { $value = $item[$this->index]; } $entity = $this->entityRepository->findOneBy(array($this->index => $value)); } else { $entity = $this->entityRepository->find(current($item)); } } if (!$entity) { $entity = $this->getNewInstance(); } $fieldNames = array_merge($this->entityMetadata->getFieldNames(), $this->entityMetadata->getAssociationNames()); foreach ($fieldNames as $fieldName) { $value = null; if (isset($item[$fieldName])) { $value = $item[$fieldName]; } elseif (method_exists($item, 'get' . ucfirst($fieldName))) { $value = $item->{'get' . ucfirst($fieldName)}; } if (null === $value) { continue; } if (!$value instanceof \DateTime || $value != $this->entityMetadata->getFieldValue($entity, $fieldName)) { $setter = 'set' . ucfirst($fieldName); $this->setValue($entity, $value, $setter); } } $this->entityManager->persist($entity); if ($this->counter % $this->batchSize == 0) { $this->entityManager->flush(); $this->entityManager->clear($this->entityName); } return $this; }
/** * @param $object * @param $fieldName * @return ArrayCollection|mixed * @throws \NForms\Exceptions\MetadataException */ protected function getCollection($object, $fieldName) { if ($this->isSingleValuedAssociation($fieldName)) { throw new MetadataException("Can't get collection from association toOne."); } $collection = $this->classMetadata->getFieldValue($object, $fieldName); if ($collection === NULL) { $collection = new ArrayCollection(); $this->classMetadata->setFieldValue($object, $fieldName, $collection); } if (!$collection instanceof Collection) { throw new MetadataException('Expected Doctrine\\Common\\Collections\\Collection, given ' . (is_object($collection) ? get_class($collection) : gettype($collection))); } return $collection; }
/** * @param ClassMetadata $meta * @param object $entity * @param string $field * @return bool|object */ private function getRelation(ClassMetadata $meta, $entity, $field) { if (!$meta->hasAssociation($field) || !$meta->isSingleValuedAssociation($field)) { return FALSE; } // todo: allow access using property or method $relation = $meta->getFieldValue($entity, $field); if ($relation instanceof Collection) { return FALSE; } if ($relation === NULL) { $class = $meta->getAssociationTargetClass($field); $relationMeta = $this->mapper->getEntityManager()->getClassMetadata($class); $relation = $relationMeta->newInstance(); $meta->setFieldValue($entity, $field, $relation); } return $relation; }
/** * @param array $item * @param object $entity */ protected function updateEntity(array $item, $entity) { $fieldNames = array_merge($this->entityMetadata->getFieldNames(), $this->entityMetadata->getAssociationNames()); foreach ($fieldNames as $fieldName) { $value = null; if (isset($item[$fieldName])) { $value = $item[$fieldName]; } elseif (method_exists($item, 'get' . ucfirst($fieldName))) { $value = $item->{'get' . ucfirst($fieldName)}; } if (null === $value) { continue; } if (!$value instanceof \DateTime || $value != $this->entityMetadata->getFieldValue($entity, $fieldName)) { $setter = 'set' . ucfirst($fieldName); $this->setValue($entity, $value, $setter); } } }
/** * @param \Doctrine\ORM\Mapping\ClassMetadata $meta * @param \Nette\ComponentModel\Component $component * @param mixed $entity * @return boolean */ public function load(ClassMetadata $meta, Component $component, $entity) { if (!$component instanceof BaseControl) { return false; } $name = $component->getOption(self::FIELD_NAME, $component->getName()); if ($meta->hasField($name)) { $component->setValue($this->accessor->getValue($entity, $name)); return true; } if (!$meta->hasAssociation($name)) { return false; } /** @var SelectBox|RadioList $component */ if (($component instanceof SelectBox || $component instanceof RadioList || $component instanceof \Nette\Forms\Controls\MultiChoiceControl) && !count($component->getItems())) { if (!($nameKey = $component->getOption(self::ITEMS_TITLE, false))) { $path = $component->lookupPath('Nette\\Application\\UI\\Form'); throw new \Kdyby\DoctrineForms\InvalidStateException('Either specify items for ' . $path . ' yourself, or set the option Kdyby\\DoctrineForms\\IComponentMapper::ITEMS_TITLE ' . 'to choose field that will be used as title'); } $criteria = $component->getOption(self::ITEMS_FILTER, array()); $orderBy = $component->getOption(self::ITEMS_ORDER, array()); $related = $this->relatedMetadata($entity, $name); $items = $this->findPairs($related, $criteria, $orderBy, $nameKey); $component->setItems($items); } if ($meta->isCollectionValuedAssociation($name)) { $collection = $meta->getFieldValue($entity, $name); if ($collection instanceof PersistentCollection) { $values = array(); foreach ($collection as $value) { $values[] = $value->getId(); } $component->setDefaultValue($values); } } elseif ($relation = $this->accessor->getValue($entity, $name)) { $UoW = $this->entityManager->getUnitOfWork(); $component->setValue($UoW->getSingleIdentifierValue($relation)); } return true; }
/** * @param object $entity */ private function storeJoinedAssociations($entity) { if ($this->joinedAssociations === null) { $associations = array(); foreach ($this->class->associationMappings as $name => $assoc) { if (isset($assoc['cache']) && $assoc['type'] & ClassMetadata::TO_ONE && ($assoc['fetch'] === ClassMetadata::FETCH_EAGER || !$assoc['isOwningSide'])) { $associations[] = $name; } } $this->joinedAssociations = $associations; } foreach ($this->joinedAssociations as $name) { $assoc = $this->class->associationMappings[$name]; $assocEntity = $this->class->getFieldValue($entity, $name); if ($assocEntity === null) { continue; } $assocId = $this->uow->getEntityIdentifier($assocEntity); $assocKey = new EntityCacheKey($assoc['targetEntity'], $assocId); $assocPersister = $this->uow->getEntityPersister($assoc['targetEntity']); $assocPersister->storeEntityCache($assocEntity, $assocKey); } }
/** * @param object $entity * @return int * @throws \Doctrine\ORM\Mapping\MappingException */ public function update($entity) { $identifiers = []; $types = ['id' => \PDO::PARAM_INT]; foreach ($this->metaData->getIdentifierColumnNames() as $columnName) { $fieldName = $this->metaData->getFieldForColumn($columnName); $value = $this->metaData->getFieldValue($entity, $fieldName); $identifiers[$columnName] = $value; } $updateSet = []; foreach ($this->metaData->getColumnNames() as $columnName) { if (isset($identifiers[$columnName])) { continue; } $fieldName = $this->metaData->getFieldForColumn($columnName); $typeName = $this->metaData->getTypeOfColumn($fieldName); $type = \Doctrine\DBAL\Types\Type::getType($typeName); $value = $type->convertToDatabaseValue($entity->{$fieldName}, $this->em->getConnection()->getDatabasePlatform()); $types[$columnName] = $type->getBindingType(); $updateSet[$columnName] = $value; } return $this->em->getConnection()->update($this->metaData->getTableName(), $updateSet, $identifiers, $types); }
function it_massively_persists_pending_versions($versionBuilder, $versionManager, $normalizer, $connection, $entityManager, $tableNameBuilder, ClassMetadata $versionMetadata, ProductInterface $product1, ProductInterface $product2, Version $pendingVersion1, Version $pendingVersion2, \DateTime $date1, \DateTime $date2) { $products = [$product1, $product2]; $date1->format(\DateTime::ISO8601)->willReturn('2014-07-16T10:20:36+02:00'); $date2->format(\DateTime::ISO8601)->willReturn('2014-07-16T10:20:37+02:00'); $versionManager->getUsername()->willReturn('julia'); $versionManager->getContext()->willReturn('CSV Import'); $normalizedProduct1 = ['sku' => 'sku-001', 'name' => 'my product 1']; $normalizedProduct2 = ['sku' => 'sku-002', 'name' => 'my product 2']; $normalizer->normalize($product1, 'csv', ['versioning' => true])->willReturn($normalizedProduct1); $normalizer->normalize($product2, 'csv', ['versioning' => true])->willReturn($normalizedProduct2); $tableNameBuilder->getTableName('VersionClass')->willReturn('version_table'); $versionMetadata->getColumnNames()->willReturn(['id', 'author', 'changeset', 'snapshot', 'resource_name', 'resource_id', 'context', 'logged_at', 'pending']); $versionMetadata->getFieldName('author')->willReturn('author'); $versionMetadata->getFieldName('changeset')->willReturn('changeset'); $versionMetadata->getFieldName('snapshot')->willReturn('snapshot'); $versionMetadata->getFieldName('resource_name')->willReturn('resourceName'); $versionMetadata->getFieldName('resource_id')->willReturn('resourceId'); $versionMetadata->getFieldName('context')->willReturn('context'); $versionMetadata->getFieldName('logged_at')->willReturn('loggedAt'); $versionMetadata->getFieldName('pending')->willReturn('pending'); $versionMetadata->getIdentifierColumnNames()->willReturn(['id']); $versionMetadata->getFieldValue($pendingVersion1, 'author')->willReturn('julia'); $versionMetadata->getFieldValue($pendingVersion1, 'context')->willReturn('CSV Import'); $versionMetadata->getFieldValue($pendingVersion1, 'changeset')->willReturn(serialize($normalizedProduct1)); $versionMetadata->getFieldValue($pendingVersion1, 'snapshot')->willReturn(null); $versionMetadata->getFieldValue($pendingVersion1, 'resourceName')->willReturn('ProductClass'); $versionMetadata->getFieldValue($pendingVersion1, 'resourceId')->willReturn('myprod1'); $versionMetadata->getFieldValue($pendingVersion1, 'loggedAt')->willReturn($date1); $versionMetadata->getFieldValue($pendingVersion1, 'pending')->willReturn(true); $versionMetadata->getFieldValue($pendingVersion2, 'author')->willReturn('julia'); $versionMetadata->getFieldValue($pendingVersion2, 'context')->willReturn('CSV Import'); $versionMetadata->getFieldValue($pendingVersion2, 'changeset')->willReturn(serialize($normalizedProduct2)); $versionMetadata->getFieldValue($pendingVersion2, 'snapshot')->willReturn(null); $versionMetadata->getFieldValue($pendingVersion2, 'resourceName')->willReturn('ProductClass'); $versionMetadata->getFieldValue($pendingVersion2, 'resourceId')->willReturn('myprod2'); $versionMetadata->getFieldValue($pendingVersion2, 'loggedAt')->willReturn($date2); $versionMetadata->getFieldValue($pendingVersion2, 'pending')->willReturn(true); $entityManager->getClassMetadata('VersionClass')->willReturn($versionMetadata); $versionBuilder->createPendingVersion($product1, 'julia', $normalizedProduct1, 'CSV Import')->willReturn($pendingVersion1); $versionBuilder->createPendingVersion($product2, 'julia', $normalizedProduct2, 'CSV Import')->willReturn($pendingVersion2); $connection->executeQuery('INSERT INTO version_table' . ' (author,changeset,snapshot,resource_name,resource_id,context,logged_at,pending)' . ' VALUES (?,?,?,?,?,?,?,?),(?,?,?,?,?,?,?,?)', ['julia', 'a:2:{s:3:"sku";s:7:"sku-001";s:4:"name";s:12:"my product 1";}', null, 'ProductClass', 'myprod1', 'CSV Import', '2014-07-16 08:20:36', true, 'julia', 'a:2:{s:3:"sku";s:7:"sku-002";s:4:"name";s:12:"my product 2";}', null, 'ProductClass', 'myprod2', 'CSV Import', '2014-07-16 08:20:37', true])->shouldBeCalled(); $this->persistPendingVersions($products); }
/** * @param \Doctrine\ORM\Mapping\ClassMetadata $metadata * @param string $alias * @param object $entity * @param array $mapping * @return array */ private function getSearchInChildrenCondition(ClassMetadata $metadata, $alias, $entity, array $mapping) { $id = $metadata->getFieldValue($entity, $mapping['id']); return ['condition' => "{$alias}.{$mapping['level']} < :level_{$alias}_{$id} AND {$alias}.{$mapping['root']} = :root_{$alias}_{$id} AND {$alias}.{$mapping['left']} < :id_{$alias}_{$id} AND {$alias}.{$mapping['right']} > :id_{$alias}_{$id}", 'parameters' => ["id_{$alias}_{$id}" => $id, "root_{$alias}_{$id}" => $metadata->getFieldValue($entity, $mapping['root']), "level_{$alias}_{$id}" => $metadata->getFieldValue($entity, $mapping['level'])]]; }
/** * Return a related object, or null if not found * @param mixed $record the record where to look at * @param string $name name of the relation * @return mixed */ public function getRelatedRecord($record, $name) { return $this->metadata->getFieldValue($record, $name); }
/** * @param ClassMetadata $meta * @param object $entity * @param string $field * @return Collection */ private function getCollection(ClassMetadata $meta, $entity, $field) { if (!$meta->hasAssociation($field) || $meta->isSingleValuedAssociation($field)) { return FALSE; } $collection = $meta->getFieldValue($entity, $field); if ($collection === NULL) { $collection = new ArrayCollection(); $meta->setFieldValue($entity, $field, $collection); } return $collection; }