/**
  * @QueryParam(name="page", requirements="\d+", default="1", description="Page of the overview")
  * @QueryParam(name="limit", requirements="\d+", default="10", description="Size of the page")
  * @QueryParam(name="sort", requirements="[a-z]+", description="Sort parameter")
  * @QueryParam(name="sort_order", requirements="(asc|desc)", allowBlank=false, default="asc", description="Sort direction")
  * @QueryParam(name="search", requirements="[a-zA-Z0-9]+", description="Search")
  * @QueryParam(name="status", requirements="(pending|publish|draft|auto-draft|future|private|inherit|trash)",  default="", nullable=true, description="Status of the posts")
  * @QueryParam(name="by_author", requirements="[a-zA-Z]+", description="By author's username", incompatibles={"search"})
  * @QueryParam(name="by_category", requirements="[a-zA-Z]+", description="By category", incompatibles={"search"})
  * @QueryParam(name="by_keywords", requirements="[a-zA-Z]+", description="By keywords", incompatibles={"search"})
  * @QueryParam(name="format", requirements="[a-z]+", default="lite", description="Format of request")
  * @Rest\View()
  */
 public function getPostsAction(ParamFetcher $paramFetcher)
 {
     $page = $paramFetcher->get("page");
     $limit = $paramFetcher->get("limit");
     $sort = $paramFetcher->get("sort");
     $sort_order = $paramFetcher->get("sort_order");
     $search = $paramFetcher->get("search");
     $status = $paramFetcher->get("status");
     $by_author = $paramFetcher->get("by_author");
     $by_category = $paramFetcher->get("by_category");
     $by_keywords = $paramFetcher->get("by_keywords");
     $format = $paramFetcher->get("format");
     $repo = $this->getDoctrine()->getManager()->getRepository('ESGISGabonPostBundle:CorporatePost');
     $posts = $repo->getPosts($format);
     $adapter = new ArrayAdapter($posts);
     $pager = new Pagerfanta($adapter);
     $pager->setMaxPerPage($limit);
     try {
         $pager->setCurrentPage($page);
     } catch (NotValidCurrentPageException $e) {
         throw new NotFoundHttpException();
     }
     $pagerfantaFactory = new PagerfantaFactory();
     $paginatedCollection = $pagerfantaFactory->createRepresentation($pager, new Route('api_get_posts', array('page' => $page, 'limit' => $limit, 'sort' => $sort, 'sort_order' => $sort_order)), new CollectionRepresentation($pager->getCurrentPageResults(), 'posts', 'posts'));
     return $paginatedCollection;
 }
Example #2
0
 /**
  * @param QueryBuilder $qb
  * @param Request $request
  * @param array $routeParameters
  *
  * @return PaginatedRepresentation
  */
 public function paginate(QueryBuilder $qb, Request $request, array $routeParameters = []) : PaginatedRepresentation
 {
     $routeName = $request->get('_route');
     $criterias = $request->query->all();
     $pager = new Pagerfanta(new DoctrineORMAdapter($qb, false, false));
     $pager->setMaxPerPage($this->getLimitPerPage($criterias))->setCurrentPage($this->getPage($criterias));
     $pff = new PagerfantaFactory(self::PAGE, self::LIMIT);
     return $pff->createRepresentation($pager, new Route($routeName, array_merge($criterias, $routeParameters)));
 }
 /**
  * @param Request $request
  * @return \FOS\RestBundle\View\View
  * @REST\View()
  */
 public function getArticlesAction(Request $request)
 {
     /** @var ArticleRepository $repository */
     $repository = $this->getDoctrine()->getRepository('AppBundle:Article');
     // TODO: extract this to a manager or something
     $query = $repository->createQueryForList();
     $pager = new Pagerfanta(new DoctrineORMAdapter($query));
     $pager->setMaxPerPage($request->query->get('limit', 10))->setCurrentPage($request->query->get('page', 1));
     $pagerFactory = new PagerfantaFactory();
     $collection = $pagerFactory->createRepresentation($pager, new Route('get_articles', array()));
     return $this->view($collection, 200);
 }
 /**
  * @Rest\Get(name="groups_list", path="/groups", defaults={"_format" = "json"})
  * @Rest\View()
  */
 public function getGroupsAction(Request $request)
 {
     $limit = $request->query->getInt('limit', 10);
     $page = $request->query->getInt('page', 1);
     $queryBuilder = $this->getDoctrine()->getManager()->createQueryBuilder()->select('g')->from('AppBundle:Group', 'g');
     $pagerAdapter = new DoctrineORMAdapter($queryBuilder);
     $pager = new Pagerfanta($pagerAdapter);
     $pager->setCurrentPage($page);
     $pager->setMaxPerPage($limit);
     $pagerFactory = new PagerfantaFactory();
     return $pagerFactory->createRepresentation($pager, new Route('groups_list', array('limit' => $limit, 'page' => $page)), new CollectionRepresentation($pager->getCurrentPageResults(), 'groups', 'groups'));
 }
 public function test()
 {
     $results = array('Adrien', 'William');
     $pagerProphecy = $this->prophesize('Pagerfanta\\Pagerfanta');
     $pagerProphecy->getCurrentPageResults()->willReturn($results);
     $pagerProphecy->getCurrentPage()->willReturn(2);
     $pagerProphecy->getMaxPerPage()->willReturn(20);
     $pagerProphecy->getNbPages()->willReturn(4);
     $factory = new PagerfantaFactory('p', 'l');
     $representation = $factory->create($pagerProphecy->reveal(), 'users', array('query' => 'hateoas'));
     $this->object($representation)->isInstanceOf('Hateoas\\Representation\\PaginatedCollection')->variable($representation->getPage())->isEqualTo(2)->variable($representation->getLimit())->isEqualTo(20)->variable($representation->getPages())->isEqualTo(4)->array($representation->getParameters())->isEqualTo(array('query' => 'hateoas', 'p' => 2, 'l' => 20))->string($representation->getPageParameterName())->isEqualTo('p')->string($representation->getLimitParameterName())->isEqualTo('l');
 }
