/** * Checks if the passed value is valid. * * @param mixed $value The value that should be validated * @param Constraint $constraint The constraint for the validation * * @api */ public function validate($value, Constraint $constraint) { if (!$value instanceof Node) { $this->context->addViolation('Attempt to validate non Node entity'); return; } $uow = $this->entityManager->getUnitOfWork(); $originalData = $uow->getOriginalEntityData($value); // If we've been given a custom path, then don't use nonConflict in route path generation $hasCustomPath = strlen($value->getPath()); $route = $this->routeBuilder->build($value, !$hasCustomPath); $routeName = $this->routeBuilder->buildRouteName($route->getPath()); if (is_array($originalData) && count($originalData)) { if ($originalData['path'] !== $value->getPath()) { $existingRoute = $this->entityManager->getRepository('CmfRoutingBundle:Route')->findOneByName($routeName); if ($existingRoute instanceof Route) { $this->context->buildViolation("A page at path '{$route->getPath()}' already exists")->atPath('path')->addViolation(); return; } } elseif ($value->getRoute() instanceof Route && $value->getRoute()->getName() !== $routeName) { $existingRoute = $this->entityManager->getRepository('CmfRoutingBundle:Route')->findOneByName($routeName); if ($existingRoute instanceof Route) { $this->context->buildViolation("A page at path '{$route->getPath()}' already exists")->atPath('path')->addViolation(); return; } } } }
/** * @group orm */ public function testORMCreate() { // unix dir $manager = new FileManager($this->ormStorage, $this->rootDir); $file = $manager->create('myDomain.en.yml', '/test/root/dir/src/Project/CoolBundle/Resources/translations'); $this->assertEquals(ORMUnitOfWork::STATE_MANAGED, $this->em->getUnitOfWork()->getEntityState($file)); $this->assertEquals('myDomain', $file->getDomain()); $this->assertEquals('en', $file->getLocale()); $this->assertEquals('yml', $file->getExtention()); $this->assertEquals('myDomain.en.yml', $file->getName()); $this->assertEquals('../src/Project/CoolBundle/Resources/translations', $file->getPath()); $file = $manager->create('messages.fr.xliff', '/test/root/dir/app/Resources/translations', true); $this->assertEquals(ORMUnitOfWork::STATE_MANAGED, $this->em->getUnitOfWork()->getEntityState($file)); $this->assertEquals('messages', $file->getDomain()); $this->assertEquals('fr', $file->getLocale()); $this->assertEquals('xliff', $file->getExtention()); $this->assertEquals('messages.fr.xliff', $file->getName()); $this->assertEquals('Resources/translations', $file->getPath()); // window dir $manager = new FileManager($this->ormStorage, 'C:\\test\\root\\dir\\app'); $file = $manager->create('myDomain.en.yml', 'C:\\test\\root\\dir\\src\\Project\\CoolBundle\\Resources\\translations'); $this->assertEquals(ORMUnitOfWork::STATE_MANAGED, $this->em->getUnitOfWork()->getEntityState($file)); $this->assertEquals('myDomain', $file->getDomain()); $this->assertEquals('en', $file->getLocale()); $this->assertEquals('yml', $file->getExtention()); $this->assertEquals('myDomain.en.yml', $file->getName()); $this->assertEquals('..\\src\\Project\\CoolBundle\\Resources\\translations', $file->getPath()); $file = $manager->create('messages.fr.xliff', 'C:\\test\\root\\dir\\app\\Resources\\translations', true); $this->assertEquals(ORMUnitOfWork::STATE_MANAGED, $this->em->getUnitOfWork()->getEntityState($file)); $this->assertEquals('messages', $file->getDomain()); $this->assertEquals('fr', $file->getLocale()); $this->assertEquals('xliff', $file->getExtention()); $this->assertEquals('messages.fr.xliff', $file->getName()); $this->assertEquals('Resources\\translations', $file->getPath()); }
/** * {@inheritdoc} */ public function load(ClassMetadata $meta, Component $component, $entity) { if (!$component instanceof BaseControl) { return FALSE; } if ($meta->hasField($name = $component->getOption(self::FIELD_NAME, $component->getName()))) { $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) && !count($component->getItems()) && !$component->getOption(self::FIELD_NOT_LOAD, false)) { 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 ($relation = $this->accessor->getValue($entity, $name)) { $UoW = $this->em->getUnitOfWork(); $component->setValue($UoW->getSingleIdentifierValue($relation)); } return TRUE; }
/** * Returns the identifier assigned to the given entity. * * @param object $entity * @return mixed * @override */ public function generate(EntityManager $em, $entity) { $class = $em->getClassMetadata(get_class($entity)); $identifier = array(); if ($class->isIdentifierComposite) { $idFields = $class->getIdentifierFieldNames(); foreach ($idFields as $idField) { $value = $class->getReflectionProperty($idField)->getValue($entity); if (isset($value)) { if (is_object($value)) { // NOTE: Single Columns as associated identifiers only allowed - this constraint it is enforced. $identifier[$idField] = current($em->getUnitOfWork()->getEntityIdentifier($value)); } else { $identifier[$idField] = $value; } } else { throw ORMException::entityMissingAssignedId($entity); } } } else { $idField = $class->identifier[0]; $value = $class->reflFields[$idField]->getValue($entity); if (isset($value)) { if (is_object($value)) { // NOTE: Single Columns as associated identifiers only allowed - this constraint it is enforced. $identifier[$idField] = current($em->getUnitOfWork()->getEntityIdentifier($value)); } else { $identifier[$idField] = $value; } } else { throw ORMException::entityMissingAssignedId($entity); } } return $identifier; }
/** * @param OnFlushEventArgs $e */ private function init(OnFlushEventArgs $e) { $this->em = $e->getEntityManager(); $this->uow = $this->em->getUnitOfWork(); $roundRepo = $this->em->getRepository('AppBundle:Round'); /* @var $roundRepo \Bml\AppBundle\Entity\RoundRepository */ $this->round = $roundRepo->findCurrent(); }
/** * @param OnFlushEventArgs $event */ public function onFlush(OnFlushEventArgs $event) { $this->em = $event->getEntityManager(); $this->uow = $this->em->getUnitOfWork(); foreach ($this->uow->getScheduledEntityInsertions() as $entity) { if ($entity instanceof Ticket) { $this->startAutoReply($entity); } } }
/** * On flush * * @param OnFlushEventArgs $args */ public function onFlush(OnFlushEventArgs $args) { $this->manager = $args->getEntityManager(); $this->uow = $this->manager->getUnitOfWork(); foreach ($this->uow->getScheduledEntityUpdates() as $entity) { $this->preUpdate($entity); } foreach ($this->uow->getScheduledEntityDeletions() as $entity) { $this->preRemove($entity); } }
/** * {@inheritdoc} */ public function pack($object) { $uow = $this->em->getUnitOfWork(); if (!$uow->isInIdentityMap($object)) { return null; } $identity = $uow->getEntityIdentifier($object); if (count($identity) == 0) { return null; } return new ObjectSignature($this->getClass($object), $identity); }
public function preUpdate(LifecycleEventArgs $lifecycleEventArgs) { $entity = $lifecycleEventArgs->getEntity(); $this->entityManager = $lifecycleEventArgs->getEntityManager(); if (!$entity instanceof UrlInterface) { return; } $changeSet = $this->entityManager->getUnitOfWork()->getEntityChangeSet($entity); if (isset($changeSet['url'])) { $url = $this->findFreeUrl($entity, String::toUrl($entity->getUrl())); $entity->setUrl($url); } }
/** * Savely persist Doctrine 2 Entity information * * @param ezcWorkflowExecution $execution * @param string $variableName * @param $value */ public function save(ezcWorkflowExecution $execution, $variableName, $value) { if (!is_object($value)) { return null; } if (!$this->em->contains($value)) { throw new \ezcWorkflowExecutionException("Entity '" . get_class($value) . "' at variable " . $variableName . " has to be managed by the EntityManager."); } $entityData = array(get_class($value), $this->em->getUnitOfWork()->getEntityIdentifier($value)); $entityDetailsVariable = $variableName . "_dc2entity"; $execution->setVariable($entityDetailsVariable, $entityData); $execution->setVariable($variableName, null); }
public function testUpdateUsesTypeValuesSQL() { $child = new CustomTypeChild(); $parent = new CustomTypeParent(); $parent->customInteger = 1; $parent->child = $child; $this->_em->getUnitOfWork()->registerManaged($parent, array('id' => 1), array('customInteger' => 0, 'child' => null)); $this->_em->getUnitOfWork()->registerManaged($child, array('id' => 1), array()); $this->_em->getUnitOfWork()->propertyChanged($parent, 'customInteger', 0, 1); $this->_em->getUnitOfWork()->propertyChanged($parent, 'child', null, $child); $this->_persister->update($parent); $executeUpdates = $this->_em->getConnection()->getExecuteUpdates(); $this->assertEquals('UPDATE customtype_parents SET customInteger = ABS(?), child_id = ? WHERE id = ?', $executeUpdates[0]['query']); }
/** * Validate the property * * @param Locale $entity * @param Constraint $constraint */ public function validate($entity, Constraint $constraint) { $originalData = $this->em->getUnitOfWork()->getOriginalEntityData($entity); $accessor = PropertyAccess::createPropertyAccessor(); foreach ($constraint->properties as $property) { $originalValue = $accessor->getValue($originalData, sprintf('[%s]', $property)); if (null !== $originalValue) { $newValue = $accessor->getValue($entity, $property); if ($originalValue !== $newValue) { $this->context->addViolationAt($property, $constraint->message); } } } }
public function onSiteStateException(SiteStateExceptionEvent $event) { $state = $event->getSite()->getSiteState(); $exception = $event->getException(); if ($exception instanceof ProtocolException) { $state->markLastFailedContactAt(new \DateTime(), $exception->getLevel(), $exception->getType(), $exception->getCode(), $exception->getContext()); } else { return; } if ($this->em->getUnitOfWork()->isInIdentityMap($state) && !$this->em->getUnitOfWork()->isScheduledForInsert($state)) { $this->em->persist($state); $this->em->flush(); } }
/** * @param $entity * @param \Doctrine\ORM\EntityManager $em */ private function makeSnapshot($entity, \Doctrine\ORM\EntityManager $em) { $resourceVersion = new ResourceVersion($entity); $class = $em->getClassMetadata(get_class($resourceVersion)); $em->persist($resourceVersion); $em->getUnitOfWork()->computeChangeSet($class, $resourceVersion); }
/** * @param BadgeRule[]|\Doctrine\Common\Collections\ArrayCollection $newRules * @param BadgeRule[]|\Doctrine\Common\Collections\ArrayCollection $originalRules * * @return bool */ public function isRuleChanged($newRules, $originalRules) { $isRulesChanged = false; $unitOfWork = $this->entityManager->getUnitOfWork(); $unitOfWork->computeChangeSets(); foreach ($newRules as $newRule) { // Check if there are new rules if (null === $newRule->getId()) { $isRulesChanged = true; } else { // Check if existed rules have been changed $changeSet = $unitOfWork->getEntityChangeSet($newRule); if (0 < count($changeSet)) { $isRulesChanged = true; } // Remove rule from original if they were not deleted if ($originalRules->contains($newRule)) { $originalRules->removeElement($newRule); } } } // Check if they are deleted rules (those who are not in the new but in the originals) if (0 < count($originalRules)) { $isRulesChanged = true; } return $isRulesChanged; }
/** * Selects all elements from a selectable that match the expression and * return a new collection containing these elements. * * @param \Doctrine\Common\Collections\Criteria $criteria * * @return Collection * * @throws \RuntimeException */ public function matching(Criteria $criteria) { if ($this->isDirty) { $this->initialize(); } if ($this->initialized) { return $this->coll->matching($criteria); } if ($this->association['type'] !== ClassMetadata::ONE_TO_MANY) { throw new \RuntimeException("Matching Criteria on PersistentCollection only works on OneToMany associations at the moment."); } $builder = Criteria::expr(); $ownerExpression = $builder->eq($this->backRefFieldName, $this->owner); $expression = $criteria->getWhereExpression(); $expression = $expression ? $builder->andX($expression, $ownerExpression) : $ownerExpression; $criteria->where($expression); $persister = $this->em->getUnitOfWork()->getEntityPersister($this->association['targetEntity']); return new ArrayCollection($persister->loadCriteria($criteria)); }
/** * Updates every indexed value assocatied to the contents flushed. * * @param Event $event */ public static function onFlushContent(Event $event) { if (null === self::getEntityManager($event)) { return; } $contents_inserted = ScheduledEntities::getScheduledAClassContentInsertions(self::$em, true, true); $contents_updated = ScheduledEntities::getScheduledAClassContentUpdates(self::$em, true, true); $contents_deleted = ScheduledEntities::getSchedulesAClassContentDeletions(self::$em, true); // Updates content-content indexes self::updateIdxContentContents(array_merge($contents_inserted, $contents_updated), $contents_deleted); // Updates site-content indexes self::updateIdxSiteContents($contents_inserted, $contents_deleted); $content = $event->getTarget(); if (!$content instanceof AbstractClassContent) { return; } $dispatcher = $event->getDispatcher(); $application = $dispatcher->getApplication(); if (null === $application) { return; } $uow = self::$em->getUnitOfWork(); if ($uow->isScheduledForInsert($content) || $uow->isScheduledForUpdate($content)) { self::$em->getRepository('BackBee\\ClassContent\\Indexes\\OptContentByModified')->replaceOptContentTable($content); self::indexContent($content); self::updateSuperContentIndexes($content); } elseif ($uow->isScheduledForDelete($content)) { self::$em->getRepository('BackBee\\ClassContent\\Indexes\\OptContentByModified')->removeOptContentTable($content); foreach ($content->getIndexation() as $index) { self::$em->remove($index); self::$em->getUnitOfWork()->computeChangeSet(self::$em->getClassMetadata('BackBee\\ClassContent\\Indexation'), $index); } } }
/** * Additionally it will refresh the nodes from the database because index * update has been made using DQL already * {@inheritdoc} */ protected function moveNode(Node\NodeInterface $item, $moveLeft, $moveRight, $moveLevel) { // $newLeft = $item->getLeftValue() + (int) $moveLeft; // $newRight = $item->getRightValue() + (int) $moveRight; // $newLevel = $item->getLevel() + (int) $moveLevel; // // Call original local move method for items not in the database yet parent::moveNode($item, $moveLeft, $moveRight, $moveLevel); // In case of entity update, make the new nested set values to be ignored $insert = $this->entityManager->getUnitOfWork()->isScheduledForInsert($item); if (!$insert) { $oid = spl_object_hash($item); $this->entityManager->getUnitOfWork()->setOriginalEntityProperty($oid, 'level', $item->getLevel()); $this->entityManager->getUnitOfWork()->setOriginalEntityProperty($oid, 'right', $item->getRightValue()); $this->entityManager->getUnitOfWork()->setOriginalEntityProperty($oid, 'left', $item->getLeftValue()); } // // if ($insert) { // // Call original local move method for items not in the database yet // parent::moveNode($item, $moveLeft, $moveRight, $moveLevel); // } else { // // Refresh so additional UPDATE-s are not executed on the server // $this->entityManager->refresh($item); // } // // Double check the values, should not happen // if ($item->getLeftValue() != $newLeft) { // $item->setLeftValue($newLeft); // } // if ($item->getRightValue() != $newRight) { // $item->setRightValue($newRight); // } // if ($item->getLevel() != $newLevel) { // $item->setLevel($newLevel); // } }
/** * Validate the property * * @param \Pim\Bundle\CatalogBundle\Entity\Locale $entity * @param Constraint $constraint */ public function validate($entity, Constraint $constraint) { $originalData = $this->em->getUnitOfWork()->getOriginalEntityData($entity); $accessor = PropertyAccess::createPropertyAccessor(); foreach ($constraint->properties as $property) { $originalValue = $accessor->getValue($originalData, sprintf('[%s]', $property)); if (null !== $originalValue) { $newValue = $accessor->getValue($entity, $property); $isDifferent = $originalValue !== $newValue; $isDirtyCollection = $newValue instanceof PersistentCollection && $newValue->isDirty(); if ($isDifferent || $isDirtyCollection) { $this->context->buildViolation($constraint->message)->atPath($property)->addViolation(); } } } }
/** * Processes an individual parameter value. * * @param mixed $value * * @return array * * @throws \Doctrine\ORM\ORMInvalidArgumentException */ public function processParameterValue($value) { if (is_scalar($value)) { return $value; } if ($value instanceof Collection) { $value = $value->toArray(); } if (is_array($value)) { foreach ($value as $key => $paramValue) { $paramValue = $this->processParameterValue($paramValue); $value[$key] = is_array($paramValue) ? reset($paramValue) : $paramValue; } return $value; } if (is_object($value) && $this->_em->getMetadataFactory()->hasMetadataFor(ClassUtils::getClass($value))) { $value = $this->_em->getUnitOfWork()->getSingleIdentifierValue($value); if ($value === null) { throw ORMInvalidArgumentException::invalidIdentifierBindingEntity(); } } if ($value instanceof Mapping\ClassMetadata) { return $value->name; } return $value; }
/** * Invalidate the given Token * * @param Token $token The Token entity * * @throws \LogicException When a not managed Token is being consumed */ public function invalidateToken(Token $token) { if ($this->em->getUnitOfWork()->getEntityState($token) != UnitOfWork::STATE_MANAGED) { throw new \LogicException('The Token must be managed by Doctrine in order to be consumed.'); } $token->setActive(false); $this->em->flush($token); }
/** * @param EntityManager $em * @param AccountUser $accountUser */ protected function setNewCurrent(EntityManager $em, AccountUser $accountUser) { $shoppingList = $em->getRepository('OroB2B\\Bundle\\ShoppingListBundle\\Entity\\ShoppingList')->findLatestForAccountUserExceptCurrent($accountUser); if ($shoppingList instanceof ShoppingList) { $shoppingList->setCurrent(true); $em->getUnitOfWork()->scheduleForUpdate($shoppingList); } }
/** * Initializes a new instance of a class derived from AbstractCollectionPersister. * * @param \Doctrine\ORM\EntityManager $em */ public function __construct(EntityManager $em) { $this->em = $em; $this->uow = $em->getUnitOfWork(); $this->conn = $em->getConnection(); $this->platform = $this->conn->getDatabasePlatform(); $this->quoteStrategy = $em->getConfiguration()->getQuoteStrategy(); }
function it_marks_product_as_updated_when_a_product_metric_is_updated(EntityManager $em, UnitOfWork $uow, ProductInterface $product, ProductValueInterface $value, MetricInterface $metric) { $metric->getValue()->willReturn($value); $value->getEntity()->willReturn($product); $em->getUnitOfWork()->willReturn($uow); $uow->getEntityChangeSet($metric)->willReturn(['data' => ['20', '25']]); $this->guessUpdates($em, $metric, UpdateGuesserInterface::ACTION_UPDATE_ENTITY)->shouldReturn([$product]); }
/** * @param EntityManager $entityManager * * @return UserInterface|null */ protected function getUser(EntityManager $entityManager) { $user = $this->securityFacadeLink->getService()->getLoggedUser(); if ($user && $entityManager->getUnitOfWork()->getEntityState($user) == UnitOfWork::STATE_DETACHED) { $user = $entityManager->find('OroUserBundle:User', $user->getId()); } return $user; }
/** * Extract a slice of $length elements starting at position $offset from the Collection. * * If $length is null it returns all elements from $offset to the end of the Collection. * Keys have to be preserved by this method. Calling this method will only return the * selected slice and NOT change the elements contained in the collection slice is called on. * * @param int $offset * @param int $length * @return array */ public function slice($offset, $length = null) { if (!$this->initialized && !$this->isDirty && $this->association['fetch'] == Mapping\ClassMetadataInfo::FETCH_EXTRA_LAZY) { return $this->em->getUnitOfWork()->getCollectionPersister($this->association)->slice($this, $offset, $length); } $this->initialize(); return $this->coll->slice($offset, $length); }
/** * @param EntityManager $entityManager * @param TokenInterface $token */ protected function assertTokenEntities(EntityManager $entityManager, TokenInterface $token) { $unitOfWork = $entityManager->getUnitOfWork(); $this->assertEquals(UnitOfWork::STATE_MANAGED, $unitOfWork->getEntityState($token->getUser())); if ($token instanceof OrganizationContextTokenInterface) { $this->assertEquals(UnitOfWork::STATE_MANAGED, $unitOfWork->getEntityState($token->getOrganizationContext())); } }
/** * {@inheritdoc} */ public function shrink($object) { if ($this->isTransient($object)) { return null; } $uow = $this->em->getUnitOfWork(); if (!$uow->isInIdentityMap($object)) { throw new ObjectNotConvertibleException(); } $identity = $uow->getEntityIdentifier($object); if (count($identity) == 1) { foreach ($identity as $value) { return $value; } } return $identity; }
/** * @return User */ protected function getLoadedUser() { $isInCache = array_key_exists($this->username, self::$userCache); if (!$isInCache || $isInCache && !$this->em->getUnitOfWork()->isInIdentityMap(self::$userCache[$this->username])) { $this->loadUser(); } return self::$userCache[$this->username]; }
/** * @param string $entityName * @param array $values * @throws \RuntimeException * @return object Detached Doctrine2 entity instance */ public function toEntity($entityName, $values) { $false = serialize(false); if (!empty($values[self::SERIALIZED_KEY])) { foreach ($values[self::SERIALIZED_KEY] as $field) { $result = unserialize($values[$field]); if ($values[$field] !== $false && $result === false) { throw new RuntimeException('Could not unserialize value: ' . $values[$field]); } $values[$field] = $result; } } $unit = $this->em->getUnitOfWork(); $entity = $unit->createEntity($entityName, $values); $this->em->detach($entity); return $entity; }