@param Content      $content Content model
@param QueryBuilder $builder Query builder

@return Collection|LengthAwarePaginator
507861
public function getManyNotPublishedChildren(Content $content, QueryBuilder $builder)
    {
        return $this->getManyNotPublishedFrom($content->children()->newQuery()->with('type')->getQuery(), $builder);
    }
760932
protected function filterOnlines(\Doctrine\ORM\QueryBuilder $query_builder = null) {

        if (!$query_builder)
            $query_builder = $this->createQueryBuilder('e');

        $query_builder->andWhere("e.nested_set = 1");
        return $query_builder;
    }
342980
public function buildContent(Model\ContentInterface $content)
    {
        $view = new ContentView();
        $attributes = $view->getAttributes()->addClass('cms-content');

        if ($this->editor->isEnabled()) {
            $attributes
                ->setId('cms-content-' . $content->getId())
                ->setData([
                    'id'      => $content->getId(),
                    'actions' => [
                        // TODO
                    ],
                ]);
        }

        // Layout
        $this->editor->getLayoutAdapter()->buildContent($content, $view);

        foreach ($content->getContainers() as $container) {
            $view->containers[] = $this->buildContainer($container);
        }

        return $view;
    }
213603
public function getManyPublishedFrom(Builder $query, QueryBuilder $builder): LengthAwarePaginator
    {
        $query = $query->where('published_at', '<=', Carbon::now())
            ->join('routes as r', function ($join) {
                $join->on('contents.id', '=', 'r.routable_id')
                    ->where('r.routable_type', '=', Content::class)
                    ->where('r.is_active', true);
            })
            ->distinct();

        if ($builder->hasFilter('type') || $builder->hasSort('type')) {
            $query->join('content_types as ct', 'contents.type_id', '=', 'ct.id');
            optional($builder->getFilter('type'))->apply($query, 'ct', 'name');
            optional($builder->getSort('type'))->apply($query, 'ct', 'name');
        }

        $count = clone $query->getQuery();

        $results = $query->limit($builder->getPageSize())
            ->offset($builder->getPageSize() * ($builder->getPage() - 1))
            ->get(['contents.*']);

        $results->load(
            array_merge(
                self::$loadRelations,
                [
                    'routes' => function ($query) {
                        $query->where('is_active', true);
                    }
                ]
            )
        );

        $results->transform(function ($content) {
            $languages            = $content->routes->pluck('language_code');
            $filteredTranslations = $content->translations->filter(function ($translation) use ($languages) {
                return $languages->contains($translation->language_code);
            });
            $content->setRelation('translations', $filteredTranslations);
            return $content;
        });

        return new LengthAwarePaginator(
            $results,
            $count->select('contents.id')->get()->count(),
            $builder->getPageSize(),
            $builder->getPage()
        );
    }