Example #6
0
 /**
  * @param Request $request
  * @param Query   $query
  * @param string  $route
  * @param array   $routeParameters
  *
  * @return View
  */
 public function formatQuery(Request $request, Query $query, $route, array $routeParameters)
 {
     $limit = $request->query->getInt('limit', 10);
     if ($limit > 100) {
         $limit = 100;
     }
     $page = $request->query->getInt('page', 1);
     $pagerAdapter = new DoctrineORMAdapter($query);
     $pager = new Pagerfanta($pagerAdapter);
     $pager->setCurrentPage($page);
     $pager->setMaxPerPage($limit);
     $pagerFactory = new PagerfantaFactory();
     return View::create($pagerFactory->createRepresentation($pager, new Route($route, array_merge($routeParameters, array('limit' => $limit, 'page' => $page)))));
 }
 /**
  * {@inheritdoc}
  */
 public function get(RequestConfiguration $requestConfiguration, RepositoryInterface $repository)
 {
     $resources = $this->resourcesResolver->getResources($requestConfiguration, $repository);
     if ($resources instanceof Pagerfanta) {
         $request = $requestConfiguration->getRequest();
         $resources->setMaxPerPage($requestConfiguration->getPaginationMaxPerPage());
         $resources->setCurrentPage($request->query->get('page', 1));
         if (!$requestConfiguration->isHtmlRequest()) {
             $route = new Route($request->attributes->get('_route'), array_merge($request->attributes->get('_route_params'), $request->query->all()));
             return $this->pagerfantaRepresentationFactory->createRepresentation($resources, $route);
         }
     }
     return $resources;
 }
 function it_creates_a_paginated_representation_for_pagerfanta_for_non_html_requests(ResourcesResolverInterface $resourcesResolver, RequestConfiguration $requestConfiguration, RepositoryInterface $repository, Pagerfanta $paginator, Request $request, ParameterBag $queryParameters, ParameterBag $requestAttributes, PagerfantaFactory $pagerfantaRepresentationFactory, PaginatedRepresentation $paginatedRepresentation)
 {
     $requestConfiguration->isHtmlRequest()->willReturn(false);
     $requestConfiguration->getPaginationMaxPerPage()->willReturn(8);
     $resourcesResolver->getResources($requestConfiguration, $repository)->willReturn($paginator);
     $requestConfiguration->getRequest()->willReturn($request);
     $request->query = $queryParameters;
     $queryParameters->get('page', 1)->willReturn(6);
     $queryParameters->all()->willReturn(['foo' => 2, 'bar' => 15]);
     $request->attributes = $requestAttributes;
     $requestAttributes->get('_route')->willReturn('sylius_product_index');
     $requestAttributes->get('_route_params')->willReturn(['slug' => 'foo-bar']);
     $paginator->setMaxPerPage(8)->shouldBeCalled();
     $paginator->setCurrentPage(6)->shouldBeCalled();
     $pagerfantaRepresentationFactory->createRepresentation($paginator, Argument::type(Route::class))->willReturn($paginatedRepresentation);
     $this->get($requestConfiguration, $repository)->shouldReturn($paginatedRepresentation);
 }
 /**
  * Retrieve all entries. It could be filtered by many options.
  *
  * @ApiDoc(
  *       parameters={
  *          {"name"="archive", "dataType"="integer", "required"=false, "format"="1 or 0, all entries by default", "description"="filter by archived status."},
  *          {"name"="starred", "dataType"="integer", "required"=false, "format"="1 or 0, all entries by default", "description"="filter by starred status."},
  *          {"name"="sort", "dataType"="string", "required"=false, "format"="'created' or 'updated', default 'created'", "description"="sort entries by date."},
  *          {"name"="order", "dataType"="string", "required"=false, "format"="'asc' or 'desc', default 'desc'", "description"="order of sort."},
  *          {"name"="page", "dataType"="integer", "required"=false, "format"="default '1'", "description"="what page you want."},
  *          {"name"="perPage", "dataType"="integer", "required"=false, "format"="default'30'", "description"="results per page."},
  *          {"name"="tags", "dataType"="string", "required"=false, "format"="api,rest", "description"="a list of tags url encoded. Will returns entries that matches ALL tags."},
  *       }
  * )
  *
  * @return Response
  */
 public function getEntriesAction(Request $request)
 {
     $this->validateAuthentication();
     $isArchived = null === $request->query->get('archive') ? null : (bool) $request->query->get('archive');
     $isStarred = null === $request->query->get('starred') ? null : (bool) $request->query->get('starred');
     $sort = $request->query->get('sort', 'created');
     $order = $request->query->get('order', 'desc');
     $page = (int) $request->query->get('page', 1);
     $perPage = (int) $request->query->get('perPage', 30);
     $pager = $this->getDoctrine()->getRepository('WallabagCoreBundle:Entry')->findEntries($this->getUser()->getId(), $isArchived, $isStarred, $sort, $order);
     $pager->setCurrentPage($page);
     $pager->setMaxPerPage($perPage);
     $pagerfantaFactory = new PagerfantaFactory('page', 'perPage');
     $paginatedCollection = $pagerfantaFactory->createRepresentation($pager, new Route('api_get_entries', [], UrlGeneratorInterface::ABSOLUTE_URL));
     $json = $this->get('serializer')->serialize($paginatedCollection, 'json');
     return $this->renderJsonResponse($json);
 }
 public function indexAction(Request $request)
 {
     $queryBuilder = $this->getDoctrine()->getManager()->createQueryBuilder()->select('r')->from('RshRecipeBookBundle:Recipe', 'r');
     $adapter = new DoctrineORMAdapter($queryBuilder);
     $pager = new Pagerfanta($adapter);
     $currentPage = 1;
     if ($request->query->get('page') !== null) {
         $currentPage = $request->query->get('page');
     }
     $pager->setCurrentPage($currentPage);
     $pagerfantaFactory = new PagerfantaFactory();
     // you can pass the page,
     // and limit parameters name
     $paginatedCollection = $pagerfantaFactory->createRepresentation($pager, new Route('rsh_recipe_book_recipe', []));
     $json = $this->container->get('serializer')->serialize($paginatedCollection, 'json');
     return new Response($json, 200, ['application/json']);
 }
