public function indexAction(Request $request, $page = 1) { $getTypes = $request->query->get('type_filters'); $getSubjects = $request->query->get('subject_filters'); $getPublishers = $request->query->get('publisher_filters'); $typeFilters = !empty($getTypes) ? explode(',', $getTypes) : []; $subjectFilters = !empty($getSubjects) ? explode(',', $getSubjects) : []; $publisherFilters = !empty($getPublishers) ? explode(',', $getPublishers) : []; $journalSearcher = $this->get('fos_elastica.index.search.journal'); $boolQuery = new Query\Bool(); $match = new Query\Match(); $match->setField('status', 1); $boolQuery->addMust($match); $match = new Query\Match(); $match->setField('published', true); $boolQuery->addMust($match); if (!empty($typeFilters) || !empty($subjectFilters) || !empty($publisherFilters)) { foreach ($typeFilters as $type) { $match = new Query\Match(); $match->setField('publisher.publisher_type.name', $type); $boolQuery->addMust($match); } foreach ($subjectFilters as $subject) { $match = new Query\Match(); $match->setField('subjects.subject', $subject); $boolQuery->addMust($match); } foreach ($publisherFilters as $publisher) { $match = new Query\Match(); $match->setField('publisher.name', $publisher); $boolQuery->addMust($match); } } $journalQuery = new Query($boolQuery); $typeAgg = new Aggregation\Terms('types'); $typeAgg->setField('publisher.publisher_type.name'); $typeAgg->setOrder('_term', 'asc'); $typeAgg->setSize(0); $journalQuery->addAggregation($typeAgg); $subjectAgg = new Aggregation\Terms('subjects'); $subjectAgg->setField('subjects.subject'); $subjectAgg->setOrder('_term', 'asc'); $subjectAgg->setSize(0); $journalQuery->addAggregation($subjectAgg); $publisherAgg = new Aggregation\Terms('publishers'); $publisherAgg->setField('publisher.name'); $publisherAgg->setOrder('_term', 'asc'); $publisherAgg->setSize(0); $journalQuery->addAggregation($publisherAgg); $adapter = new ElasticaAdapter($journalSearcher, $journalQuery); $pagerfanta = new Pagerfanta($adapter); $pagerfanta->setMaxPerPage(21); $pagerfanta->setCurrentPage($page); $journals = $pagerfanta->getCurrentPageResults(); $types = $adapter->getResultSet()->getAggregation('types')['buckets']; $subjects = $adapter->getResultSet()->getAggregation('subjects')['buckets']; $publishers = $adapter->getResultSet()->getAggregation('publishers')['buckets']; $data = ['types' => $types, 'subjects' => $subjects, 'publishers' => $publishers, 'type_filters' => $typeFilters, 'subject_filters' => $subjectFilters, 'publisher_filters' => $publisherFilters, 'journals' => $journals, 'pagerfanta' => $pagerfanta, 'page' => 'explore']; return $this->render('OjsSiteBundle:Explore:index.html.twig', $data); }
public function searchAction(Request $request) { $format = $request->getRequestFormat(); $query = trim($request->query->get('q')); if (empty($query)) { if ('json' === $format) { return new JsonResponse(array('status' => 'error', 'message' => 'Missing or too short search query, example: ?q=example'), 400); } return $this->render('KnpBundlesBundle:Bundle:search.html.twig'); } // Skip search if query matches exactly one bundle name, and such was found in database if (!$request->isXmlHttpRequest() && preg_match('/^[a-z0-9-]+\\/[a-z0-9-]+$/i', $query)) { list($ownerName, $name) = explode('/', $query); $bundle = $this->getRepository('Bundle')->findOneBy(array('ownerName' => $ownerName, 'name' => $name)); if ($bundle) { return $this->redirect($this->generateUrl('bundle_show', array('ownerName' => $ownerName, 'name' => $name, '_format' => $format))); } } /** @var $solarium \Solarium_Client */ $solarium = $this->get('solarium.client'); $select = $solarium->createSelect(); $escapedQuery = $select->getHelper()->escapeTerm($query); $dismax = $select->getDisMax(); $dismax->setQueryFields(array('name^2', 'ownerName', 'fullName^1.5', 'description', 'keywords', 'text', 'text_ngram')); $dismax->setPhraseFields(array('description^30')); $dismax->setQueryParser('edismax'); $select->setQuery($escapedQuery); try { $paginator = new Pagerfanta(new SolariumAdapter($solarium, $select)); $paginator->setMaxPerPage($request->query->get('limit', 10))->setCurrentPage($request->query->get('page', 1), false, true); if (1 === $paginator->getNbResults() && !$request->isXmlHttpRequest()) { $first = $paginator->getCurrentPageResults()->getIterator()->current(); if (strtolower($first['name']) == strtolower($query)) { return $this->redirect($this->generateUrl('bundle_show', array('ownerName' => $first['ownerName'], 'name' => $first['name'], '_format' => $format))); } } } catch (\Solarium_Client_HttpException $e) { $msg = 'Seems that our search engine is currently offline. Please check later.'; if ('json' === $format) { return new JsonResponse(array('status' => 'error', 'message' => $msg), 500); } throw new HttpException(500, $msg); } if ('json' === $format) { $result = array('results' => array(), 'total' => $paginator->getNbResults()); foreach ($paginator as $bundle) { $result['results'][] = array('name' => $bundle->fullName, 'description' => null !== $bundle->description ? substr($bundle->description, 0, 110) . '...' : '', 'avatarUrl' => $bundle->avatarUrl ?: 'http://www.gravatar.com/avatar/?d=identicon&f=y&s=50', 'state' => $bundle->state, 'score' => $bundle->totalScore, 'url' => $this->generateUrl('bundle_show', array('ownerName' => $bundle->ownerName, 'name' => $bundle->name), true)); } if (!$request->isXmlHttpRequest()) { if ($paginator->hasPreviousPage()) { $result['prev'] = $this->generateUrl('search', array('q' => urldecode($query), 'page' => $paginator->getPreviousPage(), '_format' => 'json'), true); } if ($paginator->hasNextPage()) { $result['next'] = $this->generateUrl('search', array('q' => urldecode($query), 'page' => $paginator->getNextPage(), '_format' => 'json'), true); } } return new JsonResponse($request->isXmlHttpRequest() ? $result['results'] : $result); } return $this->render('KnpBundlesBundle:Bundle:searchResults.html.twig', array('query' => urldecode($query), 'bundles' => $paginator)); }
/** * @return Pagerfanta */ public function getPagerfanta() { if (is_null($this->pagerfanta)) { $adapter = new DoctrineDBALAdapter($this->getQueryBuilder(), $this->getCountField(), $this->getUseDistinctCount()); $this->pagerfanta = new Pagerfanta($adapter); $this->pagerfanta->setCurrentPage($this->getPage()); $this->pagerfanta->setMaxPerPage($this->getLimit()); } return $this->pagerfanta; }
/** * @return Pagerfanta */ public function getPagerfanta() { if (is_null($this->pagerfanta)) { $adapter = new DoctrineORMAdapter($this->getQuery()); $this->pagerfanta = new Pagerfanta($adapter); $this->pagerfanta->setNormalizeOutOfRangePages(true); $this->pagerfanta->setMaxPerPage($this->getLimit()); $this->pagerfanta->setCurrentPage($this->getPage()); } return $this->pagerfanta; }
/** * 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); }
/** * @param TaxonInterface $taxon * @param Pagerfanta $results * @param $template * @param $page * @param null $facets * @param null $facetTags * @param null $filters * @param null $searchTerm * @param null $searchParam * @param null $requestMethod * @return \Symfony\Component\HttpFoundation\Response */ private function renderResults(TaxonInterface $taxon, Pagerfanta $results, $template, $page, $facets = null, $facetTags = null, $filters = null, $searchTerm = null, $searchParam = null, $requestMethod = null) { $results->setCurrentPage($page, true, true); $results->setMaxPerPage($this->config->getPaginationMaxPerPage()); $view = $this->view()->setTemplate($this->config->getTemplate($template))->setData(array('taxon' => $taxon, 'products' => $results, 'facets' => $facets, 'facetTags' => $facetTags, 'filters' => $filters, 'searchTerm' => $searchTerm, 'searchParam' => $searchParam, 'requestMethod' => $requestMethod)); return $this->handleView($view); }
/** * Get search results from Google. * * {@inheritdoc} */ public function getPagerfanta($query, $locale) { $adapter = new GoogleRestAdapter($this->googleApiKey, $this->getSearchKey($locale), $this->googleSearchAPIUrl, $query, $this->restrictLanguage ? $locale : false, $this->restrictToSite); $pager = new Pagerfanta($adapter); $pager->setMaxPerPage($this->maxPerPage); return $pager; }
protected function execute(InputInterface $input, OutputInterface $output) { /** @var $repo Repo */ $em = $this->getContainer()->get('doctrine.orm.entity_manager'); $repo = $this->getContainer()->get('knp_bundles.github_repository_api'); $page = 1; $pager = new Pagerfanta(new DoctrineORMAdapter($em->getRepository('KnpBundlesBundle:Bundle')->queryAllSortedBy('updatedAt'), false)); $pager->setMaxPerPage(100)->setCurrentPage($page, false, true); if (1 === $page) { $output->writeln(sprintf('[%s] Loaded <comment>%d</comment> bundles from the DB', date('d-m-y H:i:s'), $pager->getNbResults())); } do { /** @var $bundle Bundle */ foreach ($pager->getCurrentPageResults() as $bundle) { // Check that API not failed if (!$repo->updateCommits($bundle)) { // Sleep a while, and check again sleep(60); $repo->updateCommits($bundle); } $em->persist($bundle); } $output->writeln(sprintf('[%s] Migrated %d from %d bundles', date('d-m-y H:i:s'), $page * 100, $pager->getNbResults())); $em->flush(); ++$page; } while ($pager->hasNextPage() && $pager->setCurrentPage($page, false, true)); return 0; }
/** * @param int $page * @return \Symfony\Component\HttpFoundation\Response */ public function listAction($page) { $pagerfanta = new Pagerfanta($this->galleryManager->createPagerfantaAdapter()); $pagerfanta->setMaxPerPage($this->galleriesPerPage); $pagerfanta->setCurrentPage($page); return $this->templating->renderResponse('FSiGalleryBundle:Gallery:list.html.twig', array('galleries' => $pagerfanta, 'preview_photos_count' => $this->previewPhotosCount)); }
/** * @return string */ public function renderPagination(Page $page, Twig_Environment $environment) { $pagerfanta = new Pagerfanta(new PorpaginasAdapter($page)); $pagerfanta->setCurrentPage($page->getCurrentPage()); $pagerfanta->setMaxPerPage($page->getCurrentLimit()); return $environment->getExtension('pagerfanta')->renderPagerfanta($pagerfanta, $this->viewName, $this->options); }
/** * @param int $page * * @return Pagerfanta */ public function findLatest($page = 1) { $paginator = new Pagerfanta(new DoctrineORMAdapter($this->queryLatest(), false)); $paginator->setMaxPerPage(Post::NUM_ITEMS); $paginator->setCurrentPage($page); return $paginator; }
protected function execute(InputInterface $input, OutputInterface $output) { /** @var SolrIndexer $indexer */ $indexer = $this->getContainer()->get('knp_bundles.indexer.solr'); /** @var EntityManager $em */ $em = $this->getContainer()->get('doctrine')->getManager(); /** @var \Solarium_Client $solarium */ $solarium = $this->getContainer()->get('solarium.client'); /** @var EntityRepository $repository */ $repository = $em->getRepository('KnpBundlesBundle:Bundle'); $query = $solarium->createSelect(); $query->setFields(array('name', 'ownerName')); try { $hasMoreResults = true; $page = 1; while ($hasMoreResults) { $paginator = new Pagerfanta(new SolariumAdapter($solarium, $query)); $paginator->setMaxPerPage(50)->setCurrentPage($page, false, true); foreach ($paginator as $bundle) { $entity = $repository->findOneBy(array('name' => $bundle['name'])); if (!$entity) { $entity = new Bundle(); $entity->setName($bundle['name']); $entity->setOwnerName($bundle['ownerName']); $indexer->deleteBundlesIndexes($entity); $output->writeln(sprintf('The bundle "%s" was deleted from solr index.', $entity->getFullName())); } } $hasMoreResults = $paginator->getNbResults() == 50; $page++; } } catch (\Solarium_Client_HttpException $e) { throw new \Exception('Seems that our search engine is currently offline. Please check later.'); } }
/** * Creates a Doctrine ORM paginator for the given query builder. * * @param DoctrineQuery|DoctrineQueryBuilder $queryBuilder * @param int $page * @param int $maxPerPage * * @return Pagerfanta */ public function createOrmPaginator($queryBuilder, $page = 1, $maxPerPage = self::MAX_ITEMS) { $paginator = new Pagerfanta(new DoctrineORMAdapter($queryBuilder, true, false)); $paginator->setMaxPerPage($maxPerPage); $paginator->setCurrentPage($page); return $paginator; }
/** * @Route("/opencast/mediapackage", name="pumukitopencast") * @Template() */ public function indexAction(Request $request) { if (!$this->has('pumukit_opencast.client')) { throw $this->createNotFoundException('PumukitOpencastBundle not configured.'); } $opencastClient = $this->get('pumukit_opencast.client'); $repository_multimediaobjects = $this->get('doctrine_mongodb')->getRepository('PumukitSchemaBundle:MultimediaObject'); $limit = 10; $page = $request->get("page", 1); $criteria = $this->getCriteria($request); try { list($total, $mediaPackages) = $opencastClient->getMediaPackages(isset($criteria["name"]) ? $criteria["name"]->regex : "", $limit, ($page - 1) * $limit); } catch (\Exception $e) { return new Response($this->render('PumukitOpencastBundle:MediaPackage:error.html.twig', array('message' => $e->getMessage())), 400); } $currentPageOpencastIds = array(); foreach ($mediaPackages as $mediaPackage) { $currentPageOpencastIds[] = $mediaPackage["id"]; } $adapter = new FixedAdapter($total, $mediaPackages); $pagerfanta = new Pagerfanta($adapter); $pagerfanta->setMaxPerPage($limit); $pagerfanta->setCurrentPage($page); $repo = $repository_multimediaobjects->createQueryBuilder()->field("properties.opencast")->exists(true)->field("properties.opencast")->in($currentPageOpencastIds)->getQuery()->execute(); return array('mediaPackages' => $pagerfanta, 'multimediaObjects' => $repo, 'player' => $opencastClient->getPlayerUrl()); }
public function indexAction(Request $req) { $rawSpeakers = $this->app['spot']->mapper(\OpenCFP\Domain\Entity\User::class)->all()->order(['first_name' => 'ASC'])->toArray(); $airports = $this->service(AirportInformationDatabase::class); $rawSpeakers = array_map(function ($speaker) use($airports) { try { $airport = $airports->withCode($speaker['airport']); $speaker['airport'] = ['code' => $airport->code, 'name' => $airport->name, 'country' => $airport->country]; } catch (\Exception $e) { $speaker['airport'] = ['code' => null, 'name' => null, 'country' => null]; } return $speaker; }, $rawSpeakers); // Set up our page stuff $adapter = new ArrayAdapter($rawSpeakers); $pagerfanta = new Pagerfanta($adapter); $pagerfanta->setMaxPerPage(20); $pagerfanta->getNbResults(); if ($req->get('page') !== null) { $pagerfanta->setCurrentPage($req->get('page')); } // Create our default view for the navigation options $routeGenerator = function ($page) { return '/admin/speakers?page=' . $page; }; $view = new TwitterBootstrap3View(); $pagination = $view->render($pagerfanta, $routeGenerator, ['proximity' => 3]); $templateData = ['airport' => $this->app->config('application.airport'), 'arrival' => date('Y-m-d', $this->app->config('application.arrival')), 'departure' => date('Y-m-d', $this->app->config('application.departure')), 'pagination' => $pagination, 'speakers' => $pagerfanta, 'page' => $pagerfanta->getCurrentPage()]; return $this->render('admin/speaker/index.twig', $templateData); }
/** * Renders the tag. * * @param \Netgen\TagsBundle\API\Repository\Values\Tags\Tag $tag * @param \Symfony\Component\HttpFoundation\Request $request * * @return \Symfony\Component\HttpFoundation\Response */ protected function renderTag(Tag $tag, Request $request) { $configResolver = $this->getConfigResolver(); if ($this->adapter instanceof TagAdapterInterface) { $this->adapter->setTag($tag); } $pager = new Pagerfanta($this->adapter); $pager->setMaxPerPage($configResolver->getParameter('tag_view.related_content_list.limit', 'eztags')); $pager->setCurrentPage($request->get('page', 1)); $response = new Response(); $response->headers->set('X-Tag-Id', $tag->id); if ($configResolver->getParameter('tag_view.cache', 'eztags') === true) { $response->setPublic(); if ($configResolver->getParameter('tag_view.ttl_cache', 'eztags') === true) { $response->setSharedMaxAge($configResolver->getParameter('tag_view.default_ttl', 'eztags')); } // Make the response vary against X-User-Hash header ensures that an HTTP // reverse proxy caches the different possible variations of the // response as it can depend on user role for instance. if ($request->headers->has('X-User-Hash')) { $response->setVary('X-User-Hash'); } $response->setLastModified($tag->modificationDate); } return $this->render($configResolver->getParameter('tag_view.template', 'eztags'), array('tag' => $tag, 'pager' => $pager), $response); }
/** * @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; }
public function indexAction(Request $request, $page) { $querystring = $request->query->get('query'); $finder = $this->get('fos_elastica.finder.videocollection'); $language = $this->get('bestophe_video_collection.movieManager')->getLanguage(); $query = $this->getElasticaResults($querystring, $language); $results = $finder->find($query); $totalHits = count($results); $adapter = new ArrayAdapter($results); $pager = new Pagerfanta($adapter); $maxPerPage = $this->getPagerFantaMaxPerPage(); $pager->setMaxPerPage($maxPerPage); $pager->setCurrentPage($page); // if ($querystring != null && $querystring != '') { // $query = new \Elastica\Query\Match(); // $query->setFieldQuery('title_fr', $querystring); // // $query->setFieldFuzziness('title_fr', 0.7); // // $query->setFieldMinimumShouldMatch('title_fr', '80%'); // // // } else { // $query = new \Elastica\Query\MatchAll(); // } // // $results = $finder->find($query); // // $totalHits = count($results); return $this->render('bestopheVideoCollectionBundle:MovieSection:SearchView.html.twig', array('listMovies' => $pager->getCurrentPageResults(), 'pager' => $pager, 'query' => $querystring, 'totalHits' => $totalHits)); }
/** * Initializes the pager for a query. * * @param \Doctrine\ORM\QueryBuilder $query Query for packages * @param int $page Pagenumber to retrieve. * @return \Pagerfanta\Pagerfanta */ protected function setupPager($query, $page) { $paginator = new Pagerfanta(new DoctrineORMAdapter($query, true)); $paginator->setMaxPerPage(15); $paginator->setCurrentPage($page, false, true); return $paginator; }
/** * Displays the list of article. * * @param \Symfony\Component\HttpFoundation\Request $request request object * @param \eZ\Publish\Core\MVC\Symfony\View\ContentView $view * * @return \Symfony\Component\HttpFoundation\Response $location is flagged as invisible */ public function showFolderListAction(Request $request, ContentView $view) { $languages = $this->getConfigResolver()->getParameter('languages'); // Using the criteria helper (a demobundle custom service) to generate our query's criteria. // This is a good practice in order to have less code in your controller. $criteria = $this->get('ezdemo.criteria_helper')->generateListFolderCriterion($view->getLocation(), $this->container->getParameter('ezdemo.folder.folder_view.excluded_content_types'), $languages); // Generating query $query = new LocationQuery(); $query->query = $criteria; $query->sortClauses = array(new SortClause\DatePublished()); // Initialize pagination. $pager = new Pagerfanta(new ContentSearchAdapter($query, $this->getRepository()->getSearchService())); $pager->setMaxPerPage($this->container->getParameter('ezdemo.folder.folder_list.limit')); $pager->setCurrentPage($request->get('page', 1)); $includedContentTypeIdentifiers = $this->container->getParameter('ezdemo.folder.folder_tree.included_content_types'); // Get sub folder structure $subContentCriteria = $this->get('ezdemo.criteria_helper')->generateSubContentCriterion($view->getLocation(), $includedContentTypeIdentifiers, $languages); $subContentQuery = new LocationQuery(); $subContentQuery->query = $subContentCriteria; $subContentQuery->sortClauses = array(new SortClause\ContentName()); $searchService = $this->getRepository()->getSearchService(); $subContent = $searchService->findLocations($subContentQuery); $treeItems = array(); foreach ($subContent->searchHits as $hit) { $treeItems[] = $hit->valueObject; } $view->addParameters(['pagerFolder' => $pager, 'treeItems' => $treeItems]); return $view; }
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; }
public function listReviewsAction($locationId, $viewType, Request $request, $layout = false, array $params = []) { $pager = new Pagerfanta(new LocationSearchAdapter($this->get('metalfrance.repository.review')->getReviewListQuery($locationId, $request->query->get('type') === 'decouvertes'), $this->getRepository()->getSearchService())); $pager->setMaxPerPage($this->getConfigResolver()->getParameter('review.list_limit', 'metalfrance')); $pager->setCurrentPage($request->query->get('page', 1)); return $this->get('ez_content')->viewLocation($locationId, $viewType, $layout, ['reviews' => $pager] + $params); }
public function index(Request $request, Application $app, $page) { $company = $app['orm.em']->getRepository('Orcamentos\\Model\\Company')->find($app['session']->get("companyId")); $clientObjs = $company->getClientCollection(); $clients = array(); foreach ($clientObjs as $i => $client) { $clients[$i]['id'] = $client->getId(); $clients[$i]['name'] = $client->getName(); $clients[$i]['logotype'] = $client->getLogotype(); $projectCollection = $client->getProjectCollection(); $clients[$i]['numProjects'] = count($projectCollection); $clients[$i]['numQuotes'] = 0; foreach ($projectCollection as $project) { $clients[$i]['numQuotes'] += count($project->getQuoteCollection()); } } $adapter = new ArrayAdapter($clients); $pagerfanta = new Pagerfanta($adapter); $pagerfanta->setMaxPerPage(9); $pagerfanta->setCurrentPage($page); $view = new TwitterBootstrap3View(); $routeGenerator = function ($page) use($app) { return '/client/' . $page; }; $htmlPagination = $view->render($pagerfanta, $routeGenerator, array()); return $app['twig']->render('client/index.twig', array('htmlPagination' => $htmlPagination, 'pagerfanta' => $pagerfanta, 'active_page' => 'client')); }
private function createPager($objects, $page, $limit = 5) { $adapter = new DoctrineODMMongoDBAdapter($objects); $pagerfanta = new Pagerfanta($adapter); $pagerfanta->setMaxPerPage($limit)->setNormalizeOutOfRangePages(true)->setCurrentPage($page); return $pagerfanta; }
/** * Lists all Test entities. * * @Route("/", name="test") * @Template() */ public function indexAction() { $request = $this->getRequest(); $em = $this->getDoctrine()->getEntityManager(); $page = $request->query->get('page'); if (!$page) { $page = 1; } $query = $em->createQueryBuilder(); $query->add('select', 't')->add('from', 'ApplicationTestBundle:Test t')->add('orderBy', 't.featured DESC, t.position ASC, t.id DESC'); $adapter = new DoctrineORMAdapter($query); $pagerfanta = new Pagerfanta($adapter); $pagerfanta->setMaxPerPage(10); // 10 by default $maxPerPage = $pagerfanta->getMaxPerPage(); $pagerfanta->setCurrentPage($page); // 1 by default $entities = $pagerfanta->getCurrentPageResults(); $routeGenerator = function ($page) { $url = '?page=' . $page; return $url; }; $view = new DefaultView(); $html = $view->render($pagerfanta, $routeGenerator); //$twig = $this->container->get('twig'); //$twig->addExtension(new \Twig_Extensions_Extension_Text); return array('pager' => $html, 'entities' => $entities); }
/** * @param LocationQuery $query * @param SearchService $searchService * @param ContentDecoratorFactory $contentDecoratorFactory * @param $maxPerPage * @param int $currentPage * @return Pagerfanta */ public static function buildPager(LocationQuery $query, SearchService $searchService, ContentDecoratorFactory $contentDecoratorFactory, $maxPerPage, $currentPage = 1) { $pager = new Pagerfanta(new static($query, $searchService, $contentDecoratorFactory)); $pager->setMaxPerPage($maxPerPage); $pager->setCurrentPage($currentPage); return $pager; }
/** * 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; }
/** * Displays the list of blog_post * Note: This is a fully customized controller action, it will generate the response and call * the view. Since it is not calling the ViewControler we don't need to match a specific * method signature. * * @param \eZ\Publish\API\Repository\Values\Content\Location $location containing blog posts * @return \Symfony\Component\HttpFoundation\Response */ public function listBlogPostsAction(Location $location, Request $request) { $response = new Response(); // Setting default cache configuration (you can override it in you siteaccess config) $response->setSharedMaxAge($this->getConfigResolver()->getParameter('content.default_ttl')); // Make the response location cache aware for the reverse proxy $response->headers->set('X-Location-Id', $location->id); $response->setVary('X-User-Hash'); $viewParameters = $request->attributes->get('viewParameters'); // Getting location and content from ezpublish dedicated services $repository = $this->getRepository(); if ($location->invisible) { throw new NotFoundHttpException("Location #{$location->id} cannot be displayed as it is flagged as invisible."); } $content = $repository->getContentService()->loadContentByContentInfo($location->getContentInfo()); // Getting language for the current siteaccess $languages = $this->getConfigResolver()->getParameter('languages'); // Using the criteria helper (a demobundle custom service) to generate our query's criteria. // This is a good practice in order to have less code in your controller. $criteria = $this->get('ezdemo.criteria_helper')->generateListBlogPostCriterion($location, $viewParameters, $languages); // Generating query $query = new Query(); $query->query = $criteria; $query->sortClauses = array(new SortClause\Field('blog_post', 'publication_date', Query::SORT_DESC, $languages[0])); // Initialize pagination. $pager = new Pagerfanta(new ContentSearchAdapter($query, $this->getRepository()->getSearchService())); $pager->setMaxPerPage($this->container->getParameter('ezdemo.blog.blog_post_list.limit')); $pager->setCurrentPage($request->get('page', 1)); return $this->render('eZDemoBundle:full:blog.html.twig', array('location' => $location, 'content' => $content, 'pagerBlog' => $pager), $response); }
/** * 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); }
/** * Lists all ArchivedClock entities within the requested week * * @param integer $year Year in YYYY format * @param integer $month Month in MM format * @param integer $day Day in DD format * * @return Symfony\Component\HttpFoundation\Response */ public function viewAction($year, $month, $day) { if (false === $this->get('security.context')->isGranted('ROLE_ADMIN')) { throw new AccessDeniedException(); } $em = $this->getDoctrine()->getManager(); $week = new \DateTime(); $week->setDate($year, $month, $day); $week->setTime(0, 0, 0); // Midnight $week = $this->container->get('dt_utils')->getFirstDayOfWeek($week); $archivedClocksQB = $em->createQueryBuilder()->select('ac')->from('OpenSkedgeBundle:ArchivedClock', 'ac')->where('ac.week = :week')->setParameter('week', $week); $page = $this->container->get('request')->query->get('page', 1); $limit = $this->container->get('request')->query->get('limit', 15); $adapter = new DoctrineORMAdapter($archivedClocksQB); $paginator = new Pagerfanta($adapter); try { $paginator->setMaxPerPage($limit); $paginator->setCurrentPage($page); $entities = $paginator->getCurrentPageResults(); } catch (NotValidMaxPerPageException $e) { throw new HttpException(400, 'Not a valid limit', $e, array(), $e->getCode()); } catch (NotValidCurrentPageException $e) { throw $this->createNotFoundException('Page does not exist.'); } return $this->render('OpenSkedgeBundle:HoursReport:view.html.twig', array('week' => $week, 'entities' => $entities, 'paginator' => $paginator)); }