/**
  * @param string $className
  * @param string $association
  * @param array $ownerIdentifier
  * @param array $data
  */
 private function putCollectionCacheEntry($className, $association, array $ownerIdentifier, array $data)
 {
     $metadata = $this->em->getClassMetadata($className);
     $cacheKey = new CollectionCacheKey($metadata->name, $association, $ownerIdentifier);
     $cacheEntry = new CollectionCacheEntry($data);
     $persister = $this->em->getUnitOfWork()->getCollectionPersister($metadata->getAssociationMapping($association));
     $persister->getCacheRegion()->put($cacheKey, $cacheEntry);
 }
 /**
  * @param Game $game
  * @return bool
  */
 protected function hasGameAlreadyStarted(Game $game)
 {
     $unitOfWork = $this->entityManager->getUnitOfWork();
     $changes = $unitOfWork->getEntityChangeSet($game);
     $changeFieldKey = sprintf('user%dShips', $game->getPlayerNumber());
     // old ships if changed, or current ships
     $playerShipsBeforeChanges = isset($changes[$changeFieldKey]) ? $changes[$changeFieldKey][0] : $game->getPlayerShips();
     // game started if ships already set
     return count($playerShipsBeforeChanges) > 0;
 }
 public function testCreateOriginalEntityIdentity()
 {
     $gallery = new Gallery('Riverstreet 12');
     $gallery->addVisitor('Foo de Bar');
     $this->em->persist($gallery);
     $this->em->flush();
     $gallery->addVisitor('Bar Baz');
     $this->em->getUnitOfWork()->computeChangeSets();
     $this->em->flush();
     $original = $this->provider->createOriginalEntity($this->em, $gallery);
     self::assertSame($gallery->getId(), $original->getId());
 }
Exemple #4
0
 /**
  * Set updated at to current DateTime when related entities updated
  * TODO: consider refactoring of this feature to make it applicable to all entities
  *
  * @param Contact $entity
  */
 protected function setUpdatedAt(Contact $entity)
 {
     /** @var UnitOfWork $uow */
     $uow = $this->manager->getUnitOfWork();
     $uow->computeChangeSets();
     $isEntityChanged = count($uow->getEntityChangeSet($entity)) > 0;
     $isRelationChanged = count($uow->getScheduledEntityUpdates()) > 0 || count($uow->getScheduledCollectionUpdates()) > 0 || count($uow->getScheduledCollectionDeletions()) > 0;
     if (false === $isEntityChanged && $isRelationChanged) {
         $entity->setUpdatedAt(new \DateTime('now', new \DateTimeZone('UTC')));
         $this->manager->persist($entity);
     }
 }
 private function prepare($data)
 {
     $metaDataClass = $this->entityManager->getClassMetadata(get_class($data));
     $assocFields = $metaDataClass->getAssociationMappings();
     foreach ($assocFields as $assoc) {
         $relatedEntities = $metaDataClass->reflFields[$assoc['fieldName']]->getValue($data);
         if ($relatedEntities instanceof Collection) {
             if ($relatedEntities === $metaDataClass->reflFields[$assoc['fieldName']]->getValue($data)) {
                 continue;
             }
             if ($relatedEntities instanceof PersistentCollection) {
                 // Unwrap so that foreach() does not initialize
                 $relatedEntities = $relatedEntities->unwrap();
             }
             foreach ($relatedEntities as $relatedEntity) {
                 $relatedEntitiesState = $this->entityManager->getUnitOfWork()->getEntityState($relatedEntities);
                 if ($relatedEntitiesState === UnitOfWork::STATE_DETACHED) {
                     $metaDataClass->setFieldValue($data, $assoc['fieldName'], $this->entityManager->merge($relatedEntity));
                 }
             }
         } else {
             if ($relatedEntities !== null) {
                 $relatedEntitiesState = $this->entityManager->getUnitOfWork()->getEntityState($relatedEntities);
                 if ($relatedEntitiesState === UnitOfWork::STATE_DETACHED) {
                     $metaDataClass->setFieldValue($data, $assoc['fieldName'], $this->entityManager->merge($relatedEntities));
                 }
             }
         }
     }
 }
 /**
  * Processes an individual parameter value.
  *
  * @param mixed $value
  *
  * @return array|string
  *
  * @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;
 }
 /**
  * Initializes a new instance of a class derived from AbstractCollectionPersister.
  *
  * @param EntityManagerInterface $em
  */
 public function __construct(EntityManagerInterface $em)
 {
     $this->em = $em;
     $this->uow = $em->getUnitOfWork();
     $this->conn = $em->getConnection();
     $this->platform = $this->conn->getDatabasePlatform();
     $this->quoteStrategy = $em->getConfiguration()->getQuoteStrategy();
 }
 /**
  * Occur on nestednode.page.preupdate events and nestednode.section.preupdate.
  *
  * @access public
  *
  * @param Event $event
  */
 public function onFlushPage(Event $event)
 {
     $uow = $this->entityManager->getUnitOfWork();
     $page = $event->getTarget();
     if ($uow->isScheduledForInsert($page) && $page->getParent() !== null && $page->getState() < 4) {
         self::setSectionHasChildren($page->getParent()->getSection(), +1);
     }
 }
 /**
  * @param \Doctrine\ORM\EntityManagerInterface $em     The entity manager.
  * @param \Doctrine\ORM\Cache\Region           $region The query region.
  */
 public function __construct(EntityManagerInterface $em, Region $region)
 {
     $cacheConfig = $em->getConfiguration()->getSecondLevelCacheConfiguration();
     $this->em = $em;
     $this->region = $region;
     $this->uow = $em->getUnitOfWork();
     $this->cacheLogger = $cacheConfig->getCacheLogger();
     $this->validator = $cacheConfig->getQueryValidator();
 }
