]> BookStack Code Mirror - bookstack/blob - app/Search/SearchApiController.php
Cleaned up namespacing in routes
[bookstack] / app / Search / SearchApiController.php
1 <?php
2
3 namespace BookStack\Search;
4
5 use BookStack\Api\ApiEntityListFormatter;
6 use BookStack\Entities\Models\Entity;
7 use BookStack\Http\ApiController;
8 use Illuminate\Http\Request;
9
10 class SearchApiController extends ApiController
11 {
12     protected SearchRunner $searchRunner;
13     protected SearchResultsFormatter $resultsFormatter;
14
15     protected $rules = [
16         'all' => [
17             'query'  => ['required'],
18             'page'   => ['integer', 'min:1'],
19             'count'  => ['integer', 'min:1', 'max:100'],
20         ],
21     ];
22
23     public function __construct(SearchRunner $searchRunner, SearchResultsFormatter $resultsFormatter)
24     {
25         $this->searchRunner = $searchRunner;
26         $this->resultsFormatter = $resultsFormatter;
27     }
28
29     /**
30      * Run a search query against all main content types (shelves, books, chapters & pages)
31      * in the system. Takes the same input as the main search bar within the BookStack
32      * interface as a 'query' parameter. See https://www.bookstackapp.com/docs/user/searching/
33      * for a full list of search term options. Results contain a 'type' property to distinguish
34      * between: bookshelf, book, chapter & page.
35      *
36      * The paging parameters and response format emulates a standard listing endpoint
37      * but standard sorting and filtering cannot be done on this endpoint. If a count value
38      * is provided this will only be taken as a suggestion. The results in the response
39      * may currently be up to 4x this value.
40      */
41     public function all(Request $request)
42     {
43         $this->validate($request, $this->rules['all']);
44
45         $options = SearchOptions::fromString($request->get('query') ?? '');
46         $page = intval($request->get('page', '0')) ?: 1;
47         $count = min(intval($request->get('count', '0')) ?: 20, 100);
48
49         $results = $this->searchRunner->searchEntities($options, 'all', $page, $count);
50         $this->resultsFormatter->format($results['results']->all(), $options);
51
52         $data = (new ApiEntityListFormatter($results['results']->all()))
53             ->withType()->withTags()
54             ->withField('preview_html', function (Entity $entity) {
55                 return [
56                     'name'    => (string) $entity->getAttribute('preview_name'),
57                     'content' => (string) $entity->getAttribute('preview_content'),
58                 ];
59             })->format();
60
61         return response()->json([
62             'data'  => $data,
63             'total' => $results['total'],
64         ]);
65     }
66 }