/** * convert foreign identifiers into scalar foreign key values to avoid object to string conversion failures. * * @param ClassMetadata $class * @param array $id * * @return array */ public function flattenIdentifier(ClassMetadata $class, array $id) { $flatId = array(); foreach ($class->identifier as $field) { if (isset($class->associationMappings[$field]) && isset($id[$field]) && is_object($id[$field])) { /* @var $targetClassMetadata ClassMetadata */ $targetClassMetadata = $this->metadataFactory->getMetadataFor($class->associationMappings[$field]['targetEntity']); if ($this->unitOfWork->isInIdentityMap($id[$field])) { $associatedId = $this->flattenIdentifier($targetClassMetadata, $this->unitOfWork->getEntityIdentifier($id[$field])); } else { $associatedId = $this->flattenIdentifier($targetClassMetadata, $targetClassMetadata->getIdentifierValues($id[$field])); } $flatId[$field] = implode(' ', $associatedId); } elseif (isset($class->associationMappings[$field])) { $associatedId = array(); foreach ($class->associationMappings[$field]['joinColumns'] as $joinColumn) { $associatedId[] = $id[$joinColumn['name']]; } $flatId[$field] = implode(' ', $associatedId); } else { $flatId[$field] = $id[$field]; } } return $flatId; }
public function testSourceModified() { $changeset = ['datetimeLastVisited' => [null, new \DateTime()], 'data' => [null, ['foo' => 'bar']]]; $this->uow->expects($this->once())->method('getEntityChangeSet')->will($this->returnValue($changeset)); $listener = new SourceModificationListenerMock($this->sourceProcessor, $this->queueManager); $this->assertTrue($listener->visibleIsSourceModified(new SourceMock(12345), $this->uow)); }
function it_clears_the_import_cache(DoctrineCache $doctrineCache, EntityManager $entityManager, UnitOfWork $uow) { $this->setNonClearableEntities(['NonClearable']); $uow->getIdentityMap()->willReturn(['NonClearable' => [], 'Clearable' => []]); $entityManager->clear('Clearable')->shouldBeCalled(); $doctrineCache->clear(['NonClearable'])->shouldBeCalled(); $this->clear(); }
public function testRetrieveUserTracker() { $user = new User(); $tracker = $this->tracker(); $this->em->expects($this->once())->method('getUnitOfWork')->will($this->returnValue($this->unitOfWork)); $this->unitOfWork->expects($this->once())->method('getEntityPersister')->with(self::CLASS_NAME)->will($this->returnValue($this->entityPersister)); $this->entityPersister->expects($this->once())->method('load')->with(['user' => $user], null, null, [], 0, 1, null)->will($this->returnValue($tracker)); $this->repository->retrieveUserTracker($user); }
/** * Check if entity is in a valid state for operations. * * @param object $entity * * @return bool */ protected function isValidEntityState($entity) { $entityState = $this->uow->getEntityState($entity, UnitOfWork::STATE_NEW); if ($entityState === UnitOfWork::STATE_NEW) { return false; } // If Entity is scheduled for inclusion, it is not in this collection. // We can assure that because it would have return true before on array check return !($entityState === UnitOfWork::STATE_MANAGED && $this->uow->isScheduledForInsert($entity)); }
/** * @test */ public function thatApiUserRetrievesByUsername() { $email = '*****@*****.**'; $apiUser = $this->getApiUser(); $this->em->expects($this->once())->method('getUnitOfWork')->will($this->returnValue($this->unitOfWork)); $this->unitOfWork->expects($this->once())->method('getEntityPersister')->with($this->equalTo(self::DUMMY_CLASS_NAME))->will($this->returnValue($this->entityPersister)); $this->entityPersister->expects($this->once())->method('load')->with($this->equalTo(array('email' => $email)), $this->equalTo(null), $this->equalTo(null), array(), $this->equalTo(0), $this->equalTo(1), $this->equalTo(null))->will($this->returnValue($apiUser)); $retrievedApiUser = $this->repository->findOneBy(array('email' => $email)); $this->assertNotNull($retrievedApiUser); $this->assertEquals($apiUser, $retrievedApiUser); }
public function testFindAllByTicket() { $messageReference = $this->getMessageReference(); $ticket = $messageReference->getTicket(); $references = array($messageReference); $this->em->expects($this->once())->method('getUnitOfWork')->will($this->returnValue($this->unitOfWork)); $this->unitOfWork->expects($this->once())->method('getEntityPersister')->with($this->equalTo(self::DUMMY_CLASS_NAME))->will($this->returnValue($this->entityPersister)); $this->entityPersister->expects($this->once())->method('loadAll')->with($this->equalTo(array('ticket' => $ticket)), null, null, null)->will($this->returnValue($references)); $result = $this->repository->findAllByTicket($ticket); $this->assertEquals($references, $result); }
/** * @test */ public function thatBranchEmailConfigurationRetrievesByBranchId() { $branchId = 1; $branchEmailConfiguration = $this->getBranchEmailConfiguartion(); $this->em->expects($this->once())->method('getUnitOfWork')->will($this->returnValue($this->unitOfWork)); $this->unitOfWork->expects($this->once())->method('getEntityPersister')->with($this->equalTo(self::DUMMY_CLASS_NAME))->will($this->returnValue($this->entityPersister)); $this->entityPersister->expects($this->once())->method('load')->with($this->equalTo(array('branchId' => $branchId)), $this->equalTo(null), $this->equalTo(null), array(), $this->equalTo(0), $this->equalTo(1), $this->equalTo(null))->will($this->returnValue($branchEmailConfiguration)); $retrievedBranchEmailConfiguration = $this->repository->findOneBy(array('branchId' => $branchId)); $this->assertNotNull($retrievedBranchEmailConfiguration); $this->assertEquals($branchEmailConfiguration, $retrievedBranchEmailConfiguration); }
/** * Get an array describing the changes. * * @param UnitOfWork $unitOfWork * @param TermOfUse $entity * @param string $action * * @return array */ protected function getChangeSet(UnitOfWork $unitOfWork, TermOfUse $entity, $action) { switch ($action) { case 'create': return array('id' => array(null, $entity->getId()), 'weight' => array(null, $entity->getWeight()), 'keyCode' => array(null, $entity->getKeyCode()), 'langCode' => array(null, $entity->getLangCode()), 'content' => array(null, $entity->getContent()), 'created' => array(null, $entity->getCreated()), 'updated' => array(null, $entity->getUpdated())); case 'update': return $unitOfWork->getEntityChangeSet($entity); case 'delete': return array('id' => array($entity->getId(), null), 'weight' => array($entity->getWeight(), null), 'keyCode' => array($entity->getKeyCode(), null), 'langCode' => array($entity->getLangCode(), null), 'content' => array($entity->getContent(), null), 'created' => array($entity->getCreated(), null), 'updated' => array($entity->getUpdated(), null)); } }
public function onFlush(OnFlushEventArgs $e) { $this->init($e); foreach ($this->uow->getScheduledEntityInsertions() as $entity) { if ($entity instanceof RoundedEntityInterface) { $entity->setRound($this->round); $this->uow->recomputeSingleEntityChangeSet($this->em->getClassMetadata(get_class($entity)), $entity); } } //$this->uow->computeChangeSets(); }
/** * @param $emailField * @param mixed $entity * @param EmailOwnerInterface $owner * @param EntityManager $em * @param UnitOfWork $uow */ protected function processInsertionOrUpdateEntity($emailField, $entity, EmailOwnerInterface $owner, EntityManager $em, UnitOfWork $uow) { if (!empty($emailField)) { foreach ($uow->getEntityChangeSet($entity) as $field => $vals) { if ($field === $emailField) { list($oldValue, $newValue) = $vals; if ($newValue !== $oldValue) { $this->bindEmailAddress($em, $owner, $newValue, $oldValue); } } } } }
public function setUp() { $this->em = $this->getMockBuilder('Doctrine\\ORM\\EntityManager')->disableOriginalConstructor()->getMock(); $this->uow = $this->getMockBuilder('Doctrine\\ORM\\UnitOfWork')->disableOriginalConstructor()->getMock(); $this->persister = $this->getMockBuilder('Doctrine\\ORM\\Persisters\\BasicEntityPersister')->disableOriginalConstructor()->getMock(); $this->em->expects($this->any())->method('getUnitOfWork')->will($this->returnValue($this->uow)); $this->uow->expects($this->any())->method('getEntityPersister')->with('stdClass')->will($this->returnValue($this->persister)); $this->entity = new stdClass(); $metadata = new ClassMetadata('stdClass'); $metadata->fieldMappings = array('property' => 'property'); $metadata->identifier = array('id'); $this->repository = new EntityRepository($this->em, $metadata); }
/** * @param Object $entity * @return string */ public function transform($entity) { if (null === $entity || '' === $entity) { return 'null'; } if (!is_object($entity)) { throw new UnexpectedTypeException($entity, 'object'); } if (!$this->unitOfWork->isInIdentityMap($entity)) { throw new InvalidArgumentException('Entities passed to the choice field must be managed'); } return $entity->getId(); }
/** * convert foreign identifiers into scalar foreign key values to avoid object to string conversion failures. * * @param \Doctrine\ORM\Mapping\ClassMetadata $class * @param array $id * @return array */ public function flattenIdentifier(ClassMetadata $class, array $id) { $flatId = array(); foreach ($id as $idField => $idValue) { if (isset($class->associationMappings[$idField]) && is_object($idValue)) { $targetClassMetadata = $this->metadataFactory->getMetadataFor($class->associationMappings[$idField]['targetEntity']); $associatedId = $this->unitOfWork->getEntityIdentifier($idValue); $flatId[$idField] = $associatedId[$targetClassMetadata->identifier[0]]; } else { $flatId[$idField] = $idValue; } } return $flatId; }
/** * @param EntityManager $em * @param UnitOfWork $uow * @param User $entity * @param Organization $organization */ protected function createCalendar($em, $uow, $entity, $organization) { // create a default calendar for assigned organization $calendar = new Calendar(); $calendar->setOwner($entity); $calendar->setOrganization($organization); // connect the calendar to itself $calendarConnection = new CalendarConnection($calendar); $calendar->addConnection($calendarConnection); $em->persist($calendar); $em->persist($calendarConnection); $uow->computeChangeSet($this->getClassMetadata($calendar, $em), $calendar); $uow->computeChangeSet($this->getClassMetadata($calendarConnection, $em), $calendarConnection); }
/** * Deletes an entity if it is in relation to another entity * * Doctrine is obviously unable to entities detached from the relational entity when merging the relational entity, * so this had to be implemented. * * @param object $relationalEntity * @param string $fieldName * @param ClassMetadata $metadata * @param boolean $recomputeChangeSet */ public function deleteOnRelationalModification($relationalEntity, $fieldName, ClassMetadata $metadata, $recomputeChangeSet = true) { if ($recomputeChangeSet) { $this->unitOfWork->computeChangeSet($metadata, $relationalEntity); } $changeSet = $this->unitOfWork->getEntityChangeSet($relationalEntity); if (!isset($changeSet[$fieldName])) { return; } $orgValue = $changeSet[$fieldName][0]; if (null !== $orgValue && $this->entityManager->contains($orgValue)) { $this->entityManager->remove($orgValue); } }
/** * @param Ticket $ticket */ protected function startAutoReply(Ticket $ticket) { $ticketText = $ticket->getSubject() . ' ' . $ticket->getDescription(); $repository = $this->registry->getManager()->getRepository('DiamanteDeskBundle:Article'); $results = []; /** @var Article $article */ foreach ($repository->findByStatus(1) as $article) { $articleText = $article->getTitle() . ' ' . $article->getContent(); $results[$article->getId()] = $this->compare($ticketText, $articleText); } $maxResult = max($results); /** * TODO: should be configured by admin */ if ($maxResult < 3) { return; } $articleId = array_search(max($results), $results); /** * TODO: should be extracted from previous call of $repository->getAll() */ $article = $repository->find($articleId); /** * TODO: should be extracted from configuration??? */ $user = User::fromString('oro_1'); $content = $this->getAutoReplayNoticeHtml() . $article->getContent(); $comment = new Comment($content, $ticket, $user, false); $this->registry->getManager()->persist($comment); $this->uow->computeChangeSet($this->em->getClassMetadata($comment->getClassName()), $comment); /** * TODO: should be executed workflowEven? */ }
/** * {@inheritdoc} */ public function loadCacheEntry(ClassMetadata $metadata, EntityCacheKey $key, EntityCacheEntry $entry, $entity = null) { $data = $entry->data; $hints = self::$hints; if ($entity !== null) { $hints[Query::HINT_REFRESH] = true; $hints[Query::HINT_REFRESH_ENTITY] = $entity; } foreach ($metadata->associationMappings as $name => $assoc) { if (!isset($assoc['cache']) || !isset($data[$name])) { continue; } $assocClass = $data[$name]->class; $assocId = $data[$name]->identifier; $isEagerLoad = $assoc['fetch'] === ClassMetadata::FETCH_EAGER || $assoc['type'] === ClassMetadata::ONE_TO_ONE && !$assoc['isOwningSide']; if (!$isEagerLoad) { $data[$name] = $this->em->getReference($assocClass, $assocId); continue; } $assocKey = new EntityCacheKey($assoc['targetEntity'], $assocId); $assocPersister = $this->uow->getEntityPersister($assoc['targetEntity']); $assocRegion = $assocPersister->getCacheRegion(); $assocEntry = $assocRegion->get($assocKey); if ($assocEntry === null) { return null; } $data[$name] = $this->uow->createEntity($assocEntry->class, $assocEntry->resolveAssociationEntries($this->em), $hints); } if ($entity !== null) { $this->uow->registerManaged($entity, $key->identifier, $data); } $result = $this->uow->createEntity($entry->class, $data, $hints); $this->uow->hydrationComplete(); return $result; }
/** * @param B2bCustomer $b2bCustomer */ protected function scheduleUpdate(B2bCustomer $b2bCustomer) { if ($this->uow->isScheduledForDelete($b2bCustomer)) { return; } $this->queued[$b2bCustomer->getId()] = $b2bCustomer; }
/** * @param \Doctrine\ORM\Cache\QueryCacheKey $key * @param array $assoc * @param mixed $assocValue * * @return array|null */ private function storeAssociationCache(QueryCacheKey $key, array $assoc, $assocValue) { $assocPersister = $this->uow->getEntityPersister($assoc['targetEntity']); $assocMetadata = $assocPersister->getClassMetadata(); $assocRegion = $assocPersister->getCacheRegion(); // Handle *-to-one associations if ($assoc['type'] & ClassMetadata::TO_ONE) { $assocIdentifier = $this->uow->getEntityIdentifier($assocValue); $entityKey = new EntityCacheKey($assocMetadata->rootEntityName, $assocIdentifier); if (!$assocValue instanceof Proxy && $key->cacheMode & Cache::MODE_REFRESH || !$assocRegion->contains($entityKey)) { // Entity put fail if (!$assocPersister->storeEntityCache($assocValue, $entityKey)) { return null; } } return ['targetEntity' => $assocMetadata->rootEntityName, 'identifier' => $assocIdentifier, 'type' => $assoc['type']]; } // Handle *-to-many associations $list = []; foreach ($assocValue as $assocItemIndex => $assocItem) { $assocIdentifier = $this->uow->getEntityIdentifier($assocItem); $entityKey = new EntityCacheKey($assocMetadata->rootEntityName, $assocIdentifier); if ($key->cacheMode & Cache::MODE_REFRESH || !$assocRegion->contains($entityKey)) { // Entity put fail if (!$assocPersister->storeEntityCache($assocItem, $entityKey)) { return null; } } $list[$assocItemIndex] = $assocIdentifier; } return ['targetEntity' => $assocMetadata->rootEntityName, 'type' => $assoc['type'], 'list' => $list]; }
/** * @param ClassMetadata $class * @param array $entityData * @param string $revType */ private function saveRevisionEntityData($class, $entityData, $revType) { $params = array($this->getRevisionId(), $revType); $types = array(\PDO::PARAM_INT, \PDO::PARAM_STR); $fields = array(); foreach ($class->associationMappings as $field => $assoc) { if (($assoc['type'] & ClassMetadata::TO_ONE) > 0 && $assoc['isOwningSide']) { $targetClass = $this->em->getClassMetadata($assoc['targetEntity']); if ($entityData[$field] !== null) { $relatedId = $this->uow->getEntityIdentifier($entityData[$field]); } $targetClass = $this->em->getClassMetadata($assoc['targetEntity']); foreach ($assoc['sourceToTargetKeyColumns'] as $sourceColumn => $targetColumn) { $fields[$sourceColumn] = true; if ($entityData[$field] === null) { $params[] = null; $types[] = \PDO::PARAM_STR; } else { $params[] = $relatedId[$targetClass->fieldNames[$targetColumn]]; $types[] = $targetClass->getTypeOfColumn($targetColumn); } } } } foreach ($class->fieldNames as $field) { if (array_key_exists($field, $fields)) { continue; } $params[] = $entityData[$field]; $types[] = $class->fieldMappings[$field]['type']; } $this->conn->executeUpdate($this->getInsertRevisionSQL($class), $params, $types); }
/** * Computes or re-computes changes of given entity. * * @param $entity * * @author Andreas Glaser */ protected function computeChangeSet($entity) { if ($this->unitOfWork->getEntityChangeSet($entity)) { $this->unitOfWork->recomputeSingleEntityChangeSet($this->entityManager->getClassMetadata(get_class($entity)), $entity); } else { $this->unitOfWork->computeChangeSet($this->entityManager->getClassMetadata(get_class($entity)), $entity); } }
/** * @test */ public function thatGetsAll() { $entities = array(new EntityStub(), new EntityStub()); $this->em->expects($this->once())->method('getUnitOfWork')->will($this->returnValue($this->unitOfWork)); $this->unitOfWork->expects($this->once())->method('getEntityPersister')->with($this->equalTo(self::CLASS_NAME))->will($this->returnValue($this->entityPersister)); $this->entityPersister->expects($this->once())->method('loadAll')->with($this->equalTo(array()), $this->equalTo(null), $this->equalTo(null), $this->equalTo(null))->will($this->returnValue($entities)); $retrievedEntities = $this->repository->getAll(); $this->assertEquals($entities, $retrievedEntities); }
/** * {@inheritdoc} */ public function loadCacheEntry(ClassMetadata $metadata, CollectionCacheKey $key, CollectionCacheEntry $entry, PersistentCollection $collection) { $assoc = $metadata->associationMappings[$key->association]; $targetPersister = $this->uow->getEntityPersister($assoc['targetEntity']); $targetRegion = $targetPersister->getCacheRegion(); $list = array(); foreach ($entry->identifiers as $index => $identifier) { $entityEntry = $targetRegion->get(new EntityCacheKey($assoc['targetEntity'], $identifier)); if ($entityEntry === null) { return null; } $list[$index] = $this->uow->createEntity($entityEntry->class, $entityEntry->data, self::$hints); } array_walk($list, function ($entity, $index) use($collection) { $collection->hydrateSet($index, $entity); }); return $list; }
/** * @param PersistentCollection $collection */ public function loadCollection(PersistentCollection $collection) { parent::loadCollection($collection); $em = $this->getParentEntityManager(); foreach ($collection->toArray() as $element) { $postLazyloadEventArgs = new PostLazyLoadEventArgs($em, $element); $em->getEventManager()->dispatchEvent(PostLazyLoadEventArgs::EVENT_NAME, $postLazyloadEventArgs); } }
/** * Collect updated activities * * @param UnitOfWork $uof */ protected function collectUpdates(UnitOfWork $uof) { $entities = $uof->getScheduledEntityUpdates(); foreach ($entities as $hash => $entity) { if ($this->activityListManager->isSupportedEntity($entity) && empty($this->updatedEntities[$hash])) { $this->updatedEntities[$hash] = $entity; } } $updatedCollections = array_merge($uof->getScheduledCollectionUpdates(), $uof->getScheduledCollectionDeletions()); foreach ($updatedCollections as $hash => $collection) { /** @var $collection PersistentCollection */ $ownerEntity = $collection->getOwner(); $entityHash = spl_object_hash($ownerEntity); if ($this->activityListManager->isSupportedEntity($ownerEntity) && $this->doctrineHelper->getSingleEntityIdentifier($ownerEntity) !== null && empty($this->updatedEntities[$entityHash])) { $this->updatedEntities[$entityHash] = $ownerEntity; } } }
/** * Serialize data of WorkflowItem * * @param WorkflowItem $workflowItem * @param UnitOfWork $uow */ protected function serialize(WorkflowItem $workflowItem, UnitOfWork $uow) { if ($workflowItem->getData()->isModified()) { $oldValue = $workflowItem->getSerializedData(); $this->serializer->setWorkflowName($workflowItem->getWorkflowName()); $serializedData = $this->serializer->serialize($workflowItem->getData(), $this->format); $workflowItem->setSerializedData($serializedData); $uow->propertyChanged($workflowItem, 'serializedData', $oldValue, $serializedData); } }
/** * {@inheritdoc} */ public function count(PersistentCollection $collection) { $ownerId = $this->uow->getEntityIdentifier($collection->getOwner()); $key = new CollectionCacheKey($this->sourceEntity->rootEntityName, $this->association['fieldName'], $ownerId); $entry = $this->region->get($key); if ($entry !== null) { return count($entry->identifiers); } return $this->persister->count($collection); }
/** * @param \Doctrine\ORM\Mapping\ClassMetadata $metadata The entity metadata. * @param mixed $identifier The entity identifier. * * @return array */ private function toIdentifierArray(ClassMetadata $metadata, $identifier) { if (is_object($identifier) && $this->em->getMetadataFactory()->hasMetadataFor(ClassUtils::getClass($identifier))) { $identifier = $this->uow->getSingleIdentifierValue($identifier); if ($identifier === null) { throw ORMInvalidArgumentException::invalidIdentifierBindingEntity(); } } return array($metadata->identifier[0] => $identifier); }
/** * @param string $targetEntity * @param object $element */ protected function evictElementCache($targetEntity, $element) { /* @var $targetPersister CachedEntityPersister */ $targetPersister = $this->uow->getEntityPersister($targetEntity); $targetRegion = $targetPersister->getCacheRegion(); $key = new EntityCacheKey($targetEntity, $this->uow->getEntityIdentifier($element)); $targetRegion->evict($key); if ($this->cacheLogger) { $this->cacheLogger->entityCachePut($targetRegion->getName(), $key); } }