/** * Get valid UserApi for given token * * @param TokenInterface $token * @param PersistentCollection $secrets * @param User $user * * @return bool|UserApi */ protected function getValidUserApi(TokenInterface $token, PersistentCollection $secrets, User $user) { $currentIteration = 0; $nonce = $token->getAttribute('nonce'); $secretsCount = $secrets->count(); /** @var UserApi $userApi */ foreach ($secrets as $userApi) { $currentIteration++; $isSecretValid = $this->validateDigest($token->getAttribute('digest'), $nonce, $token->getAttribute('created'), $userApi->getApiKey(), $this->getSalt($user)); if ($isSecretValid && !$userApi->getUser()->getOrganizations()->contains($userApi->getOrganization())) { throw new BadCredentialsException('Wrong API key.'); } if ($isSecretValid && !$userApi->getOrganization()->isEnabled()) { throw new BadCredentialsException('Organization is not active.'); } // delete nonce from cache because user have another api keys if (!$isSecretValid && $secretsCount !== $currentIteration) { $this->getNonceCache()->delete($nonce); } if ($isSecretValid) { return $userApi; } } return false; }
/** * {@inheritdoc} */ public function update(PersistentCollection $collection) { if ($collection->isDirty() && $collection->getSnapshot()) { throw CacheException::updateReadOnlyCollection(ClassUtils::getClass($collection->getOwner()), $this->association['fieldName']); } parent::update($collection); }
public function testCanBePutInLazyLoadingMode() { $class = $this->_emMock->getClassMetadata('Doctrine\\Tests\\Models\\ECommerce\\ECommerceProduct'); $collection = new PersistentCollection($this->_emMock, $class, new ArrayCollection()); $collection->setInitialized(false); $this->assertFalse($collection->isInitialized()); }
/** * Transforms an ArrayCollection Object to a single Object. * * @param \Doctrine\ORM\PersistentCollection $values * * @return Object */ public function transform($values) { if (null === $values || !$values instanceof Collection) { return null; } return $values->first(); }
/** * Resets previous photo collection * * @param PersistentCollection $collection */ protected function clearPreviousCollection(PersistentCollection $collection) { if ($collection->count()) { foreach ($collection as $item) { $collection->removeElement($item); } } }
/** * Form event - adds entities to uow to be delete * * @param DataEvent $event */ public function postBind(DataEvent $event) { $collection = $event->getData(); if ($collection instanceof PersistentCollection) { foreach ($collection->getDeleteDiff() as $entity) { $this->om->remove($entity); } } }
/** * @param array $items * * @return PersistentCollection */ protected function getCollection(array $items = []) { /** @var \PHPUnit_Framework_MockObject_MockObject|EntityManager $em */ $em = $this->getMockBuilder('Doctrine\\ORM\\EntityManager')->disableOriginalConstructor()->getMock(); /** @var \PHPUnit_Framework_MockObject_MockObject|ClassMetadata $metadata */ $metadata = $this->getMockBuilder('Doctrine\\ORM\\Mapping\\ClassMetadata')->disableOriginalConstructor()->getMock(); $collection = new PersistentCollection($em, $metadata, new ArrayCollection($items)); $collection->takeSnapshot(); return $collection; }
public function numberComputersAndNumberEnabled(PersistentCollection $computers) { $nbComputersEnabled = 0; foreach ($computers as $computer) { if ($computer->isEnabled()) { $nbComputersEnabled++; } } return sprintf("%d computers (%d enabled)", $computers->count(), $nbComputersEnabled); }
/** * @param \Doctrine\ORM\PersistentCollection $collection * @return array */ public static function getReferenceIds($collection) { if ($collection) { return $collection->map(function ($obj) { /** @var \User\Entity\Resource $obj */ return $obj->getId(); })->toArray(); } else { return null; } }
public function testShouldNotScheduleDeletionOnClonedInstances() { $class = $this->_em->getClassMetadata('Doctrine\\Tests\\Models\\ECommerce\\ECommerceProduct'); $product = new ECommerceProduct(); $category = new ECommerceCategory(); $collection = new PersistentCollection($this->_em, $class, new ArrayCollection(array($category))); $collection->setOwner($product, $class->associationMappings['categories']); $uow = $this->_em->getUnitOfWork(); $clonedCollection = clone $collection; $clonedCollection->clear(); $this->assertEquals(0, count($uow->getScheduledCollectionDeletions())); }
public function testQueriesAssociationToLoadItself() { $class = $this->_emMock->getClassMetadata('Doctrine\\Tests\\Models\\ECommerce\\ECommerceProduct'); $collection = new PersistentCollection($this->_emMock, $class, new ArrayCollection()); $collection->setInitialized(false); $association = $this->getMock('Doctrine\\ORM\\Mapping\\OneToManyMapping', array('load'), array(), '', false, false, false); $association->targetEntityName = 'Doctrine\\Tests\\Models\\ECommerce\\ECommerceFeature'; $product = new ECommerceProduct(); $association->expects($this->once())->method('load')->with($product, $this->isInstanceOf($collection), $this->isInstanceOf($this->_emMock)); $collection->setOwner($product, $association); count($collection); }
/** * Transforms an ArrayCollection Object to a single Object. * * @param \Doctrine\ORM\PersistentCollection $value * * @return Object */ public function transform($value) { if (null === $value || !$value instanceof Collection) { return ''; } $string = ''; foreach ($value as $item) { $string .= $item->getId(); if ($value->last() != $item) { $string .= ','; } } return $string; }
/** * @return array */ public function postSetDataProvider() { $em = $this->getMockBuilder('Doctrine\\ORM\\EntityManager')->disableOriginalConstructor()->getMock(); $meta = $this->getMock('Doctrine\\Common\\Persistence\\Mapping\\ClassMetadata'); $existing = (object) ['$existing' => true]; $removed = (object) ['$removed' => true]; $added = (object) ['$added' => true]; $collectionWithElements = new ArrayCollection([$added]); $cleanCollection = new PersistentCollection($em, $meta, new ArrayCollection()); $dirtyCollection = new PersistentCollection($em, $meta, new ArrayCollection([$existing, $removed])); $dirtyCollection->takeSnapshot(); $dirtyCollection->removeElement($removed); $dirtyCollection->add($added); return ['Initialization with empty value should not be broken' => ['$data' => null, '$expectedAddedData' => [], '$expectedRemovedData' => []], 'Empty collection given should set nothing' => ['$data' => new ArrayCollection(), '$expectedAddedData' => [], '$expectedRemovedData' => []], 'Array collection with elements given, should be set to added' => ['$data' => $collectionWithElements, '$expectedAddedData' => [$added], '$expectedRemovedData' => []], 'Clean persistent collection given, should set nothing' => ['$data' => $cleanCollection, '$expectedAddedData' => [], '$expectedRemovedData' => []], 'Persistent collection given, should set from diffs' => ['$data' => $dirtyCollection, '$expectedAddedData' => [$added], '$expectedRemovedData' => [$removed]]]; }
public function testHandleLoggable() { $loggableCollectionClass = new LoggableCollectionClass(); $loggableCollectionClass->setName('testCollectionName'); $collection = new PersistentCollection($this->em, get_class($loggableCollectionClass), array($loggableCollectionClass)); $collection->setDirty(true); $this->loggableClass->setCollection($collection); $this->em->persist($this->loggableClass); //log with out user $this->loggableManager->handleLoggable($this->em); //log with user $this->loggableManager->setUsername('testUser'); $this->loggableManager->handleLoggable($this->em); //log delete $this->em->remove($this->loggableClass); $this->loggableManager->handleLoggable($this->em); }
public function getMontantCompte(PersistentCollection $transactions) { $total = 0; ### PENSER A METTRE LES TRANSACTIONS EN ORDRE DE DATE foreach (array_reverse($transactions->toArray(), true) as $key => $tra) { $type = $tra->getType(); if ($type == "deb") { $total -= $tra->getMontant(); } elseif ($type == "cre") { $total += $tra->getMontant(); } else { // $type == "aju" && $type == "ini" $total = $tra->getMontant(); } } return $total; }
/** * {@inheritdoc} */ public function update(PersistentCollection $collection) { $isInitialized = $collection->isInitialized(); $isDirty = $collection->isDirty(); if (!$isInitialized && !$isDirty) { return; } $ownerId = $this->uow->getEntityIdentifier($collection->getOwner()); $key = new CollectionCacheKey($this->sourceEntity->rootEntityName, $this->association['fieldName'], $ownerId); // Invalidate non initialized collections OR ordered collection if ($isDirty && !$isInitialized || isset($this->association['orderBy'])) { $this->persister->update($collection); $this->queuedCache['delete'][spl_object_hash($collection)] = $key; return; } $this->persister->update($collection); $this->queuedCache['update'][spl_object_hash($collection)] = ['key' => $key, 'list' => $collection]; }
/** * Prepare a lazy loadable PersistentCollection * on the entity to get Products. * The entity must have a "products" property defined * * @param object $entity The entity related to the products * @param array $assoc Association properties * @param EntityManager $entityManager Entity manager */ protected function setProductPersistentCollection($entity, $assoc, EntityManager $entityManager) { $targetEntity = $this->productClass; $productsCollection = new PersistentCollection($entityManager, $targetEntity, new ArrayCollection()); $assoc['fieldName'] = 'products'; $assoc['targetEntity'] = $targetEntity; $assoc['type'] = ClassMetadata::MANY_TO_MANY; $assoc['inversedBy'] = ''; $assoc['isOwningSide'] = false; $assoc['sourceEntity'] = get_class($entity); $assoc['orphanRemoval'] = false; $productsCollection->setOwner($entity, $assoc); $productsCollection->setInitialized(false); $entityMetadata = $entityManager->getClassMetadata(get_class($entity)); $productsReflProp = $entityMetadata->reflClass->getProperty('products'); $productsReflProp->setAccessible(true); $productsReflProp->setValue($entity, $productsCollection); }
/** * {@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; }
/** * {@inheritdoc} */ public function loadCacheEntry(ClassMetadata $metadata, CollectionCacheKey $key, CollectionCacheEntry $entry, PersistentCollection $collection) { $assoc = $metadata->associationMappings[$key->association]; /* @var $targetPersister \Doctrine\ORM\Cache\Persister\CachedPersister */ $targetPersister = $this->uow->getEntityPersister($assoc['targetEntity']); $targetRegion = $targetPersister->getCacheRegion(); $list = []; $entityEntries = $targetRegion->getMultiple($entry); if ($entityEntries === null) { return null; } /* @var $entityEntries \Doctrine\ORM\Cache\EntityCacheEntry[] */ foreach ($entityEntries as $index => $entityEntry) { $list[$index] = $this->uow->createEntity($entityEntry->class, $entityEntry->resolveAssociationEntries($this->em), self::$hints); } array_walk($list, function ($entity, $index) use($collection) { $collection->hydrateSet($index, $entity); }); $this->uow->hydrationComplete(); return $list; }
/** * @param PersistentCollection $coll * * @return string|null */ protected function buildSnapshotValue(PersistentCollection $coll) { if ($coll->isEmpty()) { return null; } $ids = []; /** @var AbstractEnumValue $item */ foreach ($coll as $item) { $ids[] = $item->getId(); } sort($ids); $snapshot = implode(',', $ids); if (strlen($snapshot) > ExtendHelper::MAX_ENUM_SNAPSHOT_LENGTH) { $snapshot = substr($snapshot, 0, ExtendHelper::MAX_ENUM_SNAPSHOT_LENGTH); $lastDelim = strrpos($snapshot, ','); if (ExtendHelper::MAX_ENUM_SNAPSHOT_LENGTH - $lastDelim - 1 < 3) { $lastDelim = strrpos($snapshot, ',', -(strlen($snapshot) - $lastDelim + 1)); } $snapshot = substr($snapshot, 0, $lastDelim + 1) . '...'; } return $snapshot; }
/** * {@inheritdoc} * * @param <type> $coll * @return <type> * @override */ protected function _getDeleteRowSql(PersistentCollection $coll) { $mapping = $coll->getMapping(); $targetClass = $this->_em->getClassMetadata($mapping->getTargetEntityName()); $table = $targetClass->getTableName(); $ownerMapping = $targetClass->getAssociationMapping($mapping->getMappedByFieldName()); $setClause = ''; foreach ($ownerMapping->getSourceToTargetKeyColumns() as $sourceCol => $targetCol) { if ($setClause != '') { $setClause .= ', '; } $setClause .= "{$sourceCol} = NULL"; } $whereClause = ''; foreach ($targetClass->getIdentifierColumnNames() as $idColumn) { if ($whereClause != '') { $whereClause .= ' AND '; } $whereClause .= "{$idColumn} = ?"; } return array("UPDATE {$table} SET {$setClause} WHERE {$whereClause}", $this->_uow->getEntityIdentifier($element)); }
/** * {@inheritdoc} */ public function get(QueryCacheKey $key, ResultSetMapping $rsm, array $hints = array()) { if (!($key->cacheMode & Cache::MODE_GET)) { return null; } $entry = $this->region->get($key); if (!$entry instanceof QueryCacheEntry) { return null; } if (!$this->validator->isValid($key, $entry)) { $this->region->evict($key); return null; } $result = array(); $entityName = reset($rsm->aliasMap); $hasRelation = !empty($rsm->relationMap); $persister = $this->uow->getEntityPersister($entityName); $region = $persister->getCacheRegion(); $regionName = $region->getName(); // @TODO - move to cache hydration component foreach ($entry->result as $index => $entry) { if (($entityEntry = $region->get($entityKey = new EntityCacheKey($entityName, $entry['identifier']))) === null) { if ($this->cacheLogger !== null) { $this->cacheLogger->entityCacheMiss($regionName, $entityKey); } return null; } if ($this->cacheLogger !== null) { $this->cacheLogger->entityCacheHit($regionName, $entityKey); } if (!$hasRelation) { $result[$index] = $this->uow->createEntity($entityEntry->class, $entityEntry->resolveAssociationEntries($this->em), self::$hints); continue; } $data = $entityEntry->data; foreach ($entry['associations'] as $name => $assoc) { $assocPersister = $this->uow->getEntityPersister($assoc['targetEntity']); $assocRegion = $assocPersister->getCacheRegion(); if ($assoc['type'] & ClassMetadata::TO_ONE) { if (($assocEntry = $assocRegion->get($assocKey = new EntityCacheKey($assoc['targetEntity'], $assoc['identifier']))) === null) { if ($this->cacheLogger !== null) { $this->cacheLogger->entityCacheMiss($assocRegion->getName(), $assocKey); } $this->uow->hydrationComplete(); return null; } $data[$name] = $this->uow->createEntity($assocEntry->class, $assocEntry->resolveAssociationEntries($this->em), self::$hints); if ($this->cacheLogger !== null) { $this->cacheLogger->entityCacheHit($assocRegion->getName(), $assocKey); } continue; } if (!isset($assoc['list']) || empty($assoc['list'])) { continue; } $targetClass = $this->em->getClassMetadata($assoc['targetEntity']); $collection = new PersistentCollection($this->em, $targetClass, new ArrayCollection()); foreach ($assoc['list'] as $assocIndex => $assocId) { if (($assocEntry = $assocRegion->get($assocKey = new EntityCacheKey($assoc['targetEntity'], $assocId))) === null) { if ($this->cacheLogger !== null) { $this->cacheLogger->entityCacheMiss($assocRegion->getName(), $assocKey); } $this->uow->hydrationComplete(); return null; } $element = $this->uow->createEntity($assocEntry->class, $assocEntry->resolveAssociationEntries($this->em), self::$hints); $collection->hydrateSet($assocIndex, $element); if ($this->cacheLogger !== null) { $this->cacheLogger->entityCacheHit($assocRegion->getName(), $assocKey); } } $data[$name] = $collection; $collection->setInitialized(true); } $result[$index] = $this->uow->createEntity($entityEntry->class, $data, self::$hints); } $this->uow->hydrationComplete(); return $result; }
/** * @param PersistentCollection $collection */ protected function calculateCollectionData(PersistentCollection $collection) { $ownerEntity = $collection->getOwner(); $ownerEntityClassName = $this->getEntityClassName($ownerEntity); if ($this->checkAuditable($ownerEntityClassName)) { $meta = $this->getConfig($ownerEntityClassName); $collectionMapping = $collection->getMapping(); if (isset($meta->propertyMetadata[$collectionMapping['fieldName']])) { $method = $meta->propertyMetadata[$collectionMapping['fieldName']]->method; // calculate collection changes $newCollection = $collection->toArray(); $oldCollection = $collection->getSnapshot(); $oldData = array_reduce($oldCollection, function ($result, $item) use($method) { return $result . ($result ? ', ' : '') . $item->{$method}(); }); $newData = array_reduce($newCollection, function ($result, $item) use($method) { return $result . ($result ? ', ' : '') . $item->{$method}(); }); $entityIdentifier = $this->getEntityIdentifierString($ownerEntity); $fieldName = $collectionMapping['fieldName']; $this->collectionLogData[$ownerEntityClassName][$entityIdentifier][$fieldName] = array('old' => $oldData, 'new' => $newData); } } }
/** * Initializes a related collection. * * @param object $entity The entity to which the collection belongs. * @param ClassMetadata $class * @param string $fieldName The name of the field on the entity that holds the collection. * @param string $parentDqlAlias Alias of the parent fetch joining this collection. * * @return \Doctrine\ORM\PersistentCollection */ private function initRelatedCollection($entity, $class, $fieldName, $parentDqlAlias) { $oid = spl_object_hash($entity); $relation = $class->associationMappings[$fieldName]; $value = $class->reflFields[$fieldName]->getValue($entity); if ($value === null || is_array($value)) { $value = new ArrayCollection((array) $value); } if (!$value instanceof PersistentCollection) { $value = new PersistentCollection($this->_em, $this->_metadataCache[$relation['targetEntity']], $value); $value->setOwner($entity, $relation); $class->reflFields[$fieldName]->setValue($entity, $value); $this->_uow->setOriginalEntityProperty($oid, $fieldName, $value); $this->initializedCollections[$oid . $fieldName] = $value; } else { if (isset($this->_hints[Query::HINT_REFRESH]) || isset($this->_hints['fetched'][$parentDqlAlias][$fieldName]) && !$value->isInitialized()) { // Is already PersistentCollection, but either REFRESH or FETCH-JOIN and UNINITIALIZED! $value->setDirty(false); $value->setInitialized(true); $value->unwrap()->clear(); $this->initializedCollections[$oid . $fieldName] = $value; } else { // Is already PersistentCollection, and DON'T REFRESH or FETCH-JOIN! $this->existingCollections[$oid . $fieldName] = $value; } } return $value; }
/** * @param object $owner * @param array $mapping * @param array $items * * @return PersistentCollection */ protected function getPersistentCollection($owner, array $mapping, array $items = []) { $metadata = $this->getMockBuilder('Doctrine\\ORM\\Mapping\\ClassMetadata')->disableOriginalConstructor()->getMock(); $coll = new PersistentCollection($this->em, $metadata, new ArrayCollection($items)); $mapping['inversedBy'] = 'test'; $coll->setOwner($owner, $mapping); return $coll; }
/** * Initializes (loads) an uninitialized persistent collection of an entity. * * @param \Doctrine\ORM\PersistentCollection $collection The collection to initialize. * * @return void * * @todo Maybe later move to EntityManager#initialize($proxyOrCollection). See DDC-733. */ public function loadCollection(PersistentCollection $collection) { $assoc = $collection->getMapping(); $persister = $this->getEntityPersister($assoc['targetEntity']); switch ($assoc['type']) { case ClassMetadata::ONE_TO_MANY: $persister->loadOneToManyCollection($assoc, $collection->getOwner(), $collection); break; case ClassMetadata::MANY_TO_MANY: $persister->loadManyToManyCollection($assoc, $collection->getOwner(), $collection); break; } $collection->setInitialized(true); }
/** * {@inheritdoc} */ public function loadOneToManyCollection(array $assoc, $sourceEntity, PersistentCollection $coll) { $persister = $this->uow->getCollectionPersister($assoc); $hasCache = $persister instanceof CachedPersister; if ($hasCache) { $ownerId = $this->uow->getEntityIdentifier($coll->getOwner()); $key = new CollectionCacheKey($assoc['sourceEntity'], $assoc['fieldName'], $ownerId); $list = $persister->loadCollectionCache($coll, $key); if ($list !== null) { if ($this->cacheLogger) { $this->cacheLogger->collectionCacheHit($persister->getCacheRegion()->getName(), $key); } return $list; } } $list = $this->persister->loadOneToManyCollection($assoc, $sourceEntity, $coll); if ($hasCache) { $persister->storeCollectionCache($key, $list); if ($this->cacheLogger) { $this->cacheLogger->collectionCacheMiss($persister->getCacheRegion()->getName(), $key); } } return $list; }
/** * Loads a collection of entities in a one-to-many association. * * @param OneToManyMapping $assoc * @param array $criteria The criteria by which to select the entities. * @param PersistentCollection The collection to load/fill. */ public function loadOneToManyCollection(array $assoc, $sourceEntity, PersistentCollection $coll) { $criteria = array(); $owningAssoc = $this->_class->associationMappings[$assoc['mappedBy']]; $sourceClass = $this->_em->getClassMetadata($assoc['sourceEntity']); foreach ($owningAssoc['targetToSourceKeyColumns'] as $sourceKeyColumn => $targetKeyColumn) { $criteria[$targetKeyColumn] = $sourceClass->reflFields[$sourceClass->fieldNames[$sourceKeyColumn]]->getValue($sourceEntity); } $sql = $this->_getSelectEntitiesSQL($criteria, $assoc); $params = array_values($criteria); $stmt = $this->_conn->executeQuery($sql, $params); while ($result = $stmt->fetch(PDO::FETCH_ASSOC)) { $coll->hydrateAdd($this->_createEntity($result)); } $stmt->closeCursor(); }
/** * {@inheritDoc} */ public function loadCriteria(PersistentCollection $coll, Criteria $criteria) { $mapping = $coll->getMapping(); $owner = $coll->getOwner(); $ownerMetadata = $this->em->getClassMetadata(get_class($owner)); $whereClauses = $params = array(); foreach ($mapping['relationToSourceKeyColumns'] as $key => $value) { $whereClauses[] = sprintf('t.%s = ?', $key); $params[] = $ownerMetadata->getFieldValue($owner, $value); } $parameters = $this->expandCriteriaParameters($criteria); foreach ($parameters as $parameter) { list($name, $value) = $parameter; $whereClauses[] = sprintf('te.%s = ?', $name); $params[] = $value; } $mapping = $coll->getMapping(); $targetClass = $this->em->getClassMetadata($mapping['targetEntity']); $tableName = $this->quoteStrategy->getTableName($targetClass, $this->platform); $joinTable = $this->quoteStrategy->getJoinTableName($mapping, $ownerMetadata, $this->platform); $onConditions = $this->getOnConditionSQL($mapping); $rsm = new Query\ResultSetMappingBuilder($this->em); $rsm->addRootEntityFromClassMetadata($mapping['targetEntity'], 'te'); $sql = 'SELECT ' . $rsm->generateSelectClause() . ' FROM ' . $tableName . ' te' . ' JOIN ' . $joinTable . ' t ON' . implode(' AND ', $onConditions) . ' WHERE ' . implode(' AND ', $whereClauses); $stmt = $this->conn->executeQuery($sql, $params); $hydrator = $this->em->newHydrator(Query::HYDRATE_OBJECT); return $hydrator->hydrateAll($stmt, $rsm); }
/** * {@inheritdoc} */ public function update(PersistentCollection $collection) { $isInitialized = $collection->isInitialized(); $isDirty = $collection->isDirty(); if (!$isInitialized && !$isDirty) { return; } $this->persister->update($collection); $ownerId = $this->uow->getEntityIdentifier($collection->getOwner()); $key = new CollectionCacheKey($this->sourceEntity->rootEntityName, $this->association['fieldName'], $ownerId); $lock = $this->region->lock($key); if ($lock === null) { return; } $this->queuedCache['update'][spl_object_hash($collection)] = array('key' => $key, 'lock' => $lock); }