538285
private function shouldDoctrinePaginatorUseOutputWalkers(QueryBuilder $queryBuilder, string $resourceClass = null, string $operationName = null): bool
    {
        if (null !== $resourceClass) {
            $resourceMetadata = $this->resourceMetadataFactory->create($resourceClass);

            if (null !== $useOutputWalkers = $resourceMetadata->getCollectionOperationAttribute($operationName, 'pagination_use_output_walkers', null, true)) {
                return $useOutputWalkers;
            }
        }

        /*
         * "Cannot count query that uses a HAVING clause. Use the output walkers for pagination"
         *
         * @see https://github.com/doctrine/orm/blob/v2.6.3/lib/Doctrine/ORM/Tools/Pagination/CountWalker.php#L56
         */
        if (QueryChecker::hasHavingClause($queryBuilder)) {
            return true;
        }

        /*
         * "Cannot count query which selects two FROM components, cannot make distinction"
         *
         * @see https://github.com/doctrine/orm/blob/v2.6.3/lib/Doctrine/ORM/Tools/Pagination/CountWalker.php#L64
         */
        if (QueryChecker::hasRootEntityWithCompositeIdentifier($queryBuilder, $this->managerRegistry)) {
            return true;
        }

        /*
         * "Paginating an entity with foreign key as identifier only works when using the Output Walkers. Call Paginator#setUseOutputWalkers(true) before iterating the paginator."
         *
         * @see https://github.com/doctrine/orm/blob/v2.6.3/lib/Doctrine/ORM/Tools/Pagination/LimitSubqueryWalker.php#L77
         */
        if (QueryChecker::hasRootEntityWithForeignKeyIdentifier($queryBuilder, $this->managerRegistry)) {
            return true;
        }

        /*
         * "Cannot select distinct identifiers from query with LIMIT and ORDER BY on a column from a fetch joined to-many association. Use output walkers."
         *
         * @see https://github.com/doctrine/orm/blob/v2.6.3/lib/Doctrine/ORM/Tools/Pagination/LimitSubqueryWalker.php#L150
         */
        if (QueryChecker::hasMaxResults($queryBuilder) && QueryChecker::hasOrderByOnFetchJoinedToManyAssociation($queryBuilder, $this->managerRegistry)) {
            return true;
        }

        // Disable output walkers by default (performance)
        return false;
    }
650669
static function ContentTreeUrl(Content $content)
    {
        $args = array();
        $pageContent = $content->GetPageContent();
        if ($pageContent)
        {
            $args['page'] = $pageContent->GetPage()->GetID();
            $args['area'] = $pageContent->GetArea()->GetID();
            return self::ModuleUrl(new \Phine\Bundles\Core\Modules\Backend\PageContentTree, $args);
        }
        $layoutContent = $content->GetLayoutContent();
        if ($layoutContent)
        {
            $args['area'] = $layoutContent->GetArea()->GetID();
            return self::ModuleUrl(new \Phine\Bundles\Core\Modules\Backend\LayoutContentTree, $args);
        }
        $containerContent = $content->GetContainerContent();
        if($containerContent)
        {
            $args['container'] = $containerContent->GetContainer()->GetID();
            return self::ModuleUrl(new \Phine\Bundles\Core\Modules\Backend\ContainerContentTree, $args);
        }
    }
