Create FractalCollection payload with pagination.

@param \Illuminate\Contracts\Pagination\LengthAwarePaginator $paginator
@param null $transformer
@param string|null $resourceKey
@return mixed
775795
public function getPagination(LengthAwarePaginator $paginator, $transformer = null, $resourceKey = null)
    {
        // Append existing query parameter to pagination link
        // @see http://fractal.thephpleague.com/pagination/#including-existing-query-string-values-in-pagination-links
        $queryParams = array_diff_key($_GET, array_flip(['page']));

        foreach ($queryParams as $key => $value) {
            $paginator->appends($key, $value);
        }

        $collection = $paginator->getCollection();

        $resource = new FractalCollection(
            $collection,
            $this->getTransformer($transformer),
            $this->getResourceKey($resourceKey)
        );
        $resource->setPaginator(new IlluminatePaginatorAdapter($paginator));

        if ($meta = $this->getMeta()) {
            $resource->setMeta($meta);
            $this->meta = [];
        }

        return $this->fractal->createData($resource)->toArray();
    }
199898
public function getPaginator(PaginatorConfig $paginatorConfig, Request $request)
    {
        $queryBuilder = $paginatorConfig->getQueryBuilder();
        // insert default values in paginator config
        $paginatorConfig = clone($paginatorConfig);
        if (is_null($paginatorConfig->getItemCountInPage())) {
            $paginatorConfig->setItemCountInPage($this->paginatorParameterList["item_count_in_page"]);
        }
        if (is_null($paginatorConfig->getVisiblePageCountInPaginator())) {
            $paginatorConfig->setVisiblePageCountInPaginator($this->paginatorParameterList["visible_page_count_in_paginator"]);
        }

        // create paginator object
        $paginator = new Paginator();
        $paginator->setPaginatorConfig($paginatorConfig);
        $paginator->setUrlTool(new UrlTool());
        $paginator->setRequestUri($request->getRequestUri());

        // get currentPage
        $paginator->setCurrentPage($request->query->get($paginatorConfig->getRequestQueryName("currentPage"), 1));

        // calculate total object count
        $countQueryBuilder = clone($queryBuilder);
        $countQueryBuilder->select("count(DISTINCT ".$paginatorConfig->getCountFieldName().")");
        $countQueryBuilder->setMaxResults(null);
        $countQueryBuilder->setFirstResult(null);
        $countQueryBuilder->resetDQLPart('groupBy');
        $countQueryBuilder->resetDQLPart('orderBy');

        // event to change paginator query builder
        $event = new DataGridEvent();
        $event->set("paginator", $paginator);
        $event->set("paginatorQueryBuilder", $countQueryBuilder);
        $event->set("request", $request);
        $this->dispatcher->dispatch(KitpagesDataGridEvents::ON_GET_PAGINATOR_QUERY, $event);

        if (!$event->isDefaultPrevented()) {
            $query = $countQueryBuilder->getQuery();
            $event->set("query", $query);
        }
        $this->dispatcher->dispatch(KitpagesDataGridEvents::AFTER_GET_PAGINATOR_QUERY, $event);

        // hack : recover query from the event so the developper can build a new query
        // from the paginatorQueryBuilder in the listener and reinject it in the event.
        $query = $event->get("query");

        try {
            $totalCount = $query->getSingleScalarResult();
            $paginator->setTotalItemCount($totalCount);
        } catch (\Doctrine\ORM\NoResultException $e) {
            $paginator->setTotalItemCount(0);
        }

        // calculate total page count
        if ($paginator->getTotalItemCount() == 0) {
            $paginator->setTotalPageCount(0);
        } else {
            $paginator->setTotalPageCount(
                (int) ((($paginator->getTotalItemCount() - 1) / $paginatorConfig->getItemCountInPage()) + 1)
            );
        }

        // change current page if needed
        if ($paginator->getCurrentPage() > $paginator->getTotalPageCount()) {
            $paginator->setCurrentPage(1);
        }

        // calculate nbPageLeft and nbPageRight
        $nbPageLeft = (int) ($paginatorConfig->getVisiblePageCountInPaginator() / 2);
        $nbPageRight = $paginatorConfig->getVisiblePageCountInPaginator() - 1 - $nbPageLeft ;

        // calculate lastPage to display
        $maxPage = min($paginator->getTotalPageCount(), $paginator->getCurrentPage() + $nbPageRight);
        // adapt minPage and maxPage
        $minPage = max(1, $maxPage-($paginatorConfig->getVisiblePageCountInPaginator() - 1));
        $maxPage = min($paginator->getTotalPageCount(), $minPage + ($paginatorConfig->getVisiblePageCountInPaginator() - 1));

        $paginator->setMinPage($minPage);
        $paginator->setMaxPage($maxPage);

        // calculate previousButton
        if ($paginator->getCurrentPage() == 1) {
            $paginator->setPreviousButtonPage(null);
        } else {
            $paginator->setPreviousButtonPage( $paginator->getCurrentPage() - 1 );
        }
        // calculate nextButton
        if ($paginator->getCurrentPage() == $paginator->getTotalPageCount()) {
            $paginator->setNextButtonPage(null);
        } else {
            $paginator->setNextButtonPage( $paginator->getCurrentPage() + 1);
        }

        return $paginator;
    }
