public function __construct(Pagerfanta $paginator, Request $request, $base_url)
 {
     $this->data = $paginator->getCurrentPageResults();
     $this->total_count = $paginator->getNbResults();
     $this->count = count($this->data);
     $query = array('q' => $request->get('q'), 'limit' => $request->get('limit'), 'page' => $request->get('page'));
     $this->query = $query;
     $this->urls['current'] = $base_url . '?' . http_build_query($query);
     if ($paginator->hasPreviousPage()) {
         $query['page'] = $paginator->getPreviousPage();
         $this->urls['previous'] = $base_url . '?' . http_build_query($query);
         if ($paginator->getCurrentPage() > 2) {
             $query['page'] = 1;
             $this->urls['start'] = $base_url . '?' . http_build_query($query);
         }
     }
     if ($paginator->hasNextPage()) {
         $query['page'] = $paginator->getNextPage();
         $this->urls['next'] = $base_url . '?' . http_build_query($query);
         if ($paginator->getCurrentPage() < $paginator->getNbPages() - 1) {
             $query['page'] = $paginator->getNbPages();
             $this->urls['end'] = $base_url . '?' . http_build_query($query);
         }
     }
 }
Exemple #2
0
 /**
  * Perform a search and return a JSON response.
  *
  * @param Request $request
  *
  * @return JsonResponse
  */
 public function searchAction(Request $request)
 {
     $queryString = $request->query->get('q');
     $category = $request->query->get('category', null);
     $locale = $request->query->get('locale', null);
     $page = $this->listRestHelper->getPage();
     $limit = $this->listRestHelper->getLimit();
     $aggregateHits = [];
     $startTime = microtime(true);
     $categories = $category ? [$category] : $this->searchManager->getCategoryNames();
     foreach ($categories as $category) {
         $query = $this->searchManager->createSearch($queryString);
         if ($locale) {
             $query->locale($locale);
         }
         if ($category) {
             $query->category($category);
         }
         foreach ($query->execute() as $hit) {
             $aggregateHits[] = $hit;
         }
     }
     $time = microtime(true) - $startTime;
     $adapter = new ArrayAdapter($aggregateHits);
     $pager = new Pagerfanta($adapter);
     $pager->setMaxPerPage($limit);
     $pager->setCurrentPage($page);
     $representation = new SearchResultRepresentation(new CollectionRepresentation($pager->getCurrentPageResults(), 'result'), 'sulu_search_search', ['locale' => $locale, 'query' => $query, 'category' => $category], (int) $page, (int) $limit, $pager->getNbPages(), 'page', 'limit', false, count($aggregateHits), $this->getCategoryTotals($aggregateHits), number_format($time, 8));
     $view = View::create($representation);
     $context = SerializationContext::create();
     $context->enableMaxDepthChecks();
     $context->setSerializeNull(true);
     $view->setSerializationContext($context);
     return $this->viewHandler->handle($view);
 }
 /**
  * Construct a pagerfanta representation from the current request
  *
  * @param AdapterInterface $adapter - The adapter to use
  * @return QueryablePaginatedRepresentation
  */
 protected function getPagerfantaRepresentation(Request $request, AdapterInterface $adapter)
 {
     $pagerfanta = new Pagerfanta($adapter);
     $limit = $request->query->get('limit');
     $zeroLimit = false;
     if (!$limit && ($limit === 0 || $limit === '0')) {
         $limit = $pagerfanta->count();
         $zeroLimit = true;
     }
     if (!$limit) {
         $limit = 10;
     }
     $pagerfanta->setMaxPerPage($limit);
     $page = $request->query->get('page');
     $nbPages = $pagerfanta->getNbPages();
     if (!$page) {
         $page = 1;
     }
     // Avoid errors: redirect to max page
     if ($page > $nbPages) {
         $page = $nbPages;
     }
     $pagerfanta->setCurrentPage($page);
     $route = new Route($request->get('_route'), $request->attributes->get('_route_params'), false);
     return new QueryablePaginatedRepresentation(new CollectionRepresentation($pagerfanta->getCurrentPageResults()), $route->getName(), $route->getParameters(), $pagerfanta->getCurrentPage(), $zeroLimit ? 0 : $pagerfanta->getMaxPerPage(), $nbPages, $pagerfanta->count(), null, null, $route->isAbsolute(), $request->query->get('where'), $request->query->get('search'), $request->query->get('order'), null, null, null);
 }
 public function createCollection(QueryBuilder $qb, Request $request, $route, array $routeParams = array())
 {
     $page = $request->query->get(self::PARAMETER_NAME_PAGE_NUMBER, 1);
     $count = $request->query->get(self::PARAMETER_NAME_PAGE_SIZE, self::PAGE_DEFAULT_COUNT);
     if ($count > self::MAX_PAGE_COUNT) {
         $count = self::MAX_PAGE_COUNT;
     }
     if ($count <= 0) {
         $count = self::PAGE_DEFAULT_COUNT;
     }
     $adapter = new DoctrineORMAdapter($qb);
     $pagerfanta = new Pagerfanta($adapter);
     $pagerfanta->setMaxPerPage($count);
     $pagerfanta->setCurrentPage($page);
     $players = [];
     foreach ($pagerfanta->getCurrentPageResults() as $result) {
         $players[] = $result;
     }
     $paginatedCollection = new PaginatedCollection($players, $pagerfanta->getNbResults());
     // make sure query parameters are included in pagination links
     $routeParams = array_merge($routeParams, $request->query->all());
     $createLinkUrl = function ($targetPage) use($route, $routeParams) {
         return $this->router->generate($route, array_merge($routeParams, array(self::PARAMETER_NAME_PAGE_NUMBER => $targetPage)));
     };
     $paginatedCollection->addLink('self', $createLinkUrl($page));
     $paginatedCollection->addLink('first', $createLinkUrl(1));
     $paginatedCollection->addLink('last', $createLinkUrl($pagerfanta->getNbPages()));
     if ($pagerfanta->hasNextPage()) {
         $paginatedCollection->addLink('next', $createLinkUrl($pagerfanta->getNextPage()));
     }
     if ($pagerfanta->hasPreviousPage()) {
         $paginatedCollection->addLink('prev', $createLinkUrl($pagerfanta->getPreviousPage()));
     }
     return $paginatedCollection;
 }
 /**
  * @param Pagerfanta $pager  The pager
  * @param Route      $route  The collection's route
  * @param mixed      $inline Most of the time, a custom `CollectionRepresentation` instance
  *
  * @return PaginatedRepresentation
  */
 public function createRepresentation(Pagerfanta $pager, Route $route, $inline = null)
 {
     if (null === $inline) {
         $inline = new CollectionRepresentation($pager->getCurrentPageResults());
     }
     return new PaginatedRepresentation($inline, $route->getName(), $route->getParameters(), $pager->getCurrentPage(), $pager->getMaxPerPage(), $pager->getNbPages(), $this->getPageParameterName(), $this->getLimitParameterName(), $route->isAbsolute(), $pager->getNbResults());
 }