1184454
protected function getFixedQueryBuilder(QueryBuilder $queryBuilder)
    {
        $queryBuilderId = clone $queryBuilder;
        $rootAlias = current($queryBuilderId->getRootAliases());

        // step 1 : retrieve the targeted class
        $from = $queryBuilderId->getDQLPart('from');
        $class = $from[0]->getFrom();
        $metadata = $queryBuilderId->getEntityManager()->getMetadataFactory()->getMetadataFor($class);

        // step 2 : retrieve identifier columns
        $idNames = $metadata->getIdentifierFieldNames();

        // step 3 : retrieve the different subjects ids
        $selects = array();
        $idxSelect = '';
        foreach ($idNames as $idName) {
            $select = sprintf('%s.%s', $rootAlias, $idName);
            // Put the ID select on this array to use it on results QB
            $selects[$idName] = $select;
            // Use IDENTITY if id is a relation too. See: http://doctrine-orm.readthedocs.org/en/latest/reference/dql-doctrine-query-language.html
            // Should work only with doctrine/orm: ~2.2
            $idSelect = $select;
            if ($metadata->hasAssociation($idName)) {
                $idSelect = sprintf('IDENTITY(%s) as %s', $idSelect, $idName);
            }
            $idxSelect .= ($idxSelect !== '' ? ', ' : '') . $idSelect;
        }

        foreach ($queryBuilderId->getDqlParts()['orderBy'] as $sort) {
            $field = chop($sort->getParts()[0], 'ASC');
            $field = chop($field, 'DESC');
            $idxSelect .= ', (' . $field . ')';
        }

        $queryBuilderId->resetDQLPart('select');
        $queryBuilderId->add('select', 'DISTINCT ' . $idxSelect);

        // for SELECT DISTINCT, ORDER BY expressions must appear in idxSelect list
        /* Consider
            SELECT DISTINCT x FROM tab ORDER BY y;
        For any particular x-value in the table there might be many different y
        values.  Which one will you use to sort that x-value in the output?
        */
        // todo : check how doctrine behave, potential SQL injection here ...
        if ($this->getSortBy()) {
            $sortBy = $this->getSortBy();
            if (strpos($sortBy, '.') === false) { // add the current alias
                $sortBy = $rootAlias . '.' . $sortBy;
            }
            $sortBy .= ' AS __order_by';
            $queryBuilderId->addSelect($sortBy);
        }

        // Use ILIKE instead of LIKE for Postgresql
        if ('pdo_pgsql' == $queryBuilderId->getEntityManager()->getConnection()->getDriver()->getName()) {
            $this->setHint(Query::HINT_CUSTOM_OUTPUT_WALKER, 'Blast\DoctrinePgsqlBundle\DoctrineExtensions\BlastWalker');
        }

        $query = $queryBuilderId->getQuery();
        foreach ($this->_hints as $name => $value) {
            $query->setHint($name, $value);
        }

        $results = $query->execute(array(), Query::HYDRATE_ARRAY);
        $platform = $queryBuilderId->getEntityManager()->getConnection()->getDatabasePlatform();
        $idxMatrix = array();
        foreach ($results as $id) {
            foreach ($idNames as $idName) {
                // Convert ids to database value in case of custom type, if provided.
                $fieldType = $metadata->getTypeOfField($idName);
                $idxMatrix[$idName][] = $fieldType && Type::hasType($fieldType)
                    ? Type::getType($fieldType)->convertToDatabaseValue($id[$idName], $platform)
                    : $id[$idName];
            }
        }

        // step 4 : alter the query to match the targeted ids
        foreach ($idxMatrix as $idName => $idx) {
            if (count($idx) > 0) {
                $idxParamName = sprintf('%s_idx', $idName);
                $idxParamName = preg_replace('/[^\w]+/', '_', $idxParamName);
                $queryBuilder->andWhere(sprintf('%s IN (:%s)', $selects[$idName], $idxParamName));
                $queryBuilder->setParameter($idxParamName, $idx);
                $queryBuilder->setMaxResults(null);
                $queryBuilder->setFirstResult(null);
            }
        }

        return $queryBuilder;
    }
826357
protected function getPaginator4QueryBuilder(QueryBuilder $queryBuilder, int $count, int $page = 1): ?Paginator
    {
        if (!$queryBuilder) {
            return null;
        }

        $paginator = new Paginator(
            new DoctrineAdapter\SimpleQueryDoctrine($count, $queryBuilder->getQuery())
        );
        $paginator->setDefaultItemCountPerPage(25);
        $paginator->setCurrentPageNumber($page);

        return $paginator;
    }
701516
public function setContent(string $content, ?StreamFactoryInterface $streamFactory = null): WebResourceInterface
    {
        $response = null;
        $contentType = $this->contentType;

        if ($this->response && empty($streamFactory)) {
            throw UnwritableContentException::create();
        }

        if ($this->response) {
            $responseBody = $streamFactory->createFromString($content);
            $response = $this->response->withBody($responseBody);
            $contentType = null;
        }

        return $this->createNewInstance([
            WebResourceProperties::ARG_CONTENT_TYPE => $contentType,
            WebResourceProperties::ARG_CONTENT => $content,
            WebResourceProperties::ARG_RESPONSE => $response,
        ]);
    }
1125347
public function extendQueryBuilder(QueryBuilder $queryBuilder)
    {
        $queryBuilder
            ->setFirstResult($this->getFirstResult())
            ->setMaxResults($this->getLimit());

        return $this;
    }
