/** * @param Request $request * @param FilterInterface $filter * @param Criteria $criteria * @param ClassMetadata $embedClassMeta * * @return null */ protected function applyFilter(Request $request, FilterInterface $filter, Criteria $criteria, ClassMetadata $embedClassMeta) { $properties = $filter->getRequestProperties($request); if ($filter instanceof OrderFilter && !empty($properties)) { $criteria->orderBy($properties); return null; } if ($filter instanceof SearchFilter) { foreach ($properties as $name => $propertie) { if (in_array($name, $embedClassMeta->getIdentifier())) { continue; } $expCriterial = Criteria::expr(); if ($embedClassMeta->hasAssociation($name)) { $associationTargetClass = $embedClassMeta->getAssociationTargetClass($name); $propertyResource = $this->resourceResolver->getResourceForEntity($associationTargetClass); $propertyObj = $this->dataProviderChain->getItem($propertyResource, (int) $propertie['value'], true); if ($propertyObj && $propertyResource instanceof ResourceInterface) { $whereCriteria = $expCriterial->in($name, [$propertyObj]); $criteria->where($whereCriteria); } } else { if ($embedClassMeta->hasField($name)) { $fieldMapping = $embedClassMeta->getFieldMapping($name); $type = isset($fieldMapping['type']) ? $fieldMapping['type'] : null; $value = isset($this->mappingFilterVar[$type]) ? filter_var($propertie['value'], $this->mappingFilterVar[$type]) : $propertie['value']; $whereCriteria = isset($propertie['precision']) && $propertie['precision'] === 'exact' ? $expCriterial->eq($name, $value) : $expCriterial->contains($name, $propertie['value']); $criteria->where($whereCriteria); } } } } }
private function createCriteria() { $criteria = new Criteria(); $criteria->orderBy(array('username' => 'ASC')); $criteria->setFirstResult(2); $criteria->setMaxResults(3); return $criteria; }
protected function generateMenu() { $criteria = new Criteria(); $criteria->orderBy(['hierarchy' => 'asc']); $collection = $this->adminMenuRepository->matching($criteria); $elements = $this->filterElements($collection, null); $tree = $this->generateTree($collection, $elements); return $tree; }
/** * {@inheritdoc} */ public function apply(Criteria $criteria, FilterValue $value = null) { $val = null !== $value ? $value->getValue() : $this->getDefaultValue(); if (!empty($val)) { $criteria->orderBy($val); } }
/** * Gets emails by ids * * @param int[] $ids * * @return Email[] */ public function findEmailsByIds($ids) { $queryBuilder = $this->createQueryBuilder('e'); $criteria = new Criteria(); $criteria->where(Criteria::expr()->in('id', $ids)); $criteria->orderBy(['sentAt' => Criteria::DESC]); $queryBuilder->addCriteria($criteria); $result = $queryBuilder->getQuery()->getResult(); return $result; }
public function getMenu() { $criteria = new Criteria(); $criteria->orderBy(['hierarchy' => 'asc']); $criteria->andWhere($criteria->expr()->eq('parent', null)); return $this->adminMenuRepository->matching($criteria); }
/** * {@inheritdoc} */ public function load(ObjectManager $manager) { $criteria = new Criteria(); $criteria->where($criteria->expr()->neq('xThreadId', null)); /** @var QueryBuilder $threadQueryBuilder */ $threadQueryBuilder = $manager->getRepository('OroEmailBundle:Email')->createQueryBuilder('entity'); $threadQueryBuilder->distinct()->select('entity.xThreadId'); $threadQueryBuilder->addCriteria($criteria); $iterator = new BufferedQueryResultIterator($threadQueryBuilder); $iterator->setBufferSize(self::BATCH_SIZE); $itemsCount = 0; $entities = []; foreach ($iterator as $threadResult) { $threadId = $threadResult['xThreadId']; /** @var QueryBuilder $queryBuilder */ $queryBuilder = $manager->getRepository('OroEmailBundle:Email')->createQueryBuilder('entity'); $criteria = new Criteria(); $criteria->where($criteria->expr()->eq('xThreadId', $threadId)); $criteria->orderBy(['created' => 'ASC']); $queryBuilder->addCriteria($criteria); $queryBuilder->setFirstResult(0); $emails = $queryBuilder->getQuery()->execute(); if (count($emails) > 1) { $itemsCount++; $newThread = new EmailThread(); $manager->persist($newThread); foreach ($emails as $key => $email) { /** @var Email $email */ if ($key == 0) { $email->setHead(true); } else { $email->setHead(false); } $email->setThread($newThread); $entities[] = $email; } } elseif (count($emails) == 1) { $email = $emails[0]; $email->setHead(true); $itemsCount++; $entities[] = $email; } if (0 == $itemsCount % self::BATCH_SIZE) { $this->saveEntities($manager, $entities); $entities = []; } } if ($itemsCount % self::BATCH_SIZE > 0) { $this->saveEntities($manager, $entities); } }
/** * {@inheritdoc} */ public function getShippingMethods() : Collection { $criteria = new Criteria(); $criteria->where($criteria->expr()->eq('enabled', true)); $criteria->orderBy(['hierarchy' => 'asc']); $methods = $this->matching($criteria)->filter(function (ShippingMethodInterface $shippingMethod) { $paymentMethodsCount = $shippingMethod->getPaymentMethods()->count(); $shippingMethodCostCount = $shippingMethod->getCosts()->count(); return $paymentMethodsCount > 0 && $shippingMethodCostCount > 0; }); return $methods; }
public function createService(ServiceLocatorInterface $serviceLocator) { $entityManager = $serviceLocator->get('entity-manager'); $languageEntity = $serviceLocator->get('lang-entity'); $criteria = new Criteria(); $criteria->where($criteria->expr()->gt('status', 0))->orderBy(['status' => Criteria::DESC]); $language = new \Application\Service\Invokable\Language(); $languageClassName = get_class($languageEntity); $activeLanguages = $entityManager->getRepository($languageClassName)->matching($criteria); $language->setActiveLanguages($activeLanguages); $defaultLanguage = $entityManager->getRepository($languageClassName)->findOneByStatus(Lang::STATUS_DEFAULT); $defaultLanguage = $defaultLanguage ?: new Lang(); $language->setDefaultLanguage($defaultLanguage); $request = $serviceLocator->get('Request'); $router = $serviceLocator->get('Router'); $match = $router->match($request); if ($match) { $matchedLangIso = $match->getParam('lang', $defaultLanguage->getIsoCode()); if ($matchedLangIso) { $currentLanguage = $entityManager->getRepository($languageClassName)->findOneByIsoCode($matchedLangIso); } } $currentLanguage = isset($currentLanguage) ? $currentLanguage : new Lang(); $language->setCurrentLanguage($currentLanguage); return $language; }
public function findByTag($tagstring) { $criteria = new Criteria(); $criteria->andWhere(Criteria::expr()->contains('t.name', "%" . $tagstring . "%")); $queryBuilder = $this->_em->createQueryBuilder()->select('p')->distinct(true)->from($this->getEntityName(), "p")->leftJoin('Product\\Entity\\ProductTags', 'pt', \Doctrine\ORM\Query\Expr\Join::WITH, 'p.id = pt.idProduct')->leftJoin('Product\\Entity\\Tags', 't', \Doctrine\ORM\Query\Expr\Join::WITH, 't.id = pt.idTag')->addCriteria($criteria)->orderBy("p.creationdate", "ASC")->getQuery(); return $queryBuilder->getArrayResult(); }
public function testMatchingAcceptsCriteriaWithNullWhereExpression() { $repository = $this->dm->getRepository('Documents\\User'); $criteria = new Criteria(); $this->assertNull($criteria->getWhereExpression()); $this->assertInstanceOf('Doctrine\\Common\\Collections\\Collection', $repository->matching($criteria)); }
protected function execute(InputInterface $input, OutputInterface $output) { $indexName = $input->getOption('index'); $batchSize = $input->getOption('batch_size'); $indexManager = $this->getIndexManager($indexName); $totalDocuments = $indexManager->getTotalEntities(); $iterations = $this->getIterations($totalDocuments, $batchSize); $output->writeln(sprintf('<info>Reindexing</info> "%s"', $indexName)); $output->writeln(sprintf('<comment>Total documents:</comment> %s', $totalDocuments)); $output->writeln(sprintf('<comment>Batch size:</comment> %s', $batchSize)); $output->writeln(sprintf('<comment>Iterations:</comment> %s', $iterations)); $progress = new ProgressBar($output, $totalDocuments); $progress->setFormat('verbose'); $progress->setRedrawFrequency($batchSize); $progress->start(); $indexManager->purgeIndex(); for ($i = 0; $i < $iterations; $i++) { $criteria = new Criteria(); $criteria->setMaxResults($batchSize); $criteria->setFirstResult($i * $batchSize); $collection = $indexManager->getEntitiesCollection($criteria); $collection->map(function (EntityInterface $entity) use($indexManager, $progress) { $indexManager->addEntity($entity); $progress->advance(); }); } $progress->finish(); $output->writeln(''); $output->writeln(sprintf('<info>Optimizing "%s"</info>', $indexName)); $indexManager->optimizeIndex(); }
/** * {@inheritdoc} */ public function apply(Criteria $criteria, FilterValue $value = null) { $val = null !== $value ? $value->getValue() : $this->getDefaultValue(); if (null !== $val) { $criteria->setMaxResults($val); } }
/** * @param User $user * @param int $limit * @return Collection|Game[] */ public function findAvailableForUser(User $user, $limit) { $criteria = new Criteria(); $expr = Criteria::expr(); $criteria->where($expr->neq('user1', $user))->andWhere($expr->isNull('user2'))->setMaxResults($limit)->orderBy(['id' => 'DESC']); return $this->matching($criteria); }
public function testUsersWithFacebookLogin() { $criteria = new Criteria(); $criteria->where($criteria->expr()->neq('facebook_id', null)); $users = $this->getUserRepository()->matching($criteria); $this->assertCount(8, $users); }
/** * Get items * @author Mohamed Labib <*****@*****.**> * * @access public * * @param int $offset * @param int $itemCountPerPage * @return array items queried */ public function getItems($offset, $itemCountPerPage) { $this->setCriteria(); $this->criteria->setFirstResult($offset); $this->criteria->setMaxResults($itemCountPerPage); return $this->query->filter($this->entityName, $this->criteria); //($pageNumber-1) for zero based count }
/** * Finds operations * * @param Status $status status to filter upon * @param DateTime $date optional date to filter upon * * @return OperationInterface[] */ public function findByStatusAndBeforeUpdatedAt(Status $status, DateTime $date) { $criteria = new Criteria(); $exprBuilder = new ExpressionBuilder(); $criteria->where($exprBuilder->eq('status', $status->getValue())); $criteria->andWhere($exprBuilder->lte('updatedAt', $date)); return $this->matching($criteria)->toArray(); }
public function count(array $criteria) { $criteriaObj = new Criteria(); foreach ($criteria as $field => $value) { $criteriaObj->where($criteriaObj->expr()->eq($field, $value)); } return $this->repository->matching($criteriaObj)->count(); }
/** * @depends testUpdate */ public function testFind() { $criteria = new Criteria(); $expression = new ExpressionBuilder(); $exp = $expression->eq('username', 'john'); $criteria->where($exp); $this->assertEquals(1, count($this->getRepository(UserExtraEntity::class)->findBy($criteria))); $this->assertEquals(2, count($this->getRepository(UserExtraEntity::class)->findAll())); }
/** * {@inheritdoc} */ public function apply(Criteria $criteria, FilterValue $value = null) { $val = null !== $value ? $value->getValue() : $this->getDefaultValue(); if (null !== $val) { $pageSize = $criteria->getMaxResults(); if (null !== $pageSize) { $criteria->setFirstResult(QueryUtils::getPageOffset($val, $pageSize)); } } }
public function copyLocaleData(LocaleInterface $sourceLocale, LocaleInterface $targetLocale) { $criteria = new Criteria(); $criteria->where($criteria->expr()->eq('locale', $sourceLocale->getCode())); foreach ($this->entityClasses as $className => $options) { $repository = $this->doctrineHelper->getRepositoryForClass($className); $entities = $repository->matching($criteria); $this->duplicateTranslatableEntities($entities, $options['properties'], $targetLocale); } $this->doctrineHelper->getEntityManager()->flush(); }
/** * list the projects * @return \Zend\View\Model\ViewModel */ public function indexAction() { $usuario = $this->getEm()->getRepository('MyClasses\\Entities\\AclUsuario')->findOneBy(array("id" => $this->identity()[0]->getId())); if ($this->identity()[1] == "adm") { $criterio = new Criteria(); $criterio->where($criterio->expr()->eq('usuario', $usuario))->orWhere($criterio->expr()->isNull('usuario')); $projetos = $this->getEm()->getRepository('MyClasses\\Entities\\Projeto')->matching($criterio); } else { $projetos = $usuario->getProjetos(); } return new ViewModel(array('projetos' => $projetos)); }
public function loadUserByUsername($username) { $criteria = new Criteria(); $criteria->where(new Comparison("username", Comparison::EQ, $username)); $criteria->orWhere(new Comparison("email", Comparison::EQ, $username)); $criteria->setMaxResults(1); $user = $this->em->getRepository("CoreUserBundle:User")->matching($criteria)->first(); if ($user) { return $user; } //throw new UsernameNotFoundException(sprintf('Username "%s" does not exist.', $username)); throw new BadCredentialsException("Bad credentials."); }
/** * @param Game $game * @param string $eventType * @param int $player 1|2 * @return Criteria */ private function createFindForGameByTypeAndPlayerCriteria(Game $game, $eventType = null, $player = null) { $criteria = new Criteria(); $expr = Criteria::expr(); $criteria->where($expr->eq('game', $game)); if ($eventType !== null) { $criteria->andWhere($expr->eq('type', $eventType)); } if ($player !== null) { $criteria->andWhere($expr->eq('player', $player)); } return $criteria; }
/** * @depends testSearchEntity */ public function testDeleteWithGlobalIndexEntity() { $criteria = new Criteria(); $exp = new ExpressionBuilder(); $criteria->where($exp->eq('is_default', 'true')); $result = $this->getDriver()->findBy($criteria, $this->getClassMetadata()); $this->assertEquals(2, count($result)); foreach ($result as $item) { $result = $this->getDriver()->deleteItem(['scope_name' => $item['scope_name']], $this->getClassMetadata()); $this->assertTrue($result); } $result = $this->getDriver()->findBy($criteria, $this->getClassMetadata()); $this->assertEquals(0, count($result)); }
public function resolve(int $currentShopId, string $url) : ShopInterface { $criteria = new Criteria(); $criteria->where($criteria->expr()->eq('id', $currentShopId)); $criteria->orWhere($criteria->expr()->eq('url', $url)); $criteria->orWhere($criteria->expr()->gte('id', 1)); return $this->matching($criteria)->first(); }
/** * * @param \DateTime $startDate beginning >= * @param \DateTime $endDate end <= * @param $type - type of the StatisticEntryFilter * * @return StatisticEntry[] * * Note: can be replaced with DQL if performance issues are notable */ public function getStatisticForRangeAndType(\DateTime $startDate, \DateTime $endDate, $type = null) { /** @var TrainingDayRepository $trainingDayRepository */ $trainingDayRepository = $this->manager->getRepository('TrainingScheduleBundle:TrainingDay'); $expr = Criteria::expr(); $criteria = Criteria::create(); $criteria->where($expr->gte('date', $startDate)); $criteria->andWhere($expr->lte('date', $endDate)); $criteria->andWhere($expr->eq('user', $this->userToken->getUser())); /** @var LazyCriteriaCollection $trainingDays */ $trainingDays = $trainingDayRepository->matching($criteria); $result = array(); /** @var TrainingDay $trainingDay * */ foreach ($trainingDays as $trainingDay) { foreach ($trainingDay->getStatistics() as $statistic) { /** @var StatisticEntry $statistic */ if ($type != null) { if ($statistic->getName() === $type) { $result[] = $statistic; } } else { $result[] = $statistic; } } } return $result; }
/** * Gets search result * * @param int $page Page number * @param int $limit Number of items per page * @param string $search The search string. * @param Criteria|null $criteria * * @return array */ public function getSearchResult($page = 1, $limit = 10, $search = '', $criteria = null) { $searchQuery = $this->searchIndexer->getSimpleSearchQuery($search, $this->getOffset($page, $limit), $limit, $this->getCustomerSearchAliases()); if ($criteria && ($expression = $criteria->getWhereExpression())) { $searchQuery->getCriteria()->andWhere($expression); } $searchResult = $this->searchIndexer->query($searchQuery); $result = ['result' => [], 'totalCount' => function () use($searchResult) { return $searchResult->getRecordsCount(); }]; if ($searchResult->count() > 0) { $customers = $this->getCustomerListQueryBuilder($searchResult)->getQuery()->getResult(); $result['result'] = $this->mergeResults($searchResult, $customers); } return $result; }
/** * Returns the context for the given email * * @param Email $email * * @return array */ public function getEmailContext(Email $email) { $criteria = Criteria::create(); $criteria->andWhere(Criteria::expr()->eq('id', $email->getId())); $qb = $this->activityManager->getActivityTargetsQueryBuilder($this->class, $criteria); if (null === $qb) { return []; } $result = $qb->getQuery()->getResult(); if (empty($result)) { return $result; } $currentUser = $this->securityFacade->getLoggedUser(); $currentUserClass = ClassUtils::getClass($currentUser); $currentUserId = $currentUser->getId(); $result = array_values(array_filter($result, function ($item) use($currentUserClass, $currentUserId) { return !($item['entity'] === $currentUserClass && $item['id'] == $currentUserId); })); foreach ($result as &$item) { $route = $this->configManager->getEntityMetadata($item['entity'])->getRoute(); $item['entityId'] = $email->getId(); $item['targetId'] = $item['id']; $item['targetClassName'] = $this->entityClassNameHelper->getUrlSafeClassName($item['entity']); $item['icon'] = $this->configManager->getProvider('entity')->getConfig($item['entity'])->get('icon'); $item['link'] = $route ? $this->router->generate($route, ['id' => $item['id']]) : null; unset($item['id'], $item['entity']); } return $result; }
public function testLteDateComparison() { $this->loadFixture(); $repository = $this->_em->getRepository('Doctrine\\Tests\\Models\\Generic\\DateTimeModel'); $dates = $repository->matching(new Criteria(Criteria::expr()->lte('datetime', new \DateTime('today')))); $this->assertEquals(2, count($dates)); }