Exemple #6
0
 /**
  * Build a Pagerfanta object based on the pagination information.
  *
  * The pagination information can be passed as a parameter, and if not the method use the injected provider to
  * extract pagination information based on the current context.
  *
  * @param \Pagerfanta\Adapter\AdapterInterface $adapter Wrapped query
  * @param PaginatedCollectionRequestInterface  $paginationInfo Requested pagination
  *
  * @return \PagerFanta\PagerFanta
  *
  * @throws \LogicException If no pagination could be used in order to paginate the results
  * @throws \AlphaLabs\Pagination\Exception\InvalidRequestedPage If the requested pagination could not be applied
  */
 public function paginate(AdapterInterface $adapter, PaginatedCollectionRequestInterface $paginationInfo = null)
 {
     if (is_null($paginationInfo)) {
         if (is_null($this->paginationInfoProvider)) {
             throw new \LogicException('A PaginatedCollectionRequestProviderInterface must be injected if you want to use pagination ' . 'and don\\t want to handle the pagination info with your own logic.');
         }
         $paginationInfo = $this->paginationInfoProvider->getPaginatedCollectionRequest();
         if (is_null($paginationInfo)) {
             throw new \LogicException('No pagination could be provided by the PaginatedCollectionRequestProviderInterface. The provider ' . 'must at least provide default pagination information in order to use the paginate() method.');
         }
     }
     $pager = new Pagerfanta($adapter);
     try {
         $pager->setMaxPerPage($paginationInfo->getItemsPerPage())->setCurrentPage($paginationInfo->getPage());
     } catch (LessThan1CurrentPageException $e) {
         $invalidPageException = new InvalidRequestedPage();
         $invalidPageException->setRequestedPage($paginationInfo->getPage())->setTargetPage(1);
         throw $invalidPageException;
     } catch (OutOfRangeCurrentPageException $e) {
         $invalidPageException = new InvalidRequestedPage();
         $invalidPageException->setRequestedPage($paginationInfo->getPage())->setTargetPage($pager->getNbPages() - 1);
         throw $invalidPageException;
     }
     return $pager;
 }
 public function __construct(Pagerfanta $pagerfanta)
 {
     $photos = $pagerfanta->getCurrentPageResults();
     $this->photos = $photos instanceof \Traversable ? iterator_to_array($photos) : $photos;
     $this->page = $pagerfanta->getCurrentPage();
     $this->pagesCount = $pagerfanta->getNbPages();
     $this->totalCount = $pagerfanta->getNbResults();
 }
 /**
  * @param JsonApiSerializationVisitor $visitor
  * @param Pagerfanta                  $pagerfanta
  * @param array                       $type
  * @param Context                     $context
  * @return Pagerfanta
  */
 public function serializePagerfanta(JsonApiSerializationVisitor $visitor, Pagerfanta $pagerfanta, array $type, Context $context)
 {
     $request = $this->requestStack->getCurrentRequest();
     $pagerfanta->setNormalizeOutOfRangePages(true);
     $pagerfanta->setAllowOutOfRangePages(true);
     $pagerfanta->setMaxPerPage($request->get('page[limit]', $this->paginationOptions['limit'], true));
     $pagerfanta->setCurrentPage($request->get('page[number]', 1, true));
     $results = $pagerfanta->getCurrentPageResults();
     if ($results instanceof \ArrayIterator) {
         $results = $results->getArrayCopy();
     }
     $data = $context->accept($results);
     $root = $visitor->getRoot();
     $root['meta'] = array('page' => $pagerfanta->getCurrentPage(), 'limit' => $pagerfanta->getMaxPerPage(), 'pages' => $pagerfanta->getNbPages(), 'total' => $pagerfanta->getNbResults());
     $root['links'] = array('first' => $this->getUriForPage(1), 'last' => $this->getUriForPage($pagerfanta->getNbPages()), 'prev' => $pagerfanta->hasPreviousPage() ? $this->getUriForPage($pagerfanta->getPreviousPage()) : null, 'next' => $pagerfanta->hasNextPage() ? $this->getUriForPage($pagerfanta->getNextPage()) : null);
     $visitor->setRoot($root);
     return $data;
 }