1174889
protected function getUseI18nQueryMethod(\QueryBuilder $builder)
    {

        $currentTable = $this->getTable();
        $db = $currentTable->getDatabase();

        $i18nTableName = $currentTable->getName() . '_i18n';
        $i18nTable = $db->getTable($i18nTableName);
        if (!$i18nTable) {
            $this->exceptionError('Table '.$i18nTableName.' not found');
        }
        foreach ($i18nTable->getForeignKeys() as $fk) {
            if ($fk->getForeignTableName() == $currentTable->getName()) {
                $foreignKey = $fk;
            }
        }

        $script = '

    /**
     * Use the I18n relation query object
     *
     * @see       useQuery()
     *
     * @param     string $locale Locale to use for the join condition, e.g. \'fr_FR\'
     * @param     string $relationAlias optional alias for the relation
     * @param     string $joinType Accepted values are null, \'left join\', \'right join\', \'inner join\'. Defaults to left join.
     *
     * @return    \\' . $builder->getNewStubQueryBuilder($i18nTable)->getFullyQualifiedClassname() . ' A secondary query class using the current class as primary query
     */
    public function useI18nQuery($locale = \'ru\', $relationAlias = null, $joinType = Criteria::LEFT_JOIN)
    {
        return $this
            ->joinI18n($locale, $relationAlias, $joinType)
            ->useQuery($relationAlias ? $relationAlias : \''. $builder->getRefFKPhpNameAffix($foreignKey) .'\', \'\\'. $builder->getNewStubQueryBuilder($i18nTable)->getFullyQualifiedClassname() .'\');
    }';
        return $script;
    }
410753
public function createFromBuilder(Builder $builder)
    {
        $this->model = $builder->getModel();
        $this->query = $builder;

        $this->build();

        return $this;
    }
28621
protected function paginateBuilder($builder, EncodingParametersInterface $parameters)
    {
        return $builder->paginate($this->getPageSize($parameters), $this->getFieldSets($parameters), 'page', $this->getPageNumber($parameters));
    }
613126
public function getNewQueryInheritanceBuilder($child)
    {
        $queryInheritanceBuilder = $this->getGeneratorConfig()->getConfiguredBuilder($this->getTable(), 'queryinheritance');
        $queryInheritanceBuilder->setChild($child);

        return $queryInheritanceBuilder;
    }
250432
static function FirstChildOf (Content $content)
    {
        $provider = self::GetTreeProvider($content);
        if (!$provider)
        {
            return null;
        }
        $item = $provider->ItemByContent($content);
        return $provider->ContentByItem($provider->FirstChildOf($item));
    }
250908
public function getLoader(ObjectManager $manager, $queryBuilder, $class)
    {
        $queryBuilder->innerJoin(NodeVersion::class, 'nv', Join::WITH, 'nv.refId = e.id and nv.refEntityName = :ref_name');

        $queryBuilder->innerJoin(NodeTranslation::class, 'nt', Join::WITH, 'nt.id = nv.nodeTranslation and nt.publicNodeVersion = nv.id');
        $queryBuilder->innerJoin(Node::class, 'n', Join::WITH, 'n.id = nt.node');

        $queryBuilder->andWhere($queryBuilder->expr()->eq("n.deleted", 0));
        $queryBuilder->andWhere($queryBuilder->expr()->eq('nt.online', 1));
        $queryBuilder->setParameter("ref_name", $class);

        if (null !== $queryBuilder->getParameter('left') && null !== $queryBuilder->getParameter('right')) {
            $queryBuilder->andWhere('n.lft >= :left')->andWhere('n.rgt <= :right');
        }

        if (null !== $queryBuilder->getParameter('lang')) {
            $queryBuilder->andWhere('nt.lang = :lang');
        }

        return new ORMQueryBuilderLoader(
            $queryBuilder,
            $manager,
            $class
        );
    }
115105
public function paginate(Builder $builder, $perPage, $page)
    {
        return $this->performSearch($builder, [
            'numericFilters' => $this->filters($builder),
            'hitsPerPage' => $perPage,
            'page' => $page - 1,
        ]);
    }