Exemple #10
0
 /**
  * Initializes a new instance of the <tt>ProxyFactory</tt> class that is
  * connected to the given <tt>EntityManager</tt>.
  *
  * @param EntityManagerInterface $em           The EntityManager the new factory works for.
  * @param string                 $proxyDir     The directory to use for the proxy classes. It must exist.
  * @param string                 $proxyNs      The namespace to use for the proxy classes.
  * @param boolean|int            $autoGenerate The strategy for automatically generating proxy classes. Possible
  *                                             values are constants of Doctrine\Common\Proxy\AbstractProxyFactory.
  */
 public function __construct(EntityManagerInterface $em, $proxyDir, $proxyNs, $autoGenerate = AbstractProxyFactory::AUTOGENERATE_NEVER)
 {
     $proxyGenerator = new ProxyGenerator($proxyDir, $proxyNs);
     $proxyGenerator->setPlaceholder('baseProxyInterface', 'Doctrine\\ORM\\Proxy\\Proxy');
     parent::__construct($proxyGenerator, $em->getMetadataFactory(), $autoGenerate);
     $this->em = $em;
     $this->uow = $em->getUnitOfWork();
     $this->proxyNs = $proxyNs;
     $this->identifierFlattener = new IdentifierFlattener($this->uow, $em->getMetadataFactory());
 }
 /**
  * Register entity as managed in UnitOfWork.
  *
  * @param ClassMetadata $class
  * @param object        $entity
  * @param array         $data
  *
  * @return void
  *
  * @todo The "$id" generation is the same of UnitOfWork#createEntity. Remove this duplication somehow
  */
 protected function registerManaged(ClassMetadata $class, $entity, array $data)
 {
     if ($class->isIdentifierComposite) {
         $id = array();
         foreach ($class->identifier as $fieldName) {
             $id[$fieldName] = isset($class->associationMappings[$fieldName]) ? $data[$class->associationMappings[$fieldName]['joinColumns'][0]['name']] : $data[$fieldName];
         }
     } else {
         $fieldName = $class->identifier[0];
         $id = array($fieldName => isset($class->associationMappings[$fieldName]) ? $data[$class->associationMappings[$fieldName]['joinColumns'][0]['name']] : $data[$fieldName]);
     }
     $this->_em->getUnitOfWork()->registerManaged($entity, $id, $data);
 }
 /**
  * Dumps the contents of the identity map into a stream.
  *
  * @param EntityManagerInterface $em
  *
  * @return void
  */
 public function dumpIdentityMap(EntityManagerInterface $em)
 {
     $uow = $em->getUnitOfWork();
     $identityMap = $uow->getIdentityMap();
     $fh = fopen($this->file, "x+");
     if (count($identityMap) == 0) {
         fwrite($fh, "Flush Operation [" . $this->context . "] - Empty identity map.\n");
         return;
     }
     fwrite($fh, "Flush Operation [" . $this->context . "] - Dumping identity map:\n");
     foreach ($identityMap as $className => $map) {
         fwrite($fh, "Class: " . $className . "\n");
         foreach ($map as $entity) {
             fwrite($fh, " Entity: " . $this->getIdString($entity, $uow) . " " . spl_object_hash($entity) . "\n");
             fwrite($fh, "  Associations:\n");
             $cm = $em->getClassMetadata($className);
             foreach ($cm->associationMappings as $field => $assoc) {
                 fwrite($fh, "   " . $field . " ");
                 $value = $cm->getFieldValue($entity, $field);
                 if ($assoc['type'] & ClassMetadata::TO_ONE) {
                     if ($value === null) {
                         fwrite($fh, " NULL\n");
                     } else {
                         if ($value instanceof Proxy && !$value->__isInitialized()) {
                             fwrite($fh, "[PROXY] ");
                         }
                         fwrite($fh, $this->getIdString($value, $uow) . " " . spl_object_hash($value) . "\n");
                     }
                 } else {
                     $initialized = !$value instanceof PersistentCollection || $value->isInitialized();
                     if ($value === null) {
                         fwrite($fh, " NULL\n");
                     } elseif ($initialized) {
                         fwrite($fh, "[INITIALIZED] " . $this->getType($value) . " " . count($value) . " elements\n");
                         foreach ($value as $obj) {
                             fwrite($fh, "    " . $this->getIdString($obj, $uow) . " " . spl_object_hash($obj) . "\n");
                         }
                     } else {
                         fwrite($fh, "[PROXY] " . $this->getType($value) . " unknown element size\n");
                         foreach ($value->unwrap() as $obj) {
                             fwrite($fh, "    " . $this->getIdString($obj, $uow) . " " . spl_object_hash($obj) . "\n");
                         }
                     }
                 }
             }
         }
     }
     fclose($fh);
 }
