]> git.immae.eu Git - github/wallabag/wallabag.git/blob - src/Wallabag/ApiBundle/Controller/SearchRestController.php
[wallabag/wallabag#2611] Fix PHPCS lint errors
[github/wallabag/wallabag.git] / src / Wallabag / ApiBundle / Controller / SearchRestController.php
1 <?php
2
3 namespace Wallabag\ApiBundle\Controller;
4
5 use Hateoas\Configuration\Route;
6 use Hateoas\Representation\Factory\PagerfantaFactory;
7 use JMS\Serializer\SerializationContext;
8 use Nelmio\ApiDocBundle\Annotation\ApiDoc;
9 use Pagerfanta\Adapter\DoctrineORMAdapter;
10 use Pagerfanta\Pagerfanta;
11 use Symfony\Component\HttpFoundation\JsonResponse;
12 use Symfony\Component\HttpFoundation\Request;
13 use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
14
15 class SearchRestController extends WallabagRestController
16 {
17 /**
18 * Search all entries by term.
19 *
20 * @ApiDoc(
21 * parameters={
22 * {"name"="term", "dataType"="string", "required"=false, "format"="any", "description"="Any query term"},
23 * {"name"="page", "dataType"="integer", "required"=false, "format"="default '1'", "description"="what page you want."},
24 * {"name"="perPage", "dataType"="integer", "required"=false, "format"="default'30'", "description"="results per page."}
25 * }
26 * )
27 *
28 * @return JsonResponse
29 */
30 public function getSearchAction(Request $request)
31 {
32 $this->validateAuthentication();
33
34 $term = $request->query->get('term');
35 $page = (int) $request->query->get('page', 1);
36 $perPage = (int) $request->query->get('perPage', 30);
37
38 $qb = $this->get('wallabag_core.entry_repository')
39 ->getBuilderForSearchByUser(
40 $this->getUser()->getId(),
41 $term,
42 null
43 );
44
45 $pagerAdapter = new DoctrineORMAdapter($qb->getQuery(), true, false);
46 $pager = new Pagerfanta($pagerAdapter);
47
48 $pager->setMaxPerPage($perPage);
49 $pager->setCurrentPage($page);
50
51 $pagerfantaFactory = new PagerfantaFactory('page', 'perPage');
52 $paginatedCollection = $pagerfantaFactory->createRepresentation(
53 $pager,
54 new Route(
55 'api_get_search',
56 [
57 'term' => $term,
58 'page' => $page,
59 'perPage' => $perPage,
60 ],
61 UrlGeneratorInterface::ABSOLUTE_URL
62 )
63 );
64
65 return $this->sendResponse($paginatedCollection);
66 }
67
68 /**
69 * Shortcut to send data serialized in json.
70 *
71 * @param mixed $data
72 *
73 * @return JsonResponse
74 */
75 private function sendResponse($data)
76 {
77 // https://github.com/schmittjoh/JMSSerializerBundle/issues/293
78 $context = new SerializationContext();
79 $context->setSerializeNull(true);
80
81 $json = $this->get('jms_serializer')->serialize($data, 'json', $context);
82
83 return (new JsonResponse())->setJson($json);
84 }
85 }