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)); }
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); } } }
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; }
public function createRepresentationFromPagerfanta(Pagerfanta $pager) { $this->pager = empty($pager) ? $this->pager : $pager; if (empty($this->pager)) { return array(); } $representation = array('hasToPaginate' => $this->pager->haveToPaginate(), 'hasNextPage' => $this->pager->hasNextPage(), 'hasPreviousPage' => $this->pager->hasPreviousPage(), 'totalItems' => $this->pager->getNbResults(), 'itemsPerPage' => $this->pager->getMaxPerPage(), 'currentPage' => $this->pager->getCurrentPage(), 'data' => $this->pager->getCurrentPageResults()); return $representation; }
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; }
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.'); } }
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); }
/** * @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()); }
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(); }
/** * Return pagers * * @return array */ public function getPager() { // view if (!$this->pagerfanta) { return []; } $pager = ['maxPerPage' => $this->maxPerPage, 'current' => $this->currentPage, 'total' => $this->pagerfanta->getNbResults(), 'hasNext' => $this->pagerfanta->hasNextPage(), 'hasPrevious' => $this->pagerfanta->hasPreviousPage(), 'html' => $this->getHtml($this->pagerfanta)]; return $pager; }
/** * @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()); }
public function AllMoviesAction($page) { $maxActors = $this->getPosterViewMaxActors(); $userListMovies = $this->get('bestophe_video_collection.movieUserManager')->getAllMovieUserList(); $adapter = new ArrayAdapter($userListMovies); $pager = new Pagerfanta($adapter); $maxPerPage = $this->getPagerFantaMaxPerPage(); $pager->setMaxPerPage($maxPerPage); $pager->setCurrentPage($page); $userListMovieCount = $pager->getNbResults(); return $this->render('bestopheVideoCollectionBundle:MovieSection:MovieList/MoviePosterViewFanta.html.twig', array('listMovies' => $pager->getCurrentPageResults(), 'pager' => $pager, 'nbActors' => $maxActors, 'totalMovies' => $userListMovieCount)); }
public function indexAction() { $contentService = $this->getRepository()->getContentService(); $content = $contentService->loadContent(74); $location = $this->getRepository()->getLocationService()->loadLocation(73); $query = new Query(); $query->criterion = new Criterion\LogicalAnd(array(new Criterion\ContentTypeIdentifier('projet'))); $query->sortClauses = array(new SortClause\Field('projet', 'annee', Query::SORT_DESC, 'fre-FR'), new SortClause\Field('projet', 'mois', Query::SORT_DESC, 'fre-FR')); $pager = new Pagerfanta(new ContentSearchAdapter($query, $this->getRepository()->getSearchService())); $pager->setMaxPerPage(12); $pager->setCurrentPage($this->getRequest()->get('page', 1)); $contentTypeService = $this->getRepository()->getContentTypeService(); $contentType = $contentTypeService->loadContentTypeByIdentifier('projet'); $categories = $contentType->getFieldDefinition('categorie')->fieldSettings['options']; return $this->render('SibilleEcommerceBundle:full:portfolio.html.twig', array('content' => $content, 'location' => $location, 'total' => $pager->getNbResults(), 'projets' => $pager, 'categories' => $categories)); }
/** * @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; }
private function indexAction(Request $req) { $rawSpeakers = $this->app['spot']->mapper('OpenCFP\\Domain\\Entity\\User')->all()->order(['first_name' => 'ASC'])->toArray(); // 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); }
protected function addPagination(Request $request, Pagerfanta $pager, $resource) { $route = $request->attributes->get('_route'); $params = $request->attributes->get('_route_params'); $params = array_merge($params, $request->query->all()); $resource->setMetaValue('page', $pager->getCurrentPage()); $resource->setMetaValue('count', $pager->getNbResults()); $resource->setMetaValue('nextPage', null); $resource->setMetaValue('previousPage', null); $resource->setMetaValue('next', null); $resource->setMetaValue('previous', null); if ($pager->hasNextPage()) { $resource->setMetaValue('next', $this->generateUrl($route, array_replace($params, ['page' => $pager->getNextPage(), 'limit' => $pager->getMaxPerPage()]), true)); $resource->setMetaValue('nextPage', $pager->getNextPage()); } if ($pager->hasPreviousPage()) { $resource->setMetaValue('previous', $this->generateUrl($route, array_replace($params, ['page' => $pager->getPreviousPage(), 'limit' => $pager->getMaxPerPage()]), true)); $resource->setMetaValue('previousPage', $pager->getPreviousPage()); } }
public function indexAction($categorie = 'toutes') { $contentService = $this->getRepository()->getContentService(); $content = $contentService->loadContent(61); $location = $this->getRepository()->getLocationService()->loadLocation(62); // récupération des catégories du blog $contentTypeService = $this->getRepository()->getContentTypeService(); $contentType = $contentTypeService->loadContentTypeByIdentifier('article'); $options = $contentType->getFieldDefinition('categorie_article')->fieldSettings['options']; // recherche de tous les posts $query = new Query(); if ($categorie == 'toutes') { $query->criterion = new Criterion\LogicalAnd(array(new Criterion\ContentTypeIdentifier('article'))); } else { $query->criterion = new Criterion\LogicalAnd(array(new Criterion\ContentTypeIdentifier('article'), new Criterion\Field('categorie_article', Criterion\Operator::CONTAINS, $categorie))); } $query->sortClauses = array(new SortClause\Field('article', 'publish_date', Query::SORT_DESC, 'fre-FR')); $pager = new Pagerfanta(new ContentSearchAdapter($query, $this->getRepository()->getSearchService())); $pager->setMaxPerPage(5); $pager->setCurrentPage($this->getRequest()->get('page', 1)); return $this->render('SibilleEcommerceBundle:full:blog.html.twig', array('content' => $content, 'location' => $location, 'total' => $pager->getNbResults(), 'articles' => $pager, 'categories' => $options)); }
/** * @Route( * "/project/{project}/collection/{collection}/{module}/taxo_view_gallery/{taxon}", * defaults={"page"=1}, * name="front_module_taxo_view_gallery" * ) * @Route( * "/project/{project}/collection/{collection}/{module}/taxo_view_gallery/{taxon}/page{page}", * requirements={"page"="\d+"}, * name="front_module_taxo_view_gallery_paginated" * ) * @Method("get") * @Template() */ public function module_taxo_view_galleryAction($project, $collection, $module, $taxon, $page, Request $request) { ControllerHelp::check_enable_project($project, $this->get_prefix(), $this); $form_page = $request->query->get('form_page'); if (!empty($form_page)) { $page = $form_page; } if ($this->container->get('request')->get('_route') == 'front_module_taxo_view_gallery_paginated' && $page == 1) { return $this->redirect($this->generateUrl('front_module_taxo_view_gallery', array('project' => $project, 'collection' => $collection, 'module' => $module, 'taxon' => $taxon)), 301); } // $translations = ControllerHelp::make_translations($project, 'front_module_taxo', array('project' => $project, 'collection' => $collection, 'module' => $module), $this, $this->container->getParameter('mdb_base')); // $dm = $this->get('doctrine.odm.mongodb.document_manager'); $dm->getConfiguration()->setDefaultDB($this->get_prefix() . $project); $collection = $dm->getRepository('PlantnetDataBundle:Collection')->findOneBy(array('url' => $collection)); if (!$collection) { throw $this->createNotFoundException('Unable to find Collection entity.'); } $module = $dm->getRepository('PlantnetDataBundle:Module')->findOneBy(array('url' => $module, 'collection.id' => $collection->getId())); if (!$module || $module->getType() != 'text' || $module->getWsonly() == true) { throw $this->createNotFoundException('Unable to find Module entity.'); } $taxon = $dm->createQueryBuilder('PlantnetDataBundle:Taxon')->field('module')->references($module)->field('identifier')->equals($taxon)->getQuery()->getSingleResult(); if (!$taxon) { throw $this->createNotFoundException('Unable to find Taxon entity.'); } $display = array(); $field = $module->getProperties(); foreach ($field as $row) { if ($row->getMain() == true) { $display[] = $row->getId(); } } $tab_ref = array($taxon->getId() => $taxon); $syns = $taxon->getSynonyms(); if (count($syns)) { foreach ($syns as $syn) { $tab_ref[$syn->getId()] = $syn; } } /* $children=$taxon->getChildren(); while(count($children)){ $children_new=array(); foreach($children as $child){ $tab_ref[$child->getId()]=$child; $syns=$child->getSynonyms(); if(count($syns)){ foreach($syns as $syn){ $tab_ref[$syn->getId()]=$syn; } } $tmp_children=$child->getChildren(); if(count($tmp_children)){ foreach($tmp_children as $new_child){ $children_new[$new_child->getId()]=$new_child; } } } $children=$children_new; } */ $plantunits = $dm->createQueryBuilder('PlantnetDataBundle:Plantunit'); $plantunits->field('module')->references($module); $plantunits->hydrate(false); $plantunits->select('_id'); if (count($tab_ref) > 1) { foreach ($tab_ref as $ref) { $plantunits->addOr($plantunits->expr()->field('taxonsrefs')->references($ref)); } } else { $plantunits->field('taxonsrefs')->references($tab_ref[key($tab_ref)]); } $plantunits = $plantunits->getQuery()->execute(); $pu_ids = array(); foreach ($plantunits as $id) { $pu_ids[] = $id['_id']; } $images = $dm->createQueryBuilder('PlantnetDataBundle:Image'); $images->field('plantunit.$id')->in($pu_ids); /* $images=$dm->createQueryBuilder('PlantnetDataBundle:Image'); if(count($tab_ref)>1){ foreach($tab_ref as $ref){ $images->addOr($images->expr()->field('taxonsrefs')->references($ref)); } } else{ $images->field('taxonsrefs')->references($tab_ref[key($tab_ref)]); } */ $images->sort('title1', 'asc'); $images->sort('title2', 'asc'); $paginator = new Pagerfanta(new DoctrineODMMongoDBAdapter($images)); try { $paginator->setMaxPerPage(15); $paginator->setCurrentPage($page); } catch (\Pagerfanta\Exception\NotValidCurrentPageException $e) { throw $this->createNotFoundException('Page not found.'); } //count to display $nb_images = 1; $nb_locations = $taxon->getHaslocations() ? 1 : 0; $config = ControllerHelp::get_config($project, $dm, $this); $tpl = $config->getTemplate(); return $this->render('PlantnetDataBundle:' . ($tpl ? $tpl : 'Frontend') . '\\Module:taxo_view.html.twig', array('config' => $config, 'project' => $project, 'collection' => $collection, 'module_parent' => $module, 'module' => $module, 'taxon' => $taxon, 'paginator' => $paginator, 'nbResults' => $paginator->getNbResults(), 'nb_images' => $nb_images, 'nb_locations' => $nb_locations, 'display' => $display, 'page' => $page, 'translations' => $translations, 'current' => 'collection', 'current_display' => 'images', 'selected' => 'taxo' . $collection->getId() . $module->getId())); }
require 'db_config.php'; require 'models/franchises.php'; require 'models/games.php'; require 'models/rotations.php'; require 'RotationAdapter.php'; $franchiseModel = new Franchise($db); $rotationModel = new Rotation($db); $games = new Game($db); $current_week = filter_input(INPUT_GET, 'week', FILTER_SANITIZE_NUMBER_INT); $max_week = $games->getMaxWeek(); if ($current_week == 0) { $current_week = $max_week; } $franchises = $franchiseModel->getAll(); $rotations = $rotationModel->getAll(); /** * We need to add an empty set of rotations to our existing list for the week * after the most current ones we have */ $rotation_max_week = $rotationModel->getMaxWeek(); $rotations = array_merge($rotations, $rotationModel->addWeek($rotation_max_week + 1, $franchises)); // load all rotations into the pager $adapter = new RotationAdapter($rotations, $franchises); $adapter->processByWeek(); $pagerfanta = new Pagerfanta($adapter); $pagerfanta->setMaxPerPage(24); $pagerfanta->setCurrentPage($current_week); $nb_results = $pagerfanta->getNbResults(); $current_page_results = $pagerfanta->getCurrentPageResults(); // display form with data require 'templates/rotations/index.php';
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()))); }
/** * @param integer $page * @param integer $limit * * @return Pagerfanta */ private function paginateExistingBundles($page, $limit = 100) { $pager = new Pagerfanta(new DoctrineORMAdapter($this->em->getRepository('KnpBundlesBundle:Bundle')->queryAllSortedBy('updatedAt'), false)); $pager->setMaxPerPage($limit)->setCurrentPage($page, false, true); if (1 === $page) { $this->output->writeln(sprintf('[%s] Loaded <comment>%d</comment> bundles from the DB', date('d-m-y H:i:s'), $pager->getNbResults())); } return $pager; }
/** * @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; }
/** * Constructor * * @param \Doctrine\DBAL\Driver\Connection $db * @param \Pagerfanta\Pagerfanta $pagerfanta */ public function __construct(DriverConnection $db, Pagerfanta $pagerfanta) { $this->db = $db; $currentPage = $this->currentPage ?: (isset($_GET[$this->pageKey]) ? $_GET[$this->pageKey] : 1); $this->firstResult = ($currentPage - 1) * $this->maxPerPage; $pagerfanta->setMaxPerPage($this->maxPerPage); $pagerfanta->setCurrentPage($currentPage, false, true); //view $this->pager = ['maxPerPage' => $this->maxPerPage, 'current' => $currentPage, 'total' => $pagerfanta->getNbResults(), 'hasNext' => $pagerfanta->hasNextPage(), 'hasPrevious' => $pagerfanta->hasPreviousPage(), 'html' => $this->getHtml($pagerfanta)]; }
/** * 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; }
public function serializeToArray(GenericSerializationVisitor $visitor, Pagerfanta $pager, array $type, Context $context) { $resultsType = array('name' => 'array'); if (isset($type['params'])) { $resultsType['params'] = $type['params']; } $shouldSetRoot = null === $visitor->getRoot(); $data = array('page' => $pager->getCurrentPage(), 'limit' => $pager->getMaxPerPage(), 'total' => $pager->getNbResults(), 'results' => $visitor->getNavigator()->accept($pager->getCurrentPageResults(), $resultsType, $context)); if (null !== ($links = $this->linkEventSubscriber->getOnPostSerializeData(new ObjectEvent($context, $pager, $type)))) { $data[$this->linksJsonKey] = $links; } if (null !== ($relations = $this->embedderEventSubscriber->getOnPostSerializeData(new ObjectEvent($context, $pager, $type)))) { $data[$this->relationsJsonKey] = $relations; } if ($shouldSetRoot) { $visitor->setRoot($data); } return $data; }
/** * @Route("/search/", name="search.ajax") * @Route("/search.{_format}", requirements={"_format"="(html|json)"}, name="search", defaults={"_format"="html"}) * @Method({"GET"}) */ public function searchAction(Request $req) { $form = $this->createForm(SearchQueryType::class, new SearchQuery()); $filteredOrderBys = $this->getFilteredOrderedBys($req); $normalizedOrderBys = $this->getNormalizedOrderBys($filteredOrderBys); $this->computeSearchQuery($req, $filteredOrderBys); $typeFilter = str_replace('%type%', '', $req->query->get('type')); $tagsFilter = $req->query->get('tags'); if ($req->query->has('search_query') || $typeFilter || $tagsFilter) { /** @var $solarium \Solarium_Client */ $solarium = $this->get('solarium.client'); $select = $solarium->createSelect(); // configure dismax $dismax = $select->getDisMax(); $dismax->setQueryFields(array('name^4', 'package_name^4', 'description', 'tags', 'text', 'text_ngram', 'name_split^2')); $dismax->setPhraseFields(array('description')); $dismax->setBoostFunctions(array('log(trendiness)^10')); $dismax->setMinimumMatch(1); $dismax->setQueryParser('edismax'); // filter by type if ($typeFilter) { $filterQueryTerm = sprintf('type:"%s"', $select->getHelper()->escapeTerm($typeFilter)); $filterQuery = $select->createFilterQuery('type')->setQuery($filterQueryTerm); $select->addFilterQuery($filterQuery); } // filter by tags if ($tagsFilter) { $tags = array(); foreach ((array) $tagsFilter as $tag) { $tags[] = $select->getHelper()->escapeTerm($tag); } $filterQueryTerm = sprintf('tags:("%s")', implode('" AND "', $tags)); $filterQuery = $select->createFilterQuery('tags')->setQuery($filterQueryTerm); $select->addFilterQuery($filterQuery); } if (!empty($filteredOrderBys)) { $select->addSorts($normalizedOrderBys); } $form->handleRequest($req); if ($form->isValid()) { $escapedQuery = $select->getHelper()->escapeTerm($form->getData()->getQuery()); $escapedQuery = preg_replace('/(^| )\\\\-(\\S)/', '$1-$2', $escapedQuery); $escapedQuery = preg_replace('/(^| )\\\\\\+(\\S)/', '$1+$2', $escapedQuery); if (substr_count($escapedQuery, '"') % 2 == 0) { $escapedQuery = str_replace('\\"', '"', $escapedQuery); } $select->setQuery($escapedQuery); } $paginator = new Pagerfanta(new SolariumAdapter($solarium, $select)); $perPage = $req->query->getInt('per_page', 15); if ($perPage <= 0 || $perPage > 100) { if ($req->getRequestFormat() === 'json') { return JsonResponse::create(array('status' => 'error', 'message' => 'The optional packages per_page parameter must be an integer between 1 and 100 (default: 15)'), 400)->setCallback($req->query->get('callback')); } $perPage = max(0, min(100, $perPage)); } $paginator->setMaxPerPage($perPage); $paginator->setCurrentPage($req->query->get('page', 1), false, true); $metadata = array(); foreach ($paginator as $package) { if (is_numeric($package->id)) { $metadata['downloads'][$package->id] = $package->downloads; $metadata['favers'][$package->id] = $package->favers; } } if ($req->getRequestFormat() === 'json') { try { $result = array('results' => array(), 'total' => $paginator->getNbResults()); } catch (\Solarium_Client_HttpException $e) { return JsonResponse::create(array('status' => 'error', 'message' => 'Could not connect to the search server'), 500)->setCallback($req->query->get('callback')); } foreach ($paginator as $package) { if (ctype_digit((string) $package->id)) { $url = $this->generateUrl('view_package', array('name' => $package->name), UrlGeneratorInterface::ABSOLUTE_URL); } else { $url = $this->generateUrl('view_providers', array('name' => $package->name), UrlGeneratorInterface::ABSOLUTE_URL); } $row = array('name' => $package->name, 'description' => $package->description ?: '', 'url' => $url, 'repository' => $package->repository); if (is_numeric($package->id)) { $row['downloads'] = $metadata['downloads'][$package->id]; $row['favers'] = $metadata['favers'][$package->id]; } else { $row['virtual'] = true; } $result['results'][] = $row; } if ($paginator->hasNextPage()) { $params = array('_format' => 'json', 'q' => $form->getData()->getQuery(), 'page' => $paginator->getNextPage()); if ($tagsFilter) { $params['tags'] = (array) $tagsFilter; } if ($typeFilter) { $params['type'] = $typeFilter; } if ($perPage !== 15) { $params['per_page'] = $perPage; } $result['next'] = $this->generateUrl('search', $params, UrlGeneratorInterface::ABSOLUTE_URL); } return JsonResponse::create($result)->setCallback($req->query->get('callback')); } if ($req->isXmlHttpRequest()) { try { return $this->render('PackagistWebBundle:Web:search.html.twig', array('packages' => $paginator, 'meta' => $metadata, 'noLayout' => true)); } catch (\Twig_Error_Runtime $e) { if (!$e->getPrevious() instanceof \Solarium_Client_HttpException) { throw $e; } return JsonResponse::create(array('status' => 'error', 'message' => 'Could not connect to the search server'), 500)->setCallback($req->query->get('callback')); } } return $this->render('PackagistWebBundle:Web:search.html.twig', array('packages' => $paginator, 'meta' => $metadata)); } elseif ($req->getRequestFormat() === 'json') { return JsonResponse::create(array('error' => 'Missing search query, example: ?q=example'), 400)->setCallback($req->query->get('callback')); } return $this->render('PackagistWebBundle:Web:search.html.twig'); }
public function search() { //$finder = $this->container->get('fos_elastica.finder.search.articles'); $bool = new Query\Bool(); $multiMatch = new Query\MultiMatch(); $multiMatch->setFields(['subjects', 'title', 'keywords', 'subtitle', 'citations.raw', 'journal.title', 'journal.subtitle']); $multiMatch->setType('phrase_prefix'); $multiMatch->setQuery($this->getParam('term')); $bool->addMust($multiMatch); if ($this->filter) { foreach ($this->filter as $key => $filter) { $filterObj = new Query\Match(); $this->applyFilter($filterObj, $key, $filter); $bool->addMust($filterObj); } } $missing = new Filter\Missing("issue"); $not = new Filter\BoolNot($missing); $notQ = new Query\Filtered(); $notQ->setFilter($not); $bool->addMust($notQ); $query = new Query(); $query->setQuery($bool); $query->setFrom($this->getPage() * $this->getLimit()); $query->setSize($this->getLimit()); $aggregation = new Terms('journals'); $aggregation->setField('journal.id'); $aggregation->setOrder('_count', 'desc'); $qb = $this->em->createQueryBuilder(); $qb->select('count(r.id)')->from('OjsJournalBundle:Journal', 'r')->where($qb->expr()->eq('r.status', 3)); $aggregation->setSize($qb->getQuery()->getSingleScalarResult()); $query->addAggregation($aggregation); $aggregation = new Terms('authors'); $aggregation->setField('articleAuthors.author.id'); $aggregation->setOrder('_count', 'desc'); $qb = $this->em->createQueryBuilder(); $qb->select('count(r.id)')->from('OjsJournalBundle:Author', 'r'); $aggregation->setSize($qb->getQuery()->getSingleScalarResult()); $query->addAggregation($aggregation); $elasticaAdapter = new ElasticaAdapter($this->index, $query); $pagerFanta = new Pagerfanta($elasticaAdapter); $pagerFanta->setMaxPerPage($this->getLimit()); $pagerFanta->setCurrentPage($this->getPage()); /** @var ResultSet $search */ $search = $pagerFanta->getCurrentPageResults(); $result = $search->getResults(); //$search->getResults(); $this->pager = $pagerFanta; $transformer = new ElasticaToModelTransformer($this->registry, 'OjsJournalBundle:Article'); $transformer->setPropertyAccessor($this->propertyAccessor); $this->result = $transformer->transform($result); $this->setCount($pagerFanta->getNbResults()); $this->addAggregation('journal', $this->transform($search->getAggregation('journals')['buckets'], 'OjsJournalBundle:Journal')); $this->addAggregation('author', $this->transform($search->getAggregation('authors')['buckets'], 'OjsJournalBundle:Author')); return $this; }
/** * @Template() * @Route("/popular.{_format}", name="browse_popular", defaults={"_format"="html"}) * @Cache(smaxage=900) */ public function popularAction(Request $req) { try { $redis = $this->get('snc_redis.default'); $perPage = $req->query->getInt('per_page', 15); if ($perPage <= 0 || $perPage > 100) { if ($req->getRequestFormat() === 'json') { return new JsonResponse(array('status' => 'error', 'message' => 'The optional packages per_page parameter must be an integer between 1 and 100 (default: 15)'), 400); } $perPage = max(0, min(100, $perPage)); } $popularIds = $redis->zrevrange('downloads:trending', ($req->get('page', 1) - 1) * $perPage, $req->get('page', 1) * $perPage - 1); $popular = $this->getDoctrine()->getRepository('PackagistWebBundle:Package')->createQueryBuilder('p')->where('p.id IN (:ids)')->setParameter('ids', $popularIds)->getQuery()->useResultCache(true, 900)->getResult(); usort($popular, function ($a, $b) use($popularIds) { return array_search($a->getId(), $popularIds) > array_search($b->getId(), $popularIds) ? 1 : -1; }); $packages = new Pagerfanta(new FixedAdapter($redis->zcard('downloads:trending'), $popular)); $packages->setMaxPerPage($perPage); $packages->setCurrentPage($req->get('page', 1), false, true); } catch (ConnectionException $e) { $packages = new Pagerfanta(new FixedAdapter(0, array())); } $data = array('packages' => $packages); $data['meta'] = $this->getPackagesMetadata($data['packages']); if ($req->getRequestFormat() === 'json') { $result = array('packages' => array(), 'total' => $packages->getNbResults()); /** @var Package $package */ foreach ($packages as $package) { $url = $this->generateUrl('view_package', array('name' => $package->getName()), UrlGeneratorInterface::ABSOLUTE_URL); $result['packages'][] = array('name' => $package->getName(), 'description' => $package->getDescription() ?: '', 'url' => $url, 'downloads' => $data['meta']['downloads'][$package->getId()], 'favers' => $data['meta']['favers'][$package->getId()]); } if ($packages->hasNextPage()) { $params = array('_format' => 'json', 'page' => $packages->getNextPage()); if ($perPage !== 15) { $params['per_page'] = $perPage; } $result['next'] = $this->generateUrl('browse_popular', $params, UrlGeneratorInterface::ABSOLUTE_URL); } return new JsonResponse($result); } return $data; }
/** * @test */ public function it_counts_total_number_of_results() { $pagerfanta = new Pagerfanta(new PorpaginasAdapter(new ArrayResult(array(1, 2, 3, 4)))); $this->assertEquals(4, $pagerfanta->getNbResults()); }
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()]; }