Example #11
0
 /**
  * @ApiDoc(
  *  description="Returns a collection of votes",
  *  requirements={
  *      {
  *          "name"="limit",
  *          "dataType"="integer",
  *          "requirement"="\d+",
  *          "description"="how many objects to return"
  *      },
  *      {
  *          "name"="page",
  *          "dataType"="integer",
  *          "requirement"="\d+",
  *          "description"="page"
  *      }
  *  },
  *  filters={
  *      {"name"="vote", "dataType"="string", "pattern"="(yes|maybe|no)"}
  *  },
  *  views = { "default", "voter" }
  * )
  * @REST\Get("votes")
  */
 public function getVotesAction(Request $request)
 {
     $limit = $request->query->getInt('limit', 10);
     $page = $request->query->getInt('page', 1);
     $vote = $request->query->getAlpha('vote');
     /** @var \AppBundle\Repository\VoteRepository $voteRepo */
     $voteRepo = $this->getDoctrine()->getRepository('AppBundle:Vote');
     $queryBuilder = $voteRepo->getQueryBuilderFindBy($this->getUser(), $vote);
     $routeParam = array('limit' => $limit, 'page' => $page);
     if ($vote) {
         $routeParam['vote'] = $vote;
     }
     $pagerAdapter = new DoctrineORMAdapter($queryBuilder);
     $pager = new Pagerfanta($pagerAdapter);
     $pager->setCurrentPage($page);
     $pager->setMaxPerPage($limit);
     $pagerFactory = new PagerfantaFactory();
     return $pagerFactory->createRepresentation($pager, new Route('get_votes', $routeParam));
 }
