Create a new Query instance for a class.
public createQueryBuilder ( string $documentName = null ) : Query\Builder | ||
$documentName | string | The document class name. |
return | Query\Builder |
/** * mongo_exists:users,email_address,10 * * @param $attribute * @param $value * @param $parameters * @return bool */ public function validate($attribute, $value, $parameters) { $collection = $parameters[0]; if (empty($parameters[1])) { $field = 'id'; } else { $field = $parameters[1]; } return (bool) $this->documentManager->createQueryBuilder($collection)->field($field)->equals($value)->count()->getQuery()->execute(); }
/** * mongo_unique:users,email_address,10 * * @param $attribute * @param $value * @param $parameters * @return bool */ public function validate($attribute, $value, $parameters) { if (is_null($value)) { return true; } $collection = $parameters[0]; $field = $parameters[1]; if (!empty($paramers[2]) && $value == $parameters[2]) { return true; } return !(bool) $this->documentManager->createQueryBuilder($collection)->field($field)->equals($value)->count()->getQuery()->execute(); }
public function testPriming() { $quiz = new Quiz(); $this->persistQuizWithQuestions($quiz); $qb = $this->dm->createQueryBuilder(get_class($quiz))->field('id')->equals($quiz->id)->field('questions')->prime(true); $receivedQuiz = $qb->getQuery()->execute()->getSingleResult(); $this->assertCount(2, $receivedQuiz->questions); $this->assertFalse($receivedQuiz->questions[0] instanceof Proxy); $this->assertTrue($receivedQuiz->questions[0] instanceof AdvancedQuestion); $this->assertFalse($receivedQuiz->questions[1] instanceof Proxy); $this->assertTrue($receivedQuiz->questions[1] instanceof BasicQuestion); }
/** * Get the last available version for the provided document * * @param VersionableInterface $versionable * * @return Version|null */ protected function getPreviousVersion(VersionableInterface $versionable) { $resourceName = ClassUtils::getClass($versionable); $resourceId = $versionable->getId(); $version = $this->documentManager->createQueryBuilder($this->versionClass)->field('resourceName')->equals($resourceName)->field('resourceId')->equals($resourceId)->limit(1)->sort('loggedAt', 'desc')->getQuery()->getSingleResult(); return $version; }
/** * @param array $subColumn * @param Column \APY\DataGridBundle\Grid\Column\Column */ protected function addReferencedColumnn(array $subColumn, Column $column) { $this->referencedColumns[$subColumn[0]][] = $subColumn[1]; if ($column->isFiltered()) { $helperQuery = $this->manager->createQueryBuilder($this->referencedMappings[$subColumn[0]]); $filters = $column->getFilters('document'); foreach ($filters as $filter) { $operator = $this->normalizeOperator($filter->getOperator()); $value = $this->normalizeValue($filter->getOperator(), $filter->getValue()); $helperQuery->field($subColumn[1])->{$operator}($value); $this->prepareQuery($this->query); $cursor = $helperQuery->getQuery()->execute(); foreach ($cursor as $resource) { if ($cursor->count() > 0) { $this->query->select($subColumn[0]); } if ($cursor->count() == 1) { $this->query->field($subColumn[0])->references($resource); } else { $this->query->addOr($this->query->expr()->field($subColumn[0])->references($resource)); } } } } }
function let(DocumentManager $documentManager, UnitOfWork $unitOfWork, ClassMetadata $class, Builder $queryBuilder, Query $query) { $class->name = 'spec\\Sylius\\Bundle\\ResourceBundle\\Fixture\\Document\\TranslatableFoo'; $documentManager->createQueryBuilder($class->name)->willReturn($queryBuilder); $queryBuilder->getQuery()->willReturn($query); $this->beConstructedWith($documentManager, $unitOfWork, $class); }
private function loadReferenceManyCollectionInverseSide(PersistentCollection $collection) { $mapping = $collection->getMapping(); $owner = $collection->getOwner(); $ownerClass = $this->dm->getClassMetadata(get_class($owner)); $criteria = array_merge( array($mapping['mappedBy'].'.'.$this->cmd.'id' => $ownerClass->getIdentifierObject($owner)), $mapping['criteria'] ); $qb = $this->dm->createQueryBuilder($mapping['targetDocument']) ->setQueryArray($criteria); if ($mapping['sort']) { $qb->sort($mapping['sort']); } if ($mapping['limit']) { $qb->limit($mapping['limit']); } if ($mapping['skip']) { $qb->skip($mapping['skip']); } $query = $qb->getQuery(); $cursor = $query->execute(); foreach ($cursor as $document) { $collection->add($document); } }
private function loadReferenceManyCollectionInverseSide(PersistentCollection $collection) { $hints = $collection->getHints(); $mapping = $collection->getMapping(); $owner = $collection->getOwner(); $ownerClass = $this->dm->getClassMetadata(get_class($owner)); $targetClass = $this->dm->getClassMetadata($mapping['targetDocument']); $mappedByMapping = $targetClass->fieldMappings[$mapping['mappedBy']]; $mappedByFieldName = isset($mappedByMapping['simple']) && $mappedByMapping['simple'] ? $mapping['mappedBy'] : $mapping['mappedBy'] . '.id'; $criteria = array_merge(array($mappedByFieldName => $ownerClass->getIdentifierObject($owner)), isset($mapping['criteria']) ? $mapping['criteria'] : array()); $qb = $this->dm->createQueryBuilder($mapping['targetDocument'])->setQueryArray($criteria); if (isset($mapping['sort'])) { $qb->sort($mapping['sort']); } if (isset($mapping['limit'])) { $qb->limit($mapping['limit']); } if (isset($mapping['skip'])) { $qb->skip($mapping['skip']); } if (isset($hints[Query::HINT_SLAVE_OKAY])) { $qb->slaveOkay(true); } $documents = $qb->getQuery()->execute()->toArray(); foreach ($documents as $document) { $collection->add($document); } }
/** * @param PersistentCollection $collection * * @return Query */ public function createReferenceManyInverseSideQuery(PersistentCollection $collection) { $hints = $collection->getHints(); $mapping = $collection->getMapping(); $owner = $collection->getOwner(); $ownerClass = $this->dm->getClassMetadata(get_class($owner)); $targetClass = $this->dm->getClassMetadata($mapping['targetDocument']); $mappedByMapping = isset($targetClass->fieldMappings[$mapping['mappedBy']]) ? $targetClass->fieldMappings[$mapping['mappedBy']] : array(); $mappedByFieldName = isset($mappedByMapping['simple']) && $mappedByMapping['simple'] ? $mapping['mappedBy'] : $mapping['mappedBy'] . '.$id'; $criteria = $this->cm->merge(array($mappedByFieldName => $ownerClass->getIdentifierObject($owner)), $this->dm->getFilterCollection()->getFilterCriteria($targetClass), isset($mapping['criteria']) ? $mapping['criteria'] : array()); $criteria = $this->uow->getDocumentPersister($mapping['targetDocument'])->prepareQueryOrNewObj($criteria); $qb = $this->dm->createQueryBuilder($mapping['targetDocument'])->setQueryArray($criteria); if (isset($mapping['sort'])) { $qb->sort($mapping['sort']); } if (isset($mapping['limit'])) { $qb->limit($mapping['limit']); } if (isset($mapping['skip'])) { $qb->skip($mapping['skip']); } if (!empty($hints[Query::HINT_SLAVE_OKAY])) { $qb->slaveOkay(true); } if (!empty($hints[Query::HINT_READ_PREFERENCE])) { $qb->setReadPreference($hints[Query::HINT_READ_PREFERENCE], $hints[Query::HINT_READ_PREFERENCE_TAGS]); } return $qb->getQuery(); }
/** * Find family from list of products * * @param array $productIds * * @return array */ protected function findFamiliesFromProductIds(array $productIds) { $qb = $this->dm->createQueryBuilder($this->documentName); $qb->field('_id')->in($productIds)->distinct('family')->hydrate(false); $cursor = $qb->getQuery()->execute(); return $cursor->toArray(); }
/** * Return a cursor on the product ids belonging the categories * with category ids provided * * @param array $categoryIds * * @return Cursor mongoDB cursor on the Ids */ public function getProductIdsInCategories(array $categoryIds) { if (count($categoryIds) === 0) { return 0; } $qb = $this->documentManager->createQueryBuilder($this->documentName)->hydrate(false)->field('categoryIds')->in($categoryIds)->select('_id'); return $qb->getQuery()->execute(); }
/** * @return ArrayCollection will return collection of objects if it matched them */ public function getMappedMatches() { $mapping = $this->mapping; // $parameters = $mapping->getAvailableParameters(); $matches = $this->matches; $Result = new ArrayCollection(); $params = $mapping->toArray(); $repos = $mapping->findRepository($params[$this->indexName]['parameter'], $params[$this->indexName]['value']); $ids = array(); foreach ($matches as $match) { $ids[] = $match['attrs']['id']; /* $element = $this->dm->getRepository($repos) ->findOneBy(array('id' => $match['attrs']['id'])); $Result->add($element); */ } // cant sort results $elements = $this->dm->createQueryBuilder($repos)->field('id')->in($ids)->getQuery()->execute(); $tmp_elements = array(); foreach ($elements as $element) { $tmp_elements[] = $element; } $total = count($tmp_elements); // temp sort foreach ($ids as $id) { for ($i = 0; $i < $total; $i++) { if (!empty($tmp_elements[$i]) && $tmp_elements[$i]->getId() == $id) { $Result->add($tmp_elements[$i]); unset($tmp_elements[$i]); break; } } } $tmp_elements = null; $elements = null; // foreach ($matches as $match) { // $attrs = array_keys($match['attrs']); // $matchedAttrs = array_intersect($attrs, $parameters); // // if (!count($matchedAttrs)) // continue; // foreach ($matchedAttrs as $matchedAttr) { // $value = $match['attrs'][$matchedAttr]; // $repoName = $mapping->findRepository($matchedAttr, $value); // if ($repoName) { // $repo = $this->dm->getRepository($repoName); // $element = $repo->find($match['attrs']['id']); // if ($element) { // if ($element instanceof SearchableInterface) { // $Result->add($element); // } else { // throw new MappingException(sprintf('Object "%s" don\'t implements interface "SearchableInterface".', get_class($element))); // } // } // } // } // } return $Result; }
public function populateSelectFilters($columns, $loop = false) { $queryFromSource = $this->manager->createQueryBuilder($this->documentName); $queryFromQuery = clone $this->query; // Clean the select fields from the query foreach ($columns as $column) { $queryFromQuery->exclude($column->getField()); } /* @var $column Column */ foreach ($columns as $column) { $selectFrom = $column->getSelectFrom(); if ($column->getFilterType() === 'select' && ($selectFrom === 'source' || $selectFrom === 'query')) { // For negative operators, show all values if ($selectFrom === 'query') { foreach ($column->getFilters('document') as $filter) { if (in_array($filter->getOperator(), array(Column::OPERATOR_NEQ, Column::OPERATOR_NLIKE))) { $selectFrom = 'source'; break; } } } // Dynamic from query or not ? $query = $selectFrom === 'source' ? clone $queryFromSource : clone $queryFromQuery; $result = $query->select($column->getField())->distinct($column->getField())->sort($column->getField(), 'asc')->skip(null)->limit(null)->getQuery()->execute(); $values = array(); foreach ($result as $value) { switch ($column->getType()) { case 'number': $values[$value] = $column->getDisplayedValue($value); break; case 'datetime': case 'date': case 'time': if ($value instanceof \MongoDate || $value instanceof \MongoTimestamp) { $value = $value->sec; } // Mongodb bug ? timestamp value is on the key 'i' instead of the key 't' if (is_array($value) && array_keys($value) == array('t', 'i')) { $value = $value['i']; } $displayedValue = $column->getDisplayedValue($value); $values[$displayedValue] = $displayedValue; break; default: $values[$value] = $value; } } // It avoids to have no result when the other columns are filtered if ($selectFrom === 'query' && empty($values) && $loop === false) { $column->setSelectFrom('source'); $this->populateSelectFilters($columns, true); } else { $column->setValues($values); } } } }
function it_count_all_products(DocumentManager $dm, Builder $builder, Query $query, CursorInterface $cursor) { $dm->createQueryBuilder('foobar')->willReturn($builder); $builder->hydrate(false)->willReturn($builder); $builder->getQuery()->willReturn($query); $query->execute()->willReturn($cursor); $cursor->count()->shouldBeCalled(); $this->countAll(); }
/** * Retorna um token de accesso com base na conexão * @param string $token * @return null|AccessToken */ public function getAccess($token = null) { if ($token == null || empty($token)) { return; } if (null != $this->accessToken) { return $this->accessToken; } if ($token !== null && !is_string($token)) { throw new InvalidArgumentException('Token must be string'); } // Limpa o Basic do token $token = $this->flushToken($token); // Consulta no banco $qb = $this->manager->createQueryBuilder('SimpleAuth\\AccessToken'); $object = $qb->field('token')->equals($token)->getQuery()->getSingleResult(); if ($object !== null) { return $object; } return null; }
/** * @param \Sorien\DataGridBundle\Grid\Column\Column[] $columns * @param int $page Page Number * @param int $limit Rows Per Page * @return \Sorien\DataGridBundle\Grid\Rows */ public function execute($columns, $page = 0, $limit = 0) { $this->query = $this->manager->createQueryBuilder($this->documentName); foreach ($columns as $column) { $this->query->select($column->getField()); if ($column->isSorted()) { $this->query->sort($column->getField(), $column->getOrder()); } if ($column->isFiltered()) { if ($column->getFiltersConnection() == column::DATA_CONJUNCTION) { foreach ($column->getFilters() as $filter) { //normalize values $operator = $this->normalizeOperator($filter->getOperator()); $value = $this->normalizeValue($filter->getOperator(), $filter->getValue()); $this->query->field($column->getField())->{$operator}($value); } } elseif ($column->getFiltersConnection() == column::DATA_DISJUNCTION) { $values = array(); foreach ($column->getFilters() as $filter) { $values[] = $filter->getValue(); } if (!empty($values)) { //@todo probably value normalization needed $this->query->field($column->getField())->all($values); } } } } if ($page > 0) { $this->query->skip($page * $limit); } if ($limit > 0) { $this->query->limit($limit); } //call overridden prepareQuery or associated closure $query = $this->prepareQuery(clone $this->query); //execute and get results $result = new Rows(); $cursor = $query->getQuery()->execute(); $this->count = $cursor->count(); foreach ($cursor as $resource) { $row = new Row(); $properties = $this->getClassProperties($resource); foreach ($columns as $column) { $row->setField($column->getId(), $properties[$column->getId()]); } //call overridden prepareRow or associated closure if (($modifiedRow = $this->prepareRow($row)) != null) { $result->addRow($modifiedRow); } } return $result; }
/** * Constructor. * * @param DocumentManager $dm */ public function __construct(DocumentManager $dm, UnitOfWork $uow) { $this->dm = $dm; $this->uow = $uow; $this->defaultPrimer = function (DocumentManager $dm, ClassMetadata $class, array $ids, array $hints) { $qb = $dm->createQueryBuilder($class->name)->field($class->identifier)->in($ids); if (!empty($hints[Query::HINT_SLAVE_OKAY])) { $qb->slaveOkay(true); } if (!empty($hints[Query::HINT_READ_PREFERENCE])) { $qb->setReadPreference($hints[Query::HINT_READ_PREFERENCE], $hints[Query::HINT_READ_PREFERENCE_TAGS]); } $qb->getQuery()->toArray(); }; }
/** * @param ContentType $contentType * @param string $format * @return Response */ public function generateTable(ContentType $contentType, $format) { $allContent = $this->dm->createQueryBuilder('IntegratedContentBundle:Content\\Content')->hydrate(false)->field('contentType')->equals($contentType->getId())->getQuery(); $fieldNames = []; foreach ($contentType->getFields() as $field) { $fieldNames[$field->getName()] = $field->getName(); } unset($fieldNames['class']); $handle = $format == 'csv' ? tmpfile() : new \PHPExcel(); $columnNames = ['id', 'contentType', 'createdAt', 'updatedAt', 'startDate', 'endDate', 'channels']; foreach ($allContent as $content) { /* main fields*/ $channelIds = array_map(function ($channel) { return $channel['$id']; }, $content['channels']); $values = ['id' => $content['_id'], 'contentType' => $content['contentType'], 'createdAt' => date('Y-m-d H:i:s', $content['createdAt']->sec), 'updatedAt' => date('Y-m-d H:i:s', $content['updatedAt']->sec), 'startDate' => date('Y-m-d H:i:s', $content['publishTime']['startDate']->sec), 'endDate' => date('Y-m-d H:i:s', $content['publishTime']['endDate']->sec), 'channels' => implode(',', $channelIds)]; /* end main fields */ $mainFields = ['_id', 'contentType', 'createdAt', 'updatedAt', 'publishTime', 'channels']; foreach ($fieldNames as $name) { if (!in_array($name, $mainFields, true)) { if (isset($content[$name]) && !is_array($content[$name]) && !is_object($content[$name])) { $values[] = $content[$name]; } else { $values[] = ''; } if (isset($columnNames)) { $columnNames[] = $name; } } } /* add column names*/ if (isset($columnNames)) { $this->addRow($columnNames, $handle, $format); unset($columnNames); } $this->addRow($values, $handle, $format); /* Until 5 seconds to throwing exception with "execution time exceeded", abort export */ $executionTime = microtime(1) - $this->startTime; $allowedTime = ini_get('max_execution_time'); if ($allowedTime - $executionTime < 5) { $partial = array_fill(0, count($values), 'PARTIAL_EXPORT'); $this->addRow($partial, $handle, $format); return $this->getResponse($format, $handle, $contentType); } } return $this->getResponse($format, $handle, $contentType); }
public function count() { $queryBuilder = $this->manager->createQueryBuilder(Document\User::REPOSITORY); return $queryBuilder->getQuery()->count(); }
/** * @param DocumentManager $documentManager * @param $document */ protected function __construct(DocumentManager $documentManager, $document) { $this->queryBuilder = $documentManager->createQueryBuilder($document); $this->document = $document; $this->dm = $documentManager; }
protected function createFakeReference($fake) { $count = $this->dm->createQueryBuilder($fake)->count()->getQuery()->execute(); $offset = rand(0, $count - 1); return $this->dm->createQueryBuilder($fake)->skip($offset)->limit(1)->find()->getQuery()->getSingleResult(); }
/** * {@inheritdoc} */ public function findOneByPartnerId($partnerId) { $qb = $this->dm->createQueryBuilder($this->partnerClass); return $qb->find()->where(sprintf('partnerId = "%s"', $partnerId))->getQuery()->getSingleResult(); }
/** * {@inheritdoc} */ public function scheduleForChannelAndLocale(ChannelInterface $channel, LocaleInterface $locale) { $productQb = $this->documentManager->createQueryBuilder($this->productClass); $pullExpr = $productQb->expr()->addAnd($productQb->expr()->field('channel')->equals($channel->getId()))->addAnd($productQb->expr()->field('locale')->equals($locale->getId())); $productQb->update()->multiple(true)->field(sprintf('normalizedData.completenesses.%s-%s', $channel->getCode(), $locale->getCode()))->unsetField()->field('completenesses')->pull($pullExpr)->getQuery()->execute(); }
/** * {@inheritdoc} */ public function count() { $qb = $this->documentManager->createQueryBuilder($this->productClass); $qb->distinct('values._id'); return $qb->getQuery()->execute()->count(); }
function it_checks_if_the_product_has_an_attribute_in_its_family_but_it_does_not_have_one(FamilyRepositoryInterface $familyRepository, DocumentManager $dm, Builder $builder, Query $query) { $this->setFamilyRepository($familyRepository); $dm->createQueryBuilder('foobar')->willReturn($builder); $builder->field('_id')->willReturn($builder); $builder->equals(10)->willReturn($builder); $builder->hydrate(false)->willReturn($builder); $builder->getQuery()->willReturn($query); $query->getSingleResult()->willReturn([]); $familyRepository->hasAttribute(Argument::cetera())->shouldNotBeCalled(); $this->hasAttributeInFamily(10, 'attribute_code')->shouldReturn(false); }
/** * Creates a Doctrine Query Builder. * * @return \Doctrine\ODM\MongoDB\Query\Builder */ public function createQueryBuilder() { $documentName = $this->getRepositoryName(); return $this->doctrineManager->createQueryBuilder($documentName); }
/** * Create a new Query\Builder instance that is prepopulated for this document name * * @return Query\Builder $qb */ public function createQueryBuilder() { return $this->dm->createQueryBuilder($this->documentName); }