Exemple #9
0
 /**
  * @param Request          $request
  * @param AdapterInterface $adapter
  * @param string|null      $route
  *
  * @return PaginatedRepresentation
  */
 protected function paginate(Request $request, AdapterInterface $adapter, $route = null, $routeParameters = null)
 {
     $pagerfanta = new Pagerfanta($adapter);
     $pagerfanta->setMaxPerPage($request->query->get(self::LIMIT_PARAMETER, 5));
     $pagerfanta->setCurrentPage($request->query->get(self::PAGE_PARAMETER, 1));
     $collection = new CollectionRepresentation($pagerfanta->getCurrentPageResults());
     $paginated = new PaginatedRepresentation($collection, $route ?? $request->get('_route'), $routeParameters ?? $request->attributes->get('_route_params'), $pagerfanta->getCurrentPage(), $pagerfanta->getMaxPerPage(), $pagerfanta->getNbPages(), self::PAGE_PARAMETER, self::LIMIT_PARAMETER, false, $pagerfanta->count());
     return $paginated;
 }
 private function getNavigationLinks(Pagerfanta $pager, array $params = array())
 {
     $page = $pager->getCurrentPage();
     $limit = $pager->getMaxPerPage();
     $links = [];
     if ($pager->getCurrentPage() > 1) {
         $links['first'] = $this->generateUrl('app_api_categories', array_merge($params, ['offset' => $this->getOffset(1, $limit)]));
     }
     if ($pager->hasPreviousPage()) {
         $links['previous'] = $this->generateUrl('app_api_categories', array_merge($params, ['offset' => $this->getOffset($pager->getPreviousPage(), $limit)]));
     }
     if ($pager->hasNextPage()) {
         $links['next'] = $this->generateUrl('app_api_categories', array_merge($params, ['offset' => $this->getOffset($pager->getNextPage(), $limit)]));
     }
     if ($pager->getNbPages() != $page) {
         $links['last'] = $this->generateUrl('app_api_categories', array_merge($params, ['offset' => $this->getOffset($pager->getNbPages(), $limit)]));
     }
     return $links;
 }
 /**
  * @param Pagerfanta $object
  *
  * @return PaginatedRepresentation
  */
 protected function createPaginatedRepresentation($object)
 {
     if (!$object instanceof Pagerfanta) {
         return;
     }
     $items = $object->getCurrentPageResults();
     if ($items instanceof \ArrayIterator) {
         $items = $items->getArrayCopy();
     }
     return new PaginatedRepresentation($items, $object->getCurrentPage(), $object->getMaxPerPage(), $object->getNbPages(), $object->getNbResults());
 }
 /**
  * Return list of children node
  * @param \eZ\Publish\Core\Repository\Values\Content\Location $location
  * @param type $maxPerPage
  * @param type $currentPage
  * @return type
  */
 public function getFolderChildrens(\eZ\Publish\Core\Repository\Values\Content\Location $location, $currentUser, $maxPerPage, $currentPage = 1, $category)
 {
     $criteria = array(new Criterion\ParentLocationId($location->id), new Criterion\ContentTypeIdentifier(array('service_link')), new Criterion\Visibility(Criterion\Visibility::VISIBLE));
     if (isset($category) && $category != "all") {
         $criteria[] = new Criterion\Field('category', Criterion\Operator::CONTAINS, $category);
     }
     $query = new Query();
     $query->filter = new Criterion\LogicalAnd($criteria);
     $query->sortClauses = array($this->sortClauseAuto($location));
     $searchResult = $this->repository->getSearchService()->findContent($query);
     $subscritions = $this->fetchByUserId($currentUser->id);
     //$this->debug($subscritions);
     $content = array();
     $contentId = null;
     foreach ($searchResult->searchHits as $serviceLink) {
         if (!$contentId) {
             $contentId = $serviceLink->valueObject->getVersionInfo()->getContentInfo()->id;
         }
         $content[] = array('serviceLink' => $serviceLink->valueObject->contentInfo->mainLocationId, 'subscrition' => $this->hasSubscription($subscritions, $serviceLink->valueObject->getVersionInfo()->getContentInfo()->id));
     }
     $result['offset'] = ($currentPage - 1) * $maxPerPage;
     $adapter = new ArrayAdapter($content);
     $pagerfanta = new Pagerfanta($adapter);
     $pagerfanta->setMaxPerPage($maxPerPage);
     $pagerfanta->setCurrentPage($currentPage);
     $httpReferer = $_SERVER['SCRIPT_URL'];
     if (isset($category)) {
         $httpReferer .= "?category=" . $category;
     } else {
         $httpReferer .= "?";
     }
     $result['offset'] = ($currentPage - 1) * $maxPerPage;
     $result['prev_page'] = $pagerfanta->hasPreviousPage() ? $pagerfanta->getPreviousPage() : 0;
     $result['next_page'] = $pagerfanta->hasNextPage() ? $pagerfanta->getNextPage() : 0;
     $result['nb_pages'] = $pagerfanta->getNbPages();
     $result['items'] = $pagerfanta->getCurrentPageResults();
     $result['base_href'] = $httpReferer;
     $result['current_page'] = $pagerfanta->getCurrentPage();
     $result['options'] = isset($contentId) ? $this->getCategorie($contentId, "ezselection") : array();
     return $result;
 }
 /**
  * @Route(
  *      "/{resourceId}/shared/spaces",
  *      name="innova_collecticiel_shared_spaces",
  *      requirements={"resourceId" = "\d+"},
  *      defaults={"page" = 1}
  * )
  * @ParamConverter("dropzone", class="InnovaCollecticielBundle:Dropzone", options={"id" = "resourceId"})
  * @Template()
  */
 public function sharedSpacesAction($dropzone, $page)
 {
     $this->get('innova.manager.dropzone_voter')->isAllowToOpen($dropzone);
     $this->get('innova.manager.dropzone_voter')->isAllowToEdit($dropzone);
     $dropRepo = $this->getDoctrine()->getManager()->getRepository('InnovaCollecticielBundle:Drop');
     // dropsQuery : finished à TRUE et unlocked_drop à FALSE
     $dropsQuery = $dropRepo->getDropsAwaitingCorrectionQuery($dropzone);
     $countUnterminatedDrops = $dropRepo->countUnterminatedDropsByDropzone($dropzone->getId());
     // Déclarations des nouveaux tableaux, qui seront passés à la vue
     $userToCommentCount = array();
     $userNbTextToRead = array();
     foreach ($dropzone->getDrops() as $drop) {
         /** InnovaERV : ajout pour calculer les 2 zones **/
         // Nombre de commentaires non lus/ Repo : Comment
         $nbCommentsPerUser = $this->getDoctrine()->getRepository('InnovaCollecticielBundle:Comment')->countCommentNotRead($drop->getUser());
         // Nombre de devoirs à corriger/ Repo : Document
         $nbTextToRead = $this->getDoctrine()->getRepository('InnovaCollecticielBundle:Document')->countTextToRead($drop->getUser());
         // Affectations des résultats dans les tableaux
         $userToCommentCount[$drop->getUser()->getId()] = $nbCommentsPerUser;
         $userNbTextToRead[$drop->getUser()->getId()] = $nbTextToRead;
     }
     $adapter = new DoctrineORMAdapter($dropsQuery);
     $pager = new Pagerfanta($adapter);
     $pager->setMaxPerPage(DropzoneBaseController::DROP_PER_PAGE);
     try {
         $pager->setCurrentPage($page);
     } catch (NotValidCurrentPageException $e) {
         if ($page > 0) {
             return $this->redirect($this->generateUrl('innova_collecticiel_drops_awaiting_paginated', array('resourceId' => $dropzone->getId(), 'page' => $pager->getNbPages())));
         } else {
             throw new NotFoundHttpException();
         }
     }
     $adminInnova = false;
     if ($this->get('security.context')->isGranted('ROLE_ADMIN' === true)) {
         $adminInnova = true;
     }
     $dataToView = $this->addDropsStats($dropzone, array('workspace' => $dropzone->getResourceNode()->getWorkspace(), '_resource' => $dropzone, 'dropzone' => $dropzone, 'unterminated_drops' => $countUnterminatedDrops, 'pager' => $pager, 'nbCommentNotRead' => $userToCommentCount, 'userNbTextToRead' => $userNbTextToRead, 'adminInnova' => $adminInnova));
     return $dataToView;
 }
 /**
  * @param Pagerfanta $paginator
  * @param $route
  * @param $limit
  */
 protected function addLinksToMetadata(Pagerfanta $paginator, $route, $limit)
 {
     $data = $this->get('bite_codes_rest_api_generator.services.response_data');
     $router = $this->get('router');
     $first = $router->generate($route, ['page' => 1, 'limit' => $limit], UrlGeneratorInterface::ABSOLUTE_URL);
     $prev = $paginator->hasPreviousPage() ? $router->generate($route, ['page' => $paginator->getPreviousPage(), 'limit' => $limit], UrlGeneratorInterface::ABSOLUTE_URL) : null;
     $current = $router->generate($route, ['page' => $paginator->getCurrentPage(), 'limit' => $limit], UrlGeneratorInterface::ABSOLUTE_URL);
     $next = $paginator->hasNextPage() ? $router->generate($route, ['page' => $paginator->getNextPage(), 'limit' => $limit], UrlGeneratorInterface::ABSOLUTE_URL) : null;
     $last = $router->generate($route, ['page' => $paginator->getNbPages(), 'limit' => $limit], UrlGeneratorInterface::ABSOLUTE_URL);
     $data->addLink('first', $first);
     $data->addLink('prev', $prev);
     $data->addLink('current', $current);
     $data->addLink('next', $next);
     $data->addLink('last', $last);
     $data->addMeta('total', $paginator->getNbResults());
 }
 /**
  * @Route(
  *      "/{resourceId}/shared/spaces",
  *      name="innova_collecticiel_shared_spaces",
  *      requirements={"resourceId" = "\d+"},
  *      defaults={"page" = 1}
  * )
  * @Route(
  *      "/{resourceId}/shared/spaces/{page}",
  *      name="innova_collecticiel_shared_spaces_paginated",
  *      requirements={"resourceId" = "\d+", "page" = "\d+"},
  *      defaults={"page" = 1}
  * )
  * @ParamConverter("dropzone", class="InnovaCollecticielBundle:Dropzone", options={"id" = "resourceId"})
  * @Template()
  */
 public function sharedSpacesAction($dropzone, $page)
 {
     // Onglet "Espaces partagés"
     $this->get('innova.manager.dropzone_voter')->isAllowToOpen($dropzone);
     $this->get('innova.manager.dropzone_voter')->isAllowToEdit($dropzone);
     $dropzoneManager = $this->get('innova.manager.dropzone_manager');
     $dropzoneVoter = $this->get('innova.manager.dropzone_voter');
     // Récupération du Workspace
     $workspace = $dropzone->getResourceNode()->getWorkspace();
     $dropRepo = $this->getDoctrine()->getManager()->getRepository('InnovaCollecticielBundle:Drop');
     // Ajout du code pour afficher les élèves inscrits mais qui n'ont pas déposé. InnovaERV.
     // Déclaration du tableau de workspace
     $workspaceArray = array();
     // Récupération du workspace courant
     $workspaceId = $dropzone->getResourceNode()->getWorkspace()->getId();
     $workspaceArray[] = $workspaceId;
     $userManager = $this->get('claroline.manager.user_manager');
     $withPager = false;
     $usersByWorkspaces = $userManager->getUsersByWorkspaces($workspaceArray, $page, 20, $withPager);
     //      var_dump($usersByWorkspaces[0]);
     $userWithRights = $userManager->getUsersWithRights($dropzone->getResourceNode());
     // Fin ajout du code pour afficher les élèves inscrits mais qui n'ont pas déposé. InnovaERV.
     // dropsQuery : finished à TRUE et unlocked_drop à FALSE
     $dropsQuery = $dropRepo->getSharedSpacesQuery($dropzone, $workspace);
     $countUnterminatedDrops = $dropRepo->countUnterminatedDropsByDropzone($dropzone->getId());
     // Déclarations des nouveaux tableaux, qui seront passés à la vue
     $userNbDocDropped = array();
     $userNbAdressedRequests = array();
     foreach ($dropzone->getDrops() as $drop) {
         /** InnovaERV : ajout pour calculer les 2 zones **/
         // Nombre de documents déposés/ Repo : Document
         $nbDocDropped = $this->getDoctrine()->getRepository('InnovaCollecticielBundle:Document')->countDocSubmissions($drop->getUser(), $drop->getDropZone());
         // Nombre de demandes adressées/ Repo : Document
         $nbAdressedRequests = $this->getDoctrine()->getRepository('InnovaCollecticielBundle:Document')->countTextToRead($drop->getUser(), $drop->getDropZone());
         // Affectations des résultats dans les tableaux
         $userNbDocDropped[$drop->getUser()->getId()] = $nbDocDropped;
         $userNbAdressedRequests[$drop->getUser()->getId()] = $nbAdressedRequests;
     }
     $adapter = new DoctrineORMAdapter($dropsQuery);
     $pager = new Pagerfanta($adapter);
     $pager->setMaxPerPage(DropzoneBaseController::DROP_PER_PAGE);
     //echo DropzoneBaseController::DROP_PER_PAGE . "--";
     try {
         $pager->setCurrentPage($page);
     } catch (NotValidCurrentPageException $e) {
         if ($page > 0) {
             return $this->redirect($this->generateUrl('innova_collecticiel_shared_spaces_paginated', array('resourceId' => $dropzone->getId(), 'page' => $pager->getNbPages())));
         } else {
             throw new NotFoundHttpException();
         }
     }
     $adminInnova = $dropzoneVoter->checkEditRight($dropzone);
     $collecticielOpenOrNot = $dropzoneManager->collecticielOpenOrNot($dropzone);
     /*
             if ($this->get('security.context')->isGranted('ROLE_ADMIN' === true)) {
                 $adminInnova = true;
             }*/
     $dataToView = $this->addDropsStats($dropzone, array('workspace' => $dropzone->getResourceNode()->getWorkspace(), '_resource' => $dropzone, 'dropzone' => $dropzone, 'unterminated_drops' => $countUnterminatedDrops, 'pager' => $pager, 'userNbDocDropped' => $userNbDocDropped, 'userNbAdressedRequests' => $userNbAdressedRequests, 'adminInnova' => $adminInnova, 'usersByWorkspaces' => $usersByWorkspaces, 'collecticielOpenOrNot' => $collecticielOpenOrNot));
     return $dataToView;
 }
 /**
  * {@inheritdoc}
  */
 public function valid()
 {
     return $this->currentPage <= $this->pager->getNbPages();
 }
 protected function configureCollectionRepresentation(CollectionRepresentation $collectionRepresentation, Pagerfanta $pager, $entity = null, $collectionRel = null)
 {
     // Properties
     $collectionRepresentation->total = $pager->getNbResults();
     $collectionRepresentation->page = $pager->getCurrentPage();
     $collectionRepresentation->limit = $pager->getMaxPerPage();
     // Links between pages
     $createRoute = function ($page, $limit) use($entity, $collectionRel) {
         $parameters = array('search' => array('page' => $page, 'limit' => $limit));
         return null !== $entity && null !== $collectionRel ? $this->getUrlGenerator()->generateEntityCollectionUrl($entity, $collectionRel, $parameters) : $this->getUrlGenerator()->generateCollectionUrl($parameters);
     };
     $collectionRepresentation->addLink($this->atomLinkFactory->create('self', $createRoute($pager->getCurrentPage(), $pager->getMaxPerPage())));
     if ($pager->hasNextPage()) {
         $collectionRepresentation->addLink($this->atomLinkFactory->create('next', $createRoute($pager->getNextPage(), $pager->getMaxPerPage())));
     }
     if ($pager->hasPreviousPage()) {
         $collectionRepresentation->addLink($this->atomLinkFactory->create('previous', $createRoute($pager->getPreviousPage(), $pager->getMaxPerPage())));
     }
     $collectionRepresentation->addLink($this->atomLinkFactory->create('first', $createRoute(1, $pager->getMaxPerPage())));
     $collectionRepresentation->addLink($this->atomLinkFactory->create('last', $createRoute($pager->getNbPages(), $pager->getMaxPerPage())));
 }
 public function serializePagerfantaToJson(JsonSerializationVisitor $visitor, Pagerfanta $pagerfanta, array $type, Context $context)
 {
     $type['name'] = 'array';
     return ['items' => $visitor->visitArray((array) $pagerfanta->getCurrentPageResults(), $type, $context), 'pages_count' => $pagerfanta->getNbPages(), 'current_page' => $pagerfanta->getCurrentPage(), 'max_per_page' => $pagerfanta->getMaxPerPage(), 'items_count' => $pagerfanta->count()];
 }
 /**
  * Get the last page.
  *
  * @return int
  */
 public function getLastPage()
 {
     return $this->paginator->getNbPages();
 }
 /**
  *
  * @Route(
  *      "/{resourceId}/examiners/{withDropOnly}",
  *      name="innova_collecticiel_examiners",
  *      requirements ={"resourceId" ="\d+","withDropOnly"="^(withDropOnly|all|withoutDrops)$"},
  *      defaults={"page" = 1, "withDropOnly" = "all" }
  * )
  *
  * @Route(
  *      "/{resourceId}/examiners/{withDropOnly}/{page}",
  *      name="innova_collecticiel_examiners_paginated",
  *      requirements ={"resourceId" ="\d+","withDropOnly"="^(withDropOnly|all|withoutDrops)$","page"="\d+"},
  *      defaults={"page" = 1, "withDropOnly" = "all" }
  * )
  *
  *
  * @ParamConverter("dropzone",class="InnovaCollecticielBundle:Dropzone",options={"id" = "resourceId"})
  * @Template()
  *
  *
  * **/
 public function ExaminersByCorrectionMadeAction($dropzone, $page, $withDropOnly)
 {
     // check rights
     $this->get('innova.manager.dropzone_voter')->isAllowToOpen($dropzone);
     $this->get('innova.manager.dropzone_voter')->isAllowToEdit($dropzone);
     /*
     // view only available in peerReview mode
     if(! $dropzone->getPeerReview())
     {
         // redirection if the dropzone is not in PeerReview.
         return $this->redirect(
                 $this->generateUrl(
                     'innova_collecticiel_drop',
                     array(
                         'resourceId' => $dropzone->getId()
                     )
                 )
             );
     }
     */
     //getting the repos
     $dropRepo = $this->getDoctrine()->getManager()->getRepository('InnovaCollecticielBundle:Drop');
     $countUnterminatedDrops = $dropRepo->countUnterminatedDropsByDropzone($dropzone->getId());
     $correctionRepo = $this->getDoctrine()->getManager()->getRepository('InnovaCollecticielBundle:Correction');
     // getting the Query of  users that have at least one correction.
     $usersQuery = $correctionRepo->getUsersByDropzoneQuery($dropzone);
     // pagitation management.
     $adapter = new DoctrineORMAdapter($usersQuery);
     $pager = new Pagerfanta($adapter);
     $pager->setMaxPerPage(DropzoneBaseController::DROP_PER_PAGE);
     try {
         $pager->setCurrentPage($page);
     } catch (NotValidCurrentPageException $e) {
         if ($page > 0) {
             return $this->redirect($this->generateUrl('innova_collecticiel_examiners_paginated', array('resourceId' => $dropzone->getId(), 'page' => $pager->getNbPages())));
         } else {
             throw new NotFoundHttpException();
         }
     }
     // execute the query and get the users.
     $users = $usersQuery->getResult();
     // add some count needed by the view.
     $usersAndCorrectionCount = $this->addCorrectionCount($dropzone, $users);
     $response = array('workspace' => $dropzone->getResourceNode()->getWorkspace(), '_resource' => $dropzone, 'dropzone' => $dropzone, 'usersAndCorrectionCount' => $usersAndCorrectionCount, 'nbDropCorrected' => $dropRepo->countDropsFullyCorrected($dropzone), 'nbDrop' => $dropRepo->countDrops($dropzone), 'unterminated_drops' => $countUnterminatedDrops, 'pager' => $pager);
     return $this->render('InnovaCollecticielBundle:Drop:Examiners/ExaminersByName.htlm.twig', $response);
 }
    /**
     * Return list of event sorted 
     * @param Location $location
     * @param type $maxPerPage
     * @param type $currentPage
     * @return type
     */
    public function getFolderChildrens( Location $location, $maxPerPage, $currentPage = 1 )
    {

        $criteria = array(
            new Criterion\ParentLocationId( $location->parentLocationId ),
            new Criterion\ContentTypeIdentifier( array( 'agenda_event' ) ),
            new Criterion\Visibility( Criterion\Visibility::VISIBLE ),
            new Criterion\Field( 'publish_start', Criterion\Operator::LT, time() ),
            new Criterion\LogicalOr( array(
                new Criterion\Field( 'publish_end', Criterion\Operator::GT, time() ), new Criterion\Field( 'publish_end', Criterion\Operator::EQ, 0 )
                    ) )
        );
        $query = new Query();
        $query->filter = new Criterion\LogicalAnd( $criteria );
        $query->sortClauses = array(
            $this->sortClauseAuto( $location )
        );

        $searchResult = $this->repository->getSearchService()->findContent( $query );

        $content = array();
        foreach( $searchResult->searchHits as $agendaEvent )
        {
            $listDates = $this->getChildren( $agendaEvent );
            foreach( $listDates->searchHits as $agendaSchedule )
            {
                $content[] = array(
                    'AgendaEvent' => $agendaEvent->valueObject->contentInfo->mainLocationId,
                    'AgendaSchedule' => $agendaSchedule->valueObject->contentInfo->mainLocationId,
                    'start' => $this->getFormattedDate( $agendaSchedule, 'order' )
                );
            }
        }

        usort( $content, array( $this, 'agendaSortMethod' ) );

        $result['offset'] = ($currentPage - 1) * $maxPerPage;
        $adapter = new ArrayAdapter( $content );
        $pagerfanta = new Pagerfanta( $adapter );

        $pagerfanta->setMaxPerPage( $maxPerPage );
        $pagerfanta->setCurrentPage( $currentPage );

        $result['prev_page'] = $pagerfanta->hasPreviousPage() ? $pagerfanta->getPreviousPage() : 0;
        $result['next_page'] = $pagerfanta->hasNextPage() ? $pagerfanta->getNextPage() : 0;
        $result['nb_pages'] = $pagerfanta->getNbPages();
        $result['items'] = $pagerfanta->getCurrentPageResults();
        $result['base_href'] = "?";
        $result['current_page'] = $pagerfanta->getCurrentPage();
        return $result;
    }