1166960
protected function transformContent(TransformContainerInterface $container)
    {
        if (null === $container->getTransformer()) {
            return $container->getContent();
        }

        $transformer = $this->makeTransformerInstance($container->getTransformer());
        $content     = $container->getContent();

        if ($container->isCollection()) {

            // Detect pagination and convert apply it for Fractal
            $paginator   = null;

            if ($content instanceof Paginator) {
                $paginator = $content;
                $content   = $content->items();
            }

            /** @var FractalCollection $resource */
            $resource = new FractalCollection($content, $transformer);

            if ($paginator) {
                $resource->setPaginator(new IlluminatePaginatorAdapter($paginator));
            }

        } else {
            /** @var FractalItem $resource */
            $resource = new FractalItem($content, $transformer);
        }

        return $this->fractalManager->createData($resource)->toArray();
    }
1109727
public function usingPaginatorIfPaged(): TransformationFactory
	{
		if ($this->resource instanceof Collection && $this->entity instanceof LengthAwarePaginator) {
			return $this->usingPaginator();
		}

		return $this;
	}
1112049
protected function pickTransformer(Resource $resource, Resource $parentResource)
    {
        foreach ($this->transformers as $i => $transformer) {
            if ($transformer->supports($resource, $parentResource)) {
                if (0 != $i) {
                    // Move transformer to top to improve next pick
                    unset($this->transformers[$i]);
                    array_unshift($this->transformers, $transformer);
                }

                return $transformer;
            }
        }

        throw new \RuntimeException('No transformer is able to support the resource.');
    }
676341
protected function isPageInRange(LengthAwarePaginator $paginator)
    {
        return $paginator->currentPage() <= ceil($paginator->lastItem() / $paginator->perPage());
    }
114925
public function paginate(Paginator $paginator, $params = [])
    {
        $query = $this->paramsToQuery($params);

        $countQuery = $this->getDB()->newSelect();
        $countQuery->count(['*', 'count']);
        $countQuery->from([$query, 'tbl']);
        $results = $countQuery->execute()->fetchResults();
        $count = $results[0]['count'];

        $paginator->setCount($count);

        $params['limit'] = $paginator->getLimits();

        return $this->findByParams($params);
    }
237450
protected function convertToLaravelPaginator(DoctrinePaginator $doctrinePaginator, $perPage, $pageName = 'page')
    {
        $results     = $this->getResults($doctrinePaginator);
        $currentPage = $this->getCurrentPage($pageName);
        $path        = Paginator::resolveCurrentPath();

        return new LengthAwarePaginator(
            $results,
            $doctrinePaginator->count(),
            $perPage,
            $currentPage,
            compact('path')
        );
    }