Example #12
0
 /**
  * @param ParamFetcherInterface $fetcher
  * @param QueryBuilder          $queryBuilder
  * @param string                $route
  *
  * @return \Symfony\Component\HttpFoundation\Response
  */
 protected function manageCollection(ParamFetcherInterface $fetcher, QueryBuilder $queryBuilder, $route)
 {
     $limit = $fetcher->get('limit');
     $page = $fetcher->get('page');
     try {
         $pager = new Pagerfanta(new DoctrineORMAdapter($queryBuilder));
         $pager->setMaxPerPage($limit);
         $pager->setCurrentPage($page);
     } catch (OutOfRangeCurrentPageException $exception) {
         $response = ['message' => 'Page out of range'];
         return $this->handleView($this->view($response, Response::HTTP_NOT_FOUND));
     }
     $pagerFactory = new PagerfantaFactory();
     if (!$route instanceof Route) {
         $route = new Route($route, [], true, $this->get('router'));
     }
     $paginatedCollection = $pagerFactory->createRepresentation($pager, $route);
     return $this->handleView($this->view($paginatedCollection));
 }
Example #13
0
 /**
  * @param ViewEvent $event
  */
 public function onApi(ViewEvent $event)
 {
     if (!$this->getParameterResolver()->resolveApi()) {
         return;
     }
     $view = $event->getView();
     $data = $view->getData();
     if (!$data instanceof Pagerfanta) {
         return;
     }
     if ($this->getParameterResolver()->resolveHateoas()) {
         if (($request = $this->requestStack->getMasterRequest()) === null) {
             throw new RequestNotFoundException();
         }
         $data = $this->pagerfantaFactory->createRepresentation($data, new Route($request->attributes->get('_route'), array_merge($request->attributes->get('_route_params', []), $request->query->all())));
     } else {
         $data = array_values(iterator_to_array($data));
     }
     $view->setData($data);
 }