Exemple #13
0
 /**
  * Update all properties to ical requirements and apply changes to dependent attributes:
  * - set $dtStart and $dtEnd according to the selected values from $dateFrom, $timeFrom, $dateTo and $timeTo
  * - remove $recurrenceRule if it's $frequency is empty
  * - set $recurrenceRule's $byDay value to null if empty
  * - apply changed $dtStart values to $excludedDates
  * Must be executed on persisting the event. Should be called prior to any validation.
  *
  * @param Event $event
  */
 public function cleanUpEvent(Event $event)
 {
     if ($event->getDateFrom()) {
         //merge dates and times, apply noTime setting
         $event->setDtStart($event->getDateFrom());
         if (is_null($event->getTimeFrom())) {
             $event->getDtStart()->setTime(0, 0);
             $event->setTimeFrom(new \DateTime('1970-01-01'));
         } else {
             $event->getDtStart()->setTime($event->getTimeFrom()->format('H'), $event->getTimeFrom()->format('i'));
         }
     }
     if ($event->getDateTo()) {
         $event->setDtEnd(clone $event->getDateTo());
         if (is_null($event->getTimeTo())) {
             $event->getDtEnd()->setTime(0, 0);
             $event->setTimeTo(new \DateTime('1970-01-01'));
         } else {
             $event->getDtEnd()->setTime($event->getTimeTo()->format('H'), $event->getTimeTo()->format('i'));
         }
         if ($event->isNoTime()) {
             $event->getDtEnd()->add(new \DateInterval('P1D'));
         }
     }
     //do the following only if event is recurring
     if ($event->getRecurrenceRule()) {
         //remove recurring rule if empty and nullify "byDay" property if empty
         if ('' == $event->getRecurrenceRule()->getFreq()) {
             $this->em->remove($event->getRecurrenceRule());
             $event->removeRecurrenceRule();
         } elseif ('' == $event->getRecurrenceRule()->getByDay()) {
             $event->getRecurrenceRule()->setByDay(null);
         }
         //update excludeDates
         /** @var $entity \Xima\ICalBundle\Entity\Component\Event */
         $uow = $this->em->getUnitOfWork();
         $changeSet = $uow->getEntityChangeSet($event);
         if (isset($changeSet['dtStart']) && isset($changeSet['dtStart'][0])) {
             $interval = $changeSet['dtStart'][0]->diff($event->getDtStart());
             foreach ($event->getExDates() as $dateTime) {
                 $dateTime->add($interval);
             }
         }
     }
 }
 /**
  * {@inheritdoc}
  */
 protected function doInitialize()
 {
     // Has NEW objects added through add(). Remember them.
     $newObjects = array();
     if ($this->isDirty) {
         $newObjects = $this->collection->toArray();
     }
     $this->collection->clear();
     $this->em->getUnitOfWork()->loadCollection($this);
     $this->takeSnapshot();
     // Reattach NEW objects added through add(), if any.
     if ($newObjects) {
         foreach ($newObjects as $obj) {
             $this->collection->add($obj);
         }
         $this->isDirty = true;
     }
 }
 /**
  * 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->collection->matching($criteria);
     }
     if ($this->association['type'] === ClassMetadata::MANY_TO_MANY) {
         $persister = $this->em->getUnitOfWork()->getCollectionPersister($this->association);
         return new ArrayCollection($persister->loadCriteria($this, $criteria));
     }
     $builder = Criteria::expr();
     $ownerExpression = $builder->eq($this->backRefFieldName, $this->owner);
     $expression = $criteria->getWhereExpression();
     $expression = $expression ? $builder->andX($expression, $ownerExpression) : $ownerExpression;
     $criteria = clone $criteria;
     $criteria->where($expression);
     $persister = $this->em->getUnitOfWork()->getEntityPersister($this->association['targetEntity']);
     return $this->association['fetch'] === ClassMetadataInfo::FETCH_EXTRA_LAZY ? new LazyCriteriaCollection($persister, $criteria) : new ArrayCollection($persister->loadCriteria($criteria));
 }
 /**
  * @param \Doctrine\ORM\EntityManagerInterface $em The entity manager.
  */
 public function __construct(EntityManagerInterface $em)
 {
     $this->em = $em;
     $this->uow = $em->getUnitOfWork();
 }
 /**
  * @param \Doctrine\ORM\Persisters\Collection\CollectionPersister $persister   The collection persister that will be cached.
  * @param \Doctrine\ORM\Cache\Region                              $region      The collection region.
  * @param \Doctrine\ORM\EntityManagerInterface                    $em          The entity manager.
  * @param array                                                   $association The association mapping.
  */
 public function __construct(CollectionPersister $persister, Region $region, EntityManagerInterface $em, array $association)
 {
     $configuration = $em->getConfiguration();
     $cacheConfig = $configuration->getSecondLevelCacheConfiguration();
     $cacheFactory = $cacheConfig->getCacheFactory();
     $this->region = $region;
     $this->persister = $persister;
     $this->association = $association;
     $this->regionName = $region->getName();
     $this->uow = $em->getUnitOfWork();
     $this->metadataFactory = $em->getMetadataFactory();
     $this->cacheLogger = $cacheConfig->getCacheLogger();
     $this->hydrator = $cacheFactory->buildCollectionHydrator($em, $association);
     $this->sourceEntity = $em->getClassMetadata($association['sourceEntity']);
     $this->targetEntity = $em->getClassMetadata($association['targetEntity']);
 }