417977
public function getCollection(string $resourceClass, string $operationName = null): iterable
    {
        $collection = $this->repository->findAll($resourceClass);

        return new Paginator(new GenericPaginatedDomainCollection((static function () use ($collection): iterable {
            foreach ($collection as $document) {
                yield $document->toProjection();
            }
        })(), $collection->getOffset(), $collection->getLimit(), (float) \count($collection), $collection->getTotalCount()));
    }
135591
public static function paginate(JsonApiSerializer $serializer, Builder $builder, $pageSize = null)
    {
        self::sort($serializer, $builder, $builder->getModel());

        $request = RequestFactory::create();

        $builder->paginate(
            $request->getPage()->size() ?: $pageSize,
            self::columns($serializer, $request->getFields()->get()),
            'page',
            $request->getPage()->number()
        );

        return $builder;
    }
261416
public function withItem($data, $transformer, $resourceKey = null, $meta = [], array $headers = [])
    {
        $resource = new Item($data, $transformer, $resourceKey);

        foreach ($meta as $metaKey => $metaValue) {
            $resource->setMetaValue($metaKey, $metaValue);
        }

        $rootScope = $this->manager->createData($resource);

        return $this->withArray($rootScope->toArray(), $headers);
    }
769652
protected function respondWithCollection($builder, $transformer, string $key = 'data'): JsonResponse
    {
        if (to_boolean($this->request->get('paginate', true)) === false) {
            $collection = fractal()->collection($builder)
                ->transformWith($transformer)
                ->withResourceName($key)
                ->toArray();

            $collection['meta'] = [
                'service' => env('APP_SERVICE_NAME'),
                'entity' => $transformer->getEntity()
            ];
        } else {
            $collection = $this->paginatedCollection(
                $builder,
                $transformer,
                $key,
                $this->request->get('per_page', 20)
            );
        }

        $collection['meta'] = $collection['meta'] ?? [];
        $collection['meta']['service'] = env('APP_SERVICE_NAME');
        $collection['meta']['entity'] = $transformer->getEntity();

        return $this->respondWithSuccess(
            $collection
        );
    }
1205843
public function collection($data, $transformer = null, $resourceName = null)
    {
        if (! is_null($resourceName)) {
            $this->resourceName = $resourceName;
        }

        return $this->data('collection', $data, $transformer);
    }
172377
public function paginatorInfoResolver(LengthAwarePaginator $root): array
    {
        return [
            'count' => $root->count(),
            'currentPage' => $root->currentPage(),
            'firstItem' => $root->firstItem(),
            'hasMorePages' => $root->hasMorePages(),
            'lastItem' => $root->lastItem(),
            'lastPage' => $root->lastPage(),
            'perPage' => $root->perPage(),
            'total' => $root->total(),
        ];
    }
563015
public function paginateES(int $size = 20, string $sortBy = "", string $sortType = "ASC", int $page = null) : LengthAwarePaginator
    {
        if(!$page) {
            $page = (Input::get("page") ? Input::get("page") : 1);
        }

        $from = (($page * $size) - $size);

        $data = $this->getESItems($size, $from, $sortBy, $sortType);
        return new LengthAwarePaginator($data['items'], $data['elasticData']['hits']['total'], $size, $page);
    }
1202987
protected function paginator($items, $total, $per_page, $current_page, array $options) {
        return new LengthAwarePaginator($items, $total, $per_page, $current_page, $options);
    }
1217019
public function createPagination($source, array $parameters, PaginationHandlerInterface $handler = null)
    {
        return new Pagination(
            $source,
            $parameters,
            $handler ? $handler : new NativePaginationHandler(),
            $this->findDataSource($source)
        );
    }