{@inheritDoc}
public matching ( Doctrine\Common\Collections\Criteria $criteria ) | ||
$criteria | Doctrine\Common\Collections\Criteria |
/** * Initialize mocks for Doctrine * * @param array $managersToMock List of managers to be mocked * * @return void */ protected function initDatabaseMock($managersToMock) { if (is_null($this->mockedManager)) { $test = $this; foreach ($managersToMock as $manager) { $entityName = $manager['entityName']; // EntityManager mock $entityManagerMock = new \mock\Doctrine\ORM\EntityManager(); // ClassMetadata mock $classMetadata = new \mock\Doctrine\ORM\Mapping\ClassMetadata($entityName); $entityClassName = $manager['entityClassName']; $this->calling($classMetadata)->getName = function () use($entityClassName) { return $entityClassName; }; // EntityRepository mock $entityRepositoryMock = new \mock\Doctrine\ORM\EntityRepository($entityManagerMock, $classMetadata); $this->calling($entityRepositoryMock)->find = function ($id) use($test, $entityName) { if (!empty($test->database[$entityName]) && array_key_exists($id, $test->database[$entityName])) { return clone $test->database[$entityName][$id]; } return null; }; $this->calling($entityRepositoryMock)->findBy = function ($criteria = [], $sort = null, $limit = null, $start = 0) use($test, $entityName) { $entities = new ArrayCollection($test->database[$entityName]); $crit = new Criteria(); foreach ($criteria as $field => $value) { $crit->andWhere($crit->expr()->eq($field, $value)); } if (!is_null($sort)) { $crit->orderBy($sort); } $crit->setFirstResult($start); $crit->setMaxResults($limit); return $entities->matching($crit)->map(function ($item) { return clone $item; }); }; // Overload main EntityManager functions $this->calling($entityManagerMock)->getRepository = function () use($entityRepositoryMock) { return $entityRepositoryMock; }; $this->calling($entityManagerMock)->getClassMetadata = function ($entity) use($classMetadata) { return $classMetadata; }; $this->calling($entityManagerMock)->persist = function ($entity) use($test, $entityName) { if (!$entity->getId()) { if (!empty($test->database[$entityName])) { $entity->setId(count($test->database[$entityName]) + 1); } else { $entity->setId(1); } } $test->database[$entityName][$entity->getId()] = $entity; return true; }; $this->calling($entityManagerMock)->remove = function ($entity) use($test, $entityName) { if (!$entity->getId() || empty($test->database[$entityName][$entity->getId()])) { return false; } unset($test->database[$entityName][$entity->getId()]); return true; }; $mockClass = '\\mock' . $manager['className']; $managerMock = new $mockClass($entityManagerMock, $entityName); $this->mockedManager[$manager['serviceName']] = $managerMock; } } }
public function testMatchingWithSortingPreservesyKeys() { $object1 = new \stdClass(); $object2 = new \stdClass(); $object1->sortField = 2; $object2->sortField = 1; $collection = new ArrayCollection(array('object1' => $object1, 'object2' => $object2)); $this->assertSame(array('object2' => $object2, 'object1' => $object1), $collection->matching(new Criteria(null, array('sortField' => Criteria::ASC)))->toArray()); }
public function matching(Criteria $criteria) { if (null === $this->entries) { $this->__load___(); } return $this->entries->matching($criteria); }
/** * Gets permissions of the given user * * @param User $user * @param Criteria|null $filters * * @return array */ public function getUserPermissions(User $user, Criteria $filters = null) { $entityAclExtension = $this->aclSelector->select($user); $resources = array_map(function (AclClassInfo $class) use($entityAclExtension) { return ['type' => $entityAclExtension->getExtensionKey(), 'resource' => $class->getClassName()]; }, $entityAclExtension->getClasses()); if ($filters) { $collection = new ArrayCollection($resources); $resources = $collection->matching($filters)->toArray(); } $result = []; $originalToken = $this->impersonateUser($user); try { foreach ($resources as $resource) { $oid = new ObjectIdentity($resource['type'], $resource['resource']); $permissions = []; foreach ($entityAclExtension->getAllowedPermissions($oid) as $permission) { if ($this->securityContext->isGranted($permission, $oid)) { $permissions[] = $permission; } } $result[] = array_merge($resource, ['permissions' => $permissions]); } $this->undoImpersonation($originalToken); } catch (\Exception $e) { $this->undoImpersonation($originalToken); throw $e; } return $result; }
private function getVoteInfoAssignment(AbstractTerritoire $territoire) { // try to fetch from cache if (isset($this->cache['voteInfo'][spl_object_hash($territoire)])) { return $this->cache['voteInfo'][spl_object_hash($territoire)]; } // if not in cache, not changed, so we dont mind fetching from db if ($this->voteInfos instanceof PersistentCollection) { $this->voteInfos->setDirty(false); } $criteria = Criteria::create()->where(Criteria::expr()->eq('territoire_id', $territoire->getId())); $collection = $this->voteInfos->matching($criteria); if ($this->voteInfos instanceof PersistentCollection) { $this->voteInfos->setDirty(true); } // filter again if territoire_id were not initialized $criteria = Criteria::create()->where(Criteria::expr()->eq('territoire', $territoire)); $array = array_values($collection->matching($criteria)->toArray()); if (array_key_exists(0, $array)) { $voteInfoAssignment = $array[0]; } // new one if not found if (!isset($voteInfoAssignment)) { $voteInfoAssignment = new VoteInfoAssignment($this, $territoire); $this->voteInfos[] = $voteInfoAssignment; } // put to cache $this->cache['voteInfo'][spl_object_hash($territoire)] = $voteInfoAssignment; return $voteInfoAssignment; }
public function getPluginByCriteria($criteria, $needle) { $eb = new ExpressionBuilder(); $expr = $eb->eq($criteria, $needle); $criteria = new Criteria($expr); $availablePlugins = new ArrayCollection($this->getAllAvailablePlugins()); return $availablePlugins->matching($criteria); }
public function getAnnouncements() { $eb = new ExpressionBuilder(); $expr = $eb->eq('removed', false); $criteria = new Criteria($expr); $announcements = new ArrayCollection($this->announcements->toArray()); return $announcements->matching($criteria); }
/** * @Given /^Records in \'([^\']+)\' where \'([^\']+)\', has data$/ * @param $tableName * @param $where * @param TableNode $table * @throws \Doctrine\DBAL\DBALException * @throws \Exception */ public function thereAreRecordsInWhere($tableName, $where, TableNode $table) { /** @var Connection $connection */ $connection = $this->container->get('doctrine')->getConnection(); $exists = new ArrayCollection($connection->query("SELECT * FROM {$tableName} WHERE {$where}")->fetchAll()); $criteria = new Criteria(); $recordsMatching = $exists->matching($criteria); $record = $recordsMatching->first(); $i = 1; foreach ($table as $row) { foreach ($row as $key => $value) { \PHPUnit_Framework_Assert::assertArrayHasKey($key, $record, "Column '{$key}' doesn't exists in database"); \PHPUnit_Framework_Assert::assertEquals($value, $record[$key], "Invalid value for '{$key}' in row {$i}"); } ++$i; } }
/** * Filter a result set for a given configuration. * * @param ActiveConfigurationInterface $config * @param array $data * @return array */ public static function filter(ActiveConfigurationInterface $config, array $data) { $data = new ArrayCollection($data); $filters = $config->getFields(); $filterOptions = $config->getOriginalConfig()->getFields(); $fields = array_keys($filters); $criteria = Criteria::create(); foreach ($fields as $field) { foreach ($filters[$field] as $key => $filter) { $resolver = new OptionsResolver(); $filter->configureOptions($resolver); $options = $filter->resolveOptions($resolver, $filterOptions[$field][$key]->getOptions()); $filter->filter($criteria, $config->getField($field), $options); } } return $data->matching($criteria)->getValues(); }
/** * Get head email in thread * * @param EntityManager $entityManager * @param Email $entity * * @return Email */ public function getHeadEmail(EntityManager $entityManager, Email $entity) { $headEmail = $entity; $thread = $entity->getThread(); if ($thread) { $emails = new ArrayCollection($this->getThreadEmails($entityManager, $entity)); $criteria = new Criteria(); $criteria->orderBy(['sentAt' => Criteria::DESC]); $criteria->setMaxResults(1); $unseenEmails = $emails->matching($criteria); if (count($unseenEmails)) { $headEmail = $unseenEmails[0]; } elseif (count($emails)) { $headEmail = $emails[0]; } } return $headEmail; }
/** * Collects terms where $prop matches $value * * @return ArrayCollection */ protected function getTermsBy($prop, $value) { $criteria = new Criteria(Criteria::expr()->eq($prop, $value)); return $this->terms->matching($criteria); }
/** * Get user from course by status * @param \Chamilo\CoreBundle\Entity\Course $course * @param string $status * @return \Doctrine\Common\Collections\Collection|static */ public function getUserCourseSubscriptionsByStatus(Course $course, $status) { $criteria = Criteria::create()->where(Criteria::expr()->eq("course", $course))->andWhere(Criteria::expr()->eq("status", $status)); return $this->userCourseSubscriptions->matching($criteria); }
/** * Get Country Description by language * * @param integer $languageId * @return CountryDescription */ public function getCountryDescriptionByLanguage($languageId = 2) { $criteria = Criteria::create(); $criteria->where(Criteria::expr()->eq('languageId', $languageId)); return $this->descriptions->matching($criteria)->current(); }
/** * @param string $name * * @return \Doctrine\Common\Collections\Collection */ public function getMetaByKey($name) { $criteria = Criteria::create(); $criteria->where(Criteria::expr()->eq('key', $name)); return $this->metas->matching($criteria); }
public function testMultiColumnSortAppliesAllSorts() { $collection = new ArrayCollection(array(array('foo' => 1, 'bar' => 2), array('foo' => 2, 'bar' => 4), array('foo' => 2, 'bar' => 3))); $expected = array(1 => array('foo' => 2, 'bar' => 4), 2 => array('foo' => 2, 'bar' => 3), 0 => array('foo' => 1, 'bar' => 2)); $this->assertSame($expected, $collection->matching(new Criteria(null, array('foo' => Criteria::DESC, 'bar' => Criteria::DESC)))->toArray()); }
/** * Determine whether user is a winning participant * * @return ArrayCollection */ public function checkIfUserIsWinningParticipant(User $user) { $criteria = Criteria::create()->where(Criteria::expr()->eq('winner', true))->andWhere(Criteria::expr()->eq('user', $user))->setMaxResults(1); return $this->participants->matching($criteria)->count() === 1; }
/** * Retrieve a single meta field. * * @param string $key * @return UserMetaField|bool */ public function getMetaField($key) { $filter = Criteria::create()->where(Criteria::expr()->eq('key', $key))->setMaxResults(1); return $this->meta->matching($filter)->first(); }
/** * Get Subnodes sorted by priority. * * @return \Doctrine\Common\Collections\ArrayCollection Subnodes */ public function getSubnodes() { $sort = \Doctrine\Common\Collections\Criteria::create(); $sort->orderBy(['priority' => \Doctrine\Common\Collections\Criteria::DESC]); return $this->subnodes->matching($sort); }
public function findAllBySpecification(ISpecificationCriteria $specification) { return $this->collection->matching($specification->getCriteria()); }
public function hasErrors() { $criteria = new Criteria(); $criteria->where($criteria->expr()->eq('error', TRUE)); return count($this->outputs->matching($criteria)) !== 0; }
/** * Get Content by Language * * @return mixed * * @param $language */ public function getCurrentContent($language) { $criteria = Criteria::create()->where(Criteria::expr()->eq("language", $language)); $translatableContent = $this->contents->matching($criteria)->first(); return $translatableContent; }
/** * @param Event $event * @return bool */ public function hasEventEntry(Event $event) { $trialIds = []; foreach ($event->getTrials() as $trial) { $trialIds[] = $trial->getId(); } return (bool) count($this->entries->matching(Criteria::create()->where(Criteria::expr()->in('trial', $trialIds)))); }
if (isset($_POST['action'])) { $bdi = new BookDaoImp($entityManager); $books = $bdi->getAllBooks(); $collections = new ArrayCollection($books); if (isset($_POST['sort'])) { if (strcmp($_POST['sort'], 'high') == 0) { $criteria = Criteria::create()->orderBy(array("price" => Criteria::DESC)); } else { if (strcmp($_POST['sort'], 'low') == 0) { $criteria = Criteria::create()->orderBy(array("price" => Criteria::ASC)); } } } else { $criteria = Criteria::create()->orderBy(array("price" => Criteria::ASC)); } $sortedBooks = $collections->matching($criteria); if (isset($_POST['page']) && strcmp($_POST['action'], 'square') == 0) { if (sizeof($books) > 0) { $display = ""; $j = 0; $np = intval($_POST['page']); $nbr = getNumberBooks($np, count($books)); if (isset($_POST['min']) && isset($_POST['max'])) { $min = intval($_POST['min']); $max = intval($_POST['max']); } else { $min = 0; $max = 100000; } for ($i = 6 * ($np - 1); $i < 6 * $np; $i++) { if ($sortedBooks[$i]->getPrice() <= $max && $sortedBooks[$i]->getPrice() >= $min) {
/** * @group DDC-2430 */ public function testMatchingCriteriaAssocationInWithArray() { list($userId, $addressId) = $this->loadAssociatedFixture(); $user = $this->_em->find('Doctrine\\Tests\\Models\\CMS\\CmsUser', $userId); $criteria = new Criteria(Criteria::expr()->in('user', array($user))); $repository = $this->_em->getRepository('Doctrine\\Tests\\Models\\CMS\\CmsAddress'); $addresses = $repository->matching($criteria); $this->assertEquals(1, count($addresses)); $addresses = new ArrayCollection($repository->findAll()); $this->assertEquals(1, count($addresses->matching($criteria))); }
/** * Get Data by Language * * @return mixed * * @param $language */ public function getCurrentData($language) { $criteria = Criteria::create()->where(Criteria::expr()->eq("language", $language)); $translatableData = $this->datas->matching($criteria)->first(); return $translatableData; }
/** * @param Division $division * @return TrialDivision */ public function getTrialDivisionForDivision(Division $division) { return $this->trialDivisions->matching(Criteria::create()->where(Criteria::expr()->eq('division', $division)))->first(); }
/** * @param integer $id * @return CartItem|null */ public function findItem($id) { $criteria = Criteria::create()->where(Criteria::expr()->eq('id', $id)); return $this->items->matching($criteria)->first(); }
/** * Взять один или несколько предметов * @param User $user * @param Item|Item[] $items * @param int $quantityToTake Сколько предметов взять */ public function takeItems(User $user, $items, int $quantityToTake = 1) { $itemsToTake = $this->prepareItemsArray($items); $inventoryItems = $this->inventoryItemRepository->findByUser($user); $inventoryItemCollection = new ArrayCollection($inventoryItems); foreach ($itemsToTake as $itemToTake) { $criteria = Criteria::create(); $criteria->where(Criteria::expr()->eq('item', $itemToTake)); $collectedInventoryItem = $inventoryItemCollection->matching($criteria); if ($collectedInventoryItem->count() === 1) { $inventoryItem = $collectedInventoryItem->first(); $quantity = $inventoryItem->getQuantity() + $quantityToTake; $inventoryItem->setQuantity($quantity); } elseif ($collectedInventoryItem->count() === 0) { $inventoryItem = new InventoryItem($user, $itemToTake, $quantityToTake); $this->inventoryItemRepository->persist($inventoryItem); } else { throw new \RuntimeException('Найдено более одного предмета'); } } $this->inventoryItemRepository->flush(); $this->logObtainedItems($user, $itemsToTake, $quantityToTake); }
/** * @return bool */ public function requiresStatus() { $criteria = Criteria::create(); $criteria->where($criteria->expr()->contains('cell', 'status')); return count($this->columns->matching($criteria)) > 0; }
/** * Get other TransPosts for current Language * * @param $language * @return \Doctrine\Common\Collections\Collection|static */ public function getOtherTransPosts($language) { $result = []; $iterator = 0; $condition = true; $criteria = Criteria::create()->where(Criteria::expr()->neq('language', $language))->andWhere(Criteria::expr()->eq('enabled', $condition)); $transPosts = $this->transPosts->matching($criteria); foreach ($transPosts as $transPost) { $result[$iterator]['id'] = $transPost->getId(); $result[$iterator]['locale'] = $transPost->getLanguage()->getLocale(); $iterator++; } return $result; }