Exemple #18
0
 /**
  * {@inheritdoc}
  */
 public function __construct(EntityManagerInterface $em)
 {
     $this->em = $em;
     $this->uow = $em->getUnitOfWork();
     $this->cacheFactory = $em->getConfiguration()->getSecondLevelCacheConfiguration()->getCacheFactory();
 }
 protected function getEntityPersister($entity)
 {
     $uow = $this->em->getUnitOfWork();
     return $uow->getEntityPersister($entity);
 }
 /**
  * @param EntityManagerInterface $em
  * @param mixed                  $entity
  * @return bool
  */
 public function isEntityManaged(EntityManagerInterface $em, $entity)
 {
     return $em->getUnitOfWork()->getEntityState($entity) === UnitOfWork::STATE_MANAGED;
 }
 /**
  * {@inheritdoc}
  */
 public function getUnitOfWork()
 {
     return $this->wrapped->getUnitOfWork();
 }
 /**
  * @param object $entity
  */
 protected function updateChangeSets($entity)
 {
     $metadata = $this->getMetadataForEntity($entity);
     $this->entityManager->getUnitOfWork()->recomputeSingleEntityChangeSet($metadata, $entity);
 }
 /**
  * Builds criteria and execute SQL statement to fetch the one to many entities from.
  *
  * @param array    $assoc
  * @param object   $sourceEntity
  * @param int|null $offset
  * @param int|null $limit
  *
  * @return \Doctrine\DBAL\Statement
  */
 private function getOneToManyStatement(array $assoc, $sourceEntity, $offset = null, $limit = null)
 {
     $this->switchPersisterContext($offset, $limit);
     $criteria = array();
     $parameters = array();
     $owningAssoc = $this->class->associationMappings[$assoc['mappedBy']];
     $sourceClass = $this->em->getClassMetadata($assoc['sourceEntity']);
     $tableAlias = $this->getSQLTableAlias(isset($owningAssoc['inherited']) ? $owningAssoc['inherited'] : $this->class->name);
     foreach ($owningAssoc['targetToSourceKeyColumns'] as $sourceKeyColumn => $targetKeyColumn) {
         if ($sourceClass->containsForeignIdentifier) {
             $field = $sourceClass->getFieldForColumn($sourceKeyColumn);
             $value = $sourceClass->reflFields[$field]->getValue($sourceEntity);
             if (isset($sourceClass->associationMappings[$field])) {
                 $value = $this->em->getUnitOfWork()->getEntityIdentifier($value);
                 $value = $value[$this->em->getClassMetadata($sourceClass->associationMappings[$field]['targetEntity'])->identifier[0]];
             }
             $criteria[$tableAlias . "." . $targetKeyColumn] = $value;
             $parameters[] = array('value' => $value, 'field' => $field, 'class' => $sourceClass);
             continue;
         }
         $field = $sourceClass->fieldNames[$sourceKeyColumn];
         $value = $sourceClass->reflFields[$field]->getValue($sourceEntity);
         $criteria[$tableAlias . "." . $targetKeyColumn] = $value;
         $parameters[] = array('value' => $value, 'field' => $field, 'class' => $sourceClass);
     }
     $sql = $this->getSelectSQL($criteria, $assoc, null, $limit, $offset);
     list($params, $types) = $this->expandToManyParameters($parameters);
     return $this->conn->executeQuery($sql, $params, $types);
 }
 /**
  * @param EntityManagerInterface $em
  * @return array
  */
 public function getFullChangeSet(EntityManagerInterface $em)
 {
     return $em->getUnitOfWork()->getIdentityMap();
 }
 /**
  * Retrieves an individual parameter value.
  *
  * @param mixed $value
  *
  * @return mixed
  */
 private function getIndividualValue($value)
 {
     if (!is_object($value) || !$this->em->getMetadataFactory()->hasMetadataFor(ClassUtils::getClass($value))) {
         return $value;
     }
     return $this->em->getUnitOfWork()->getSingleIdentifierValue($value);
 }
 /**
  * @param \Doctrine\ORM\Persisters\Entity\EntityPersister $persister The entity persister to cache.
  * @param \Doctrine\ORM\Cache\Region                      $region    The entity cache region.
  * @param \Doctrine\ORM\EntityManagerInterface            $em        The entity manager.
  * @param \Doctrine\ORM\Mapping\ClassMetadata             $class     The entity metadata.
  */
 public function __construct(EntityPersister $persister, Region $region, EntityManagerInterface $em, ClassMetadata $class)
 {
     $configuration = $em->getConfiguration();
     $cacheConfig = $configuration->getSecondLevelCacheConfiguration();
     $cacheFactory = $cacheConfig->getCacheFactory();
     $this->class = $class;
     $this->region = $region;
     $this->persister = $persister;
     $this->cache = $em->getCache();
     $this->regionName = $region->getName();
     $this->uow = $em->getUnitOfWork();
     $this->metadataFactory = $em->getMetadataFactory();
     $this->cacheLogger = $cacheConfig->getCacheLogger();
     $this->timestampRegion = $cacheFactory->getTimestampRegion();
     $this->hydrator = $cacheFactory->buildEntityHydrator($em, $class);
     $this->timestampKey = new TimestampCacheKey($this->class->getTableName());
 }
 /**
  * @param \Doctrine\ORM\EntityManagerInterface $em The entity manager.
  */
 public function __construct(EntityManagerInterface $em)
 {
     $this->em = $em;
     $this->uow = $em->getUnitOfWork();
     $this->identifierFlattener = new IdentifierFlattener($em->getUnitOfWork(), $em->getMetadataFactory());
 }
 /**
  * Constructor
  *
  * @param EntityManagerInterface $entityManager
  */
 public function __construct(EntityManagerInterface $entityManager)
 {
     $this->entityManager = $entityManager;
     $this->unitOfWork = $entityManager->getUnitOfWork();
 }
 /**
  * {@inheritdoc}
  */
 public function buildCollectionHydrator(EntityManagerInterface $em, array $mapping)
 {
     /* @var $targetPersister \Doctrine\ORM\Cache\Persister\CachedPersister */
     $targetPersister = $em->getUnitOfWork()->getEntityPersister($mapping['targetEntity']);
     return new DefaultCollectionHydrator($em, $targetPersister->getCacheRegion());
 }