]> git.immae.eu Git - github/wallabag/wallabag.git/blobdiff - src/Wallabag/ApiBundle/Controller/SearchRestController.php
Merge pull request #3627 from craig0990/feature/add-search-api-endpoint
[github/wallabag/wallabag.git] / src / Wallabag / ApiBundle / Controller / SearchRestController.php
diff --git a/src/Wallabag/ApiBundle/Controller/SearchRestController.php b/src/Wallabag/ApiBundle/Controller/SearchRestController.php
new file mode 100644 (file)
index 0000000..d9f9984
--- /dev/null
@@ -0,0 +1,65 @@
+<?php
+
+namespace Wallabag\ApiBundle\Controller;
+
+use Hateoas\Configuration\Route;
+use Hateoas\Representation\Factory\PagerfantaFactory;
+use Nelmio\ApiDocBundle\Annotation\ApiDoc;
+use Pagerfanta\Adapter\DoctrineORMAdapter;
+use Pagerfanta\Pagerfanta;
+use Symfony\Component\HttpFoundation\JsonResponse;
+use Symfony\Component\HttpFoundation\Request;
+
+class SearchRestController extends WallabagRestController
+{
+    /**
+     * Search all entries by term.
+     *
+     * @ApiDoc(
+     *       parameters={
+     *          {"name"="term", "dataType"="string", "required"=false, "format"="any", "description"="Any query term"},
+     *          {"name"="page", "dataType"="integer", "required"=false, "format"="default '1'", "description"="what page you want."},
+     *          {"name"="perPage", "dataType"="integer", "required"=false, "format"="default'30'", "description"="results per page."}
+     *       }
+     * )
+     *
+     * @return JsonResponse
+     */
+    public function getSearchAction(Request $request)
+    {
+        $this->validateAuthentication();
+
+        $term = $request->query->get('term');
+        $page = (int) $request->query->get('page', 1);
+        $perPage = (int) $request->query->get('perPage', 30);
+
+        $qb = $this->get('wallabag_core.entry_repository')
+            ->getBuilderForSearchByUser(
+                $this->getUser()->getId(),
+                $term,
+                null
+            );
+
+        $pagerAdapter = new DoctrineORMAdapter($qb->getQuery(), true, false);
+        $pager = new Pagerfanta($pagerAdapter);
+
+        $pager->setMaxPerPage($perPage);
+        $pager->setCurrentPage($page);
+
+        $pagerfantaFactory = new PagerfantaFactory('page', 'perPage');
+        $paginatedCollection = $pagerfantaFactory->createRepresentation(
+            $pager,
+            new Route(
+                'api_get_search',
+                [
+                    'term' => $term,
+                    'page' => $page,
+                    'perPage' => $perPage,
+                ],
+                true
+            )
+        );
+
+        return $this->sendResponse($paginatedCollection);
+    }
+}