Example #14
0
    public function testGenerateAbsoluteURIs()
    {
        $factory = new PagerfantaFactory();
        $pagerfanta = new Pagerfanta(new ArrayAdapter(array('bim', 'bam', 'boom')));
        $collection = $factory->createRepresentation($pagerfanta, new Route('/my_route', array(), true));
        $this->string($this->hateoas->serialize($collection, 'xml'))->isEqualTo(<<<XML
<?xml version="1.0" encoding="UTF-8"?>
<collection page="1" limit="10" pages="1" total="3">
  <entry rel="items">
    <entry><![CDATA[bim]]></entry>
    <entry><![CDATA[bam]]></entry>
    <entry><![CDATA[boom]]></entry>
  </entry>
  <link rel="self" href="http://example.com/my_route?page=1&amp;limit=10"/>
  <link rel="first" href="http://example.com/my_route?page=1&amp;limit=10"/>
  <link rel="last" href="http://example.com/my_route?page=1&amp;limit=10"/>
</collection>

XML
);
    }
 /**
  * {@inheritdoc}
  */
 public function get(RequestConfiguration $requestConfiguration, RepositoryInterface $repository)
 {
     if (null !== ($repositoryMethod = $requestConfiguration->getRepositoryMethod())) {
         $callable = [$repository, $repositoryMethod];
         return call_user_func_array($callable, $requestConfiguration->getRepositoryArguments());
     }
     if (!$requestConfiguration->isPaginated() && !$requestConfiguration->isLimited()) {
         return $repository->findAll();
     }
     if (!$requestConfiguration->isPaginated()) {
         return $repository->findBy($requestConfiguration->getCriteria(), $requestConfiguration->getSorting(), $requestConfiguration->getLimit());
     }
     $request = $requestConfiguration->getRequest();
     /** @var Pagerfanta $paginator */
     $paginator = $repository->createPaginator($requestConfiguration->getCriteria(), $requestConfiguration->getSorting());
     $paginator->setCurrentPage($request->query->get('page', 1));
     if (!$requestConfiguration->isHtmlRequest()) {
         $route = new Route($request->attributes->get('_route'), array_merge($request->attributes->get('_route_params'), $request->query->all()));
         return $this->pagerfantaRepresentationFactory->createRepresentation($paginator, $route);
     }
     return $paginator;
 }
    public function testWithPagerfanta()
    {
        $hateoas = HateoasBuilder::create()->setUrlGenerator(null, new CallableUrlGenerator(function ($route, array $parameters) {
            return $route . '?' . http_build_query($parameters);
        }))->build();
        $factory = new PagerfantaFactory();
        $pagerfanta = new Pagerfanta(new ArrayAdapter(array('bim', 'bam', 'boom')));
        $collection = $factory->create($pagerfanta, 'my_route');
        $this->string($hateoas->serialize($collection, 'xml'))->isEqualTo(<<<XML
<?xml version="1.0" encoding="UTF-8"?>
<collection page="1" limit="10" pages="1">
  <entry><![CDATA[bim]]></entry>
  <entry><![CDATA[bam]]></entry>
  <entry><![CDATA[boom]]></entry>
  <link rel="self" href="my_route?page=1&amp;limit=10"/>
  <link rel="first" href="my_route?page=1&amp;limit=10"/>
  <link rel="last" href="my_route?page=1&amp;limit=10"/>
</collection>

XML
);
    }
 function it_creates_a_pagniated_respresentation_for_pagerfanta_for_non_html_requests(RequestConfiguration $requestConfiguration, RepositoryInterface $repository, Pagerfanta $paginator, Request $request, ParameterBag $queryParameters, ParameterBag $requestAttributes, PagerfantaFactory $pagerfantaRepresentationFactory, PaginatedRepresentation $paginatedRepresentation)
 {
     $requestConfiguration->isHtmlRequest()->willReturn(false);
     $requestConfiguration->getRepositoryMethod()->willReturn(null);
     $requestConfiguration->isPaginated()->willReturn(true);
     $requestConfiguration->isLimited()->willReturn(false);
     $requestConfiguration->getCriteria()->willReturn(array());
     $requestConfiguration->getSorting()->willReturn(array());
     $repository->createPaginator(array(), array())->willReturn($paginator);
     $requestConfiguration->getRequest()->willReturn($request);
     $request->query = $queryParameters;
     $queryParameters->get('page', 1)->willReturn(6);
     $queryParameters->all()->willReturn(array('foo' => 2, 'bar' => 15));
     $request->attributes = $requestAttributes;
     $requestAttributes->get('_route')->willReturn('sylius_product_index');
     $requestAttributes->get('_route_params')->willReturn(array('slug' => 'foo-bar'));
     $paginator->setCurrentPage(6)->shouldBeCalled();
     $pagerfantaRepresentationFactory->createRepresentation($paginator, Argument::type(Route::class))->willReturn($paginatedRepresentation);
     $this->get($requestConfiguration, $repository)->shouldReturn($paginatedRepresentation);
 }
Example #18
0
 /**
  * @ApiDoc(
  *  description="Returns a collection of unvoted proposals",
  *  requirements={
  *      {
  *          "name"="limit",
  *          "dataType"="integer",
  *          "requirement"="\d+",
  *          "description"="how many objects to return"
  *      },
  *      {
  *          "name"="page",
  *          "dataType"="integer",
  *          "requirement"="\d+",
  *          "description"="page"
  *      }
  *  },
  *  views = { "default", "voter" }
  * )
  * @REST\Get("proposals/todo")
  */
 public function getProposalsTodoAction(Request $request)
 {
     $limit = $request->query->getInt('limit', 10);
     $page = $request->query->getInt('page', 1);
     $queryBuilder = $this->getDoctrine()->getRepository('AppBundle:Proposal')->getQueryBuilderFindTodoBy($this->getUser());
     $pagerAdapter = new DoctrineORMAdapter($queryBuilder);
     $pager = new Pagerfanta($pagerAdapter);
     $pager->setCurrentPage($page);
     $pager->setMaxPerPage($limit);
     $pagerFactory = new PagerfantaFactory();
     return $pagerFactory->createRepresentation($pager, new Route('get_proposals_todo', array('limit' => $limit, 'page' => $page)));
 }