Exemple #22
0
 /**
  * Global method to retrieve entries depending on the given type
  * It returns the response to be send.
  *
  * @param string  $type    Entries type: unread, starred or archive
  * @param Request $request
  * @param int     $page
  *
  * @return \Symfony\Component\HttpFoundation\Response
  */
 private function showEntries($type, Request $request, $page)
 {
     $repository = $this->get('wallabag_core.entry_repository');
     switch ($type) {
         case 'starred':
             $qb = $repository->getBuilderForStarredByUser($this->getUser()->getId());
             break;
         case 'archive':
             $qb = $repository->getBuilderForArchiveByUser($this->getUser()->getId());
             break;
         case 'unread':
             $qb = $repository->getBuilderForUnreadByUser($this->getUser()->getId());
             break;
         case 'all':
             $qb = $repository->getBuilderForAllByUser($this->getUser()->getId());
             break;
         default:
             throw new \InvalidArgumentException(sprintf('Type "%s" is not implemented.', $type));
     }
     $form = $this->createForm(EntryFilterType::class);
     if ($request->query->has($form->getName())) {
         // manually bind values from the request
         $form->submit($request->query->get($form->getName()));
         // build the query from the given form object
         $this->get('lexik_form_filter.query_builder_updater')->addFilterConditions($form, $qb);
     }
     $pagerAdapter = new DoctrineORMAdapter($qb->getQuery());
     $entries = new Pagerfanta($pagerAdapter);
     $entries->setMaxPerPage($this->getUser()->getConfig()->getItemsPerPage());
     try {
         $entries->setCurrentPage($page);
     } catch (OutOfRangeCurrentPageException $e) {
         if ($page > 1) {
             return $this->redirect($this->generateUrl($type, ['page' => $entries->getNbPages()]), 302);
         }
     }
     return $this->render('WallabagCoreBundle:Entry:entries.html.twig', ['form' => $form->createView(), 'entries' => $entries, 'currentPage' => $page]);
 }
 public function create(Pagerfanta $pager, $route, array $routeParameters = array())
 {
     return new PaginatedCollection($pager->getCurrentPageResults(), $route, $routeParameters, $pager->getCurrentPage(), $pager->getMaxPerPage(), $pager->getNbPages(), $this->pageParameterName, $this->limitParameterName);
 }
 public function getPagedCollection($page = 1, $limit = 10, $query = null, $sorting = null, $order = 'DESC')
 {
     $queryBuilder = $this->repository->createQueryBuilder('e');
     $this->prepareJoinedQuery($queryBuilder);
     if ($query) {
         $this->createFilterQuery($queryBuilder, $query);
     }
     if ($sorting) {
         if (strpos($sorting, '.') === false) {
             $queryBuilder->addOrderBy(sprintf('e.%s', $sorting), $order);
         } else {
             $queryBuilder->addOrderBy($sorting, $order);
         }
     }
     $pagerAdapter = new DoctrineORMAdapter($queryBuilder);
     $pager = new Pagerfanta($pagerAdapter);
     $pager->setCurrentPage($page);
     $pager->setMaxPerPage($limit);
     return ['limit' => (int) $limit, 'page' => (int) $page, 'pages' => $pager->getNbPages(), 'total' => $pager->getNbResults(), 'data' => $pager->getIterator()->getArrayCopy()];
 }
 /**
  * @param Pagerfanta $pager
  *
  * @return array
  */
 protected function getPagerMeta(Pagerfanta $pager)
 {
     if ($pager instanceof OutOfRangePager) {
         return array('currentPage' => $pager->getOriginalPage(), 'maxPerPage' => $pager->getMaxPerPage(), 'hasNextPage' => false, 'outOfRange' => true);
     }
     $meta = array('currentPage' => $pager->getCurrentPage(), 'maxPerPage' => $pager->getMaxPerPage(), 'pagesCount' => $pager->getNbPages(), 'hasNextPage' => $pager->hasNextPage(), 'resultsCount' => $pager->getNbResults(), 'hasPreviousPage' => $pager->hasPreviousPage());
     if ($pager->hasNextPage()) {
         $meta['nextPage'] = $pager->getNextPage();
     }
     if ($pager->hasPreviousPage()) {
         $meta['previousPage'] = $pager->getPreviousPage();
     }
     return $meta;
 }
 /**
  *@Route(
  *      "/{resourceId}/edit/criteria",
  *      name="innova_collecticiel_edit_criteria",
  *      requirements={"resourceId" = "\d+"},
  *      defaults={"page" = 1}
  * )
  *@Route(
  *      "/{resourceId}/edit/criteria",
  *      name="innova_collecticiel_edit_criteria_innova",
  *      requirements={"resourceId" = "\d+"},
  *      defaults={"page" = 1}
  * )
  *
  *@Route(
  *      "/{resourceId}/edit/criteria/{page}",
  *      name="innova_collecticiel_edit_criteria_paginated",
  *      requirements={"resourceId" = "\d+", "page" = "\d+"},
  *      defaults={"page" = 1}
  * )
  *@ParamConverter("dropzone",
  * class="InnovaCollecticielBundle:Dropzone", options={"id" = "resourceId"})
  *@Template()
  *
  * @param Dropzone $dropzone dropzone to handle
  * @param int      $page     page to display
  *
  *@return array (workspace, _resource,dropzone,pager,form,
  *nbCorrection,add_criteria_after,
  *adminInnova,collecticielOpenOrNot)
  */
 public function editCriteriaAction(Dropzone $dropzone, $page)
 {
     $this->get('innova.manager.dropzone_voter')->isAllowToOpen($dropzone);
     $this->get('innova.manager.dropzone_voter')->isAllowToEdit($dropzone);
     $em = $this->getDoctrine()->getManager();
     $repository = $em->getRepository('InnovaCollecticielBundle:Criterion');
     $query = $repository->createQueryBuilder('criterion')->andWhere('criterion.dropzone = :dropzone')->setParameter('dropzone', $dropzone)->orderBy('criterion.id', 'ASC');
     $adapter = new DoctrineORMAdapter($query);
     $pager = new Pagerfanta($adapter);
     $pager->setMaxPerPage(DropzoneBaseController::CRITERION_PER_PAGE);
     try {
         $pager->setCurrentPage($page);
     } catch (NotValidCurrentPageException $e) {
         if ($page > 0) {
             return $this->redirect($this->generateUrl('innova_collecticiel_edit_criteria_paginated', ['resourceId' => $dropzone->getId(), 'page' => $pager->getNbPages()]));
         } else {
             throw new NotFoundHttpException();
         }
     }
     $nbCorrection = $this->getDoctrine()->getManager()->getRepository('InnovaCollecticielBundle:Correction')->countByDropzone($dropzone->getId());
     $form = $this->createForm(new DropzoneCriteriaType(), $dropzone);
     $add_criteria_after = false;
     if ($this->getRequest()->isMethod('POST')) {
         $form->handleRequest($this->getRequest());
         if ($form->isValid()) {
             $add_criteria_after = $this->getRequest()->request->get('addCriteria') === 'add-criterion' ? true : false;
             $dropzone = $form->getData();
             if ($dropzone->getEditionState() < 3) {
                 $dropzone->setEditionState(3);
             }
             $em = $this->getDoctrine()->getManager();
             $unitOfWork = $em->getUnitOfWork();
             $unitOfWork->computeChangeSets();
             $changeSet = $unitOfWork->getEntityChangeSet($dropzone);
             $em->persist($dropzone);
             $em->flush();
             if ($form->get('recalculateGrades')->getData() === 1) {
                 $this->get('innova.manager.dropzone_manager')->recalculateScoreByDropzone($dropzone);
                 $this->getRequest()->getSession()->getFlashBag()->add('success', $this->get('translator')->trans('Grades were recalculated', [], 'innova_collecticiel'));
             }
             $event = new LogDropzoneConfigureEvent($dropzone, $changeSet);
             $this->dispatch($event);
             if ($dropzone->hasCriteria() === false) {
                 $this->getRequest()->getSession()->getFlashBag()->add('warning', $this->get('translator')->trans('Warning your peer review offers no criteria
                              on which to base correct copies', [], 'innova_collecticiel'));
             }
             if ($add_criteria_after) {
                 return new JsonResponse(['success' => true]);
             }
             $goBack = $form->get('goBack')->getData();
             if ($goBack === 0) {
                 $this->getRequest()->getSession()->getFlashBag()->add('success', $this->get('translator')->trans('The collecticiel has been successfully saved', [], 'innova_collecticiel'));
             } else {
                 return $this->redirect($this->generateUrl('innova_collecticiel_edit_common', ['resourceId' => $dropzone->getId()]));
             }
         }
     }
     $dropzoneVoter = $this->get('innova.manager.dropzone_voter');
     $dropzoneManager = $this->get('innova.manager.dropzone_manager');
     $collecticielOpenOrNot = $dropzoneManager->collecticielOpenOrNot($dropzone);
     $adminInnova = $dropzoneVoter->checkEditRight($dropzone);
     return ['workspace' => $dropzone->getResourceNode()->getWorkspace(), '_resource' => $dropzone, 'dropzone' => $dropzone, 'pager' => $pager, 'form' => $form->createView(), 'nbCorrection' => $nbCorrection, 'add_criteria_after' => $add_criteria_after, 'adminInnova' => $adminInnova, 'collecticielOpenOrNot' => $collecticielOpenOrNot];
 }
 /**
  * @Route(
  *      "/{resourceId}/shared/spaces",
  *      name="innova_collecticiel_shared_spaces",
  *      requirements={"resourceId" = "\d+"},
  *      defaults={"page" = 1}
  * )
  * @Route(
  *      "/{resourceId}/shared/spaces/{page}",
  *      name="innova_collecticiel_shared_spaces_paginated",
  *      requirements={"resourceId" = "\d+", "page" = "\d+"},
  *      defaults={"page" = 1}
  * )
  * @ParamConverter("dropzone", class="InnovaCollecticielBundle:Dropzone", options={"id" = "resourceId"})
  * @Template()
  */
 public function sharedSpacesAction(Dropzone $dropzone, $page)
 {
     $this->get('innova.manager.dropzone_voter')->isAllowToOpen($dropzone);
     $this->get('innova.manager.dropzone_voter')->isAllowToEdit($dropzone);
     $dropzoneManager = $this->get('innova.manager.dropzone_manager');
     $dropManager = $this->get('innova.manager.drop_manager');
     $userManager = $this->get('claroline.manager.user_manager');
     $dropzoneVoter = $this->get('innova.manager.dropzone_voter');
     $resourceNode = $dropzone->getResourceNode();
     $workspace = $resourceNode->getWorkspace();
     $dropRepo = $this->getDoctrine()->getManager()->getRepository('InnovaCollecticielBundle:Drop');
     // dropsQuery : finished à TRUE et unlocked_drop à FALSE
     $dropsQuery = $dropRepo->getSharedSpacesQuery($dropzone, $workspace);
     $adapter = new DoctrineORMAdapter($dropsQuery);
     $pager = new Pagerfanta($adapter);
     $pager->setMaxPerPage(DropzoneBaseController::DROP_PER_PAGE);
     try {
         $pager->setCurrentPage($page);
     } catch (NotValidCurrentPageException $e) {
         if ($page > 0) {
             return $this->redirect($this->generateUrl('innova_collecticiel_shared_spaces_paginated', ['resourceId' => $dropzone->getId(), 'page' => $pager->getNbPages()]));
         } else {
             throw new NotFoundHttpException();
         }
     }
     $isAdmin = $dropzoneVoter->checkEditRight($dropzone);
     $isOpen = $dropzoneManager->collecticielOpenOrNot($dropzone);
     $userNbDocDropped = $dropManager->getDroppedDocsByUserCount($dropzone);
     $userNbAdressedRequests = $dropManager->getRequestByUserCount($dropzone);
     $countUnterminatedDrops = $dropRepo->countUnterminatedDropsByDropzone($dropzone->getId());
     $usersByWorkspaces = $userManager->getUsersByWorkspaces([$workspace->getId()], $page, 20, false);
     $dataToView = $this->addDropsStats($dropzone, ['workspace' => $workspace, '_resource' => $dropzone, 'dropzone' => $dropzone, 'unterminated_drops' => $countUnterminatedDrops, 'pager' => $pager, 'userNbDocDropped' => $userNbDocDropped, 'userNbAdressedRequests' => $userNbAdressedRequests, 'adminInnova' => $isAdmin, 'usersByWorkspaces' => $usersByWorkspaces, 'collecticielOpenOrNot' => $isOpen]);
     return $dataToView;
 }
 /**
  * Get the view list of multimedia objects
  * belonging to a series
  */
 private function getListMultimediaObjects(Series $series, $newMultimediaObjectId = null)
 {
     $session = $this->get('session');
     $page = $session->get('admin/mms/page', 1);
     $maxPerPage = $session->get('admin/mms/paginate', 10);
     $sorting = array("rank" => "asc");
     $mmsQueryBuilder = $this->get('doctrine_mongodb.odm.document_manager')->getRepository('PumukitSchemaBundle:MultimediaObject')->getQueryBuilderOrderedBy($series, $sorting);
     $adapter = new DoctrineODMMongoDBAdapter($mmsQueryBuilder);
     $mms = new Pagerfanta($adapter);
     $mms->setMaxPerPage($maxPerPage)->setNormalizeOutOfRangePages(true);
     /*
       NOTE: Multimedia Objects are sorted by ascending rank.
       A new MultimediaObject is created with last rank,
       so it will be at the end of the list.
       We update the page if a new page is created to show the
       the new MultimediaObject in new last page.
     */
     if ($newMultimediaObjectId && $mms->getNbResults() / $maxPerPage > $page) {
         $page = $mms->getNbPages();
         $session->set('admin/mms/page', $page);
     }
     $mms->setCurrentPage($page);
     return $mms;
 }
Exemple #29
0
 /**
  * Perform a search and return a JSON response.
  *
  * @param Request $request
  *
  * @return Response
  */
 public function searchAction(Request $request)
 {
     $queryString = $request->query->get('q');
     $index = $request->query->get('index', null);
     $locale = $request->query->get('locale', null);
     $page = $this->listRestHelper->getPage();
     $limit = $this->listRestHelper->getLimit();
     $startTime = microtime(true);
     $indexes = $index ? [$index] : $this->getAllowedIndexes();
     $query = $this->searchManager->createSearch($queryString);
     if ($locale) {
         $query->locale($locale);
     }
     $query->indexes($indexes);
     $query->setLimit($limit);
     $time = microtime(true) - $startTime;
     $adapter = new ArrayAdapter(iterator_to_array($query->execute()));
     $pager = new Pagerfanta($adapter);
     $pager->setMaxPerPage($limit);
     $pager->setCurrentPage($page);
     $representation = new SearchResultRepresentation(new CollectionRepresentation($pager->getCurrentPageResults(), 'result'), 'sulu_search_search', ['locale' => $locale, 'query' => $query, 'index' => $index], (int) $page, (int) $limit, $pager->getNbPages(), 'page', 'limit', false, $adapter->getNbResults(), $this->getIndexTotals($adapter->getArray()), number_format($time, 8));
     $view = View::create($representation);
     $context = SerializationContext::create();
     $context->enableMaxDepthChecks();
     $context->setSerializeNull(true);
     $view->setSerializationContext($context);
     return $this->viewHandler->handle($view);
 }
Exemple #30
0
 /**
  * @param Pagerfanta $pagerfanta
  * @param int $page
  * @return int
  */
 protected function normalizePage(Pagerfanta $pagerfanta, $page)
 {
     return max(1, min($page, $pagerfanta->getNbPages()));
 }