]> BookStack Code Mirror - bookstack/blobdiff - app/Http/Controllers/Api/SearchApiController.php
Added content-perms API examples and docs tweaks
[bookstack] / app / Http / Controllers / Api / SearchApiController.php
index 8fb2496657588a09116037edcbcf594744a1abf9..bf59ec67162f1a264c59a734ba9c33634f5d15bf 100644 (file)
@@ -2,26 +2,30 @@
 
 namespace BookStack\Http\Controllers\Api;
 
+use BookStack\Api\ApiEntityListFormatter;
 use BookStack\Entities\Models\Entity;
-use BookStack\Entities\Tools\SearchOptions;
-use BookStack\Entities\Tools\SearchRunner;
+use BookStack\Search\SearchOptions;
+use BookStack\Search\SearchResultsFormatter;
+use BookStack\Search\SearchRunner;
 use Illuminate\Http\Request;
 
 class SearchApiController extends ApiController
 {
-    protected $searchRunner;
+    protected SearchRunner $searchRunner;
+    protected SearchResultsFormatter $resultsFormatter;
 
     protected $rules = [
         'all' => [
-            'query' => ['required'],
-            'page'  => ['integer', 'min:1'],
+            'query'  => ['required'],
+            'page'   => ['integer', 'min:1'],
             'count'  => ['integer', 'min:1', 'max:100'],
         ],
     ];
 
-    public function __construct(SearchRunner $searchRunner)
+    public function __construct(SearchRunner $searchRunner, SearchResultsFormatter $resultsFormatter)
     {
         $this->searchRunner = $searchRunner;
+        $this->resultsFormatter = $resultsFormatter;
     }
 
     /**
@@ -45,23 +49,20 @@ class SearchApiController extends ApiController
         $count = min(intval($request->get('count', '0')) ?: 20, 100);
 
         $results = $this->searchRunner->searchEntities($options, 'all', $page, $count);
+        $this->resultsFormatter->format($results['results']->all(), $options);
 
-        /** @var Entity $result */
-        foreach ($results['results'] as $result) {
-            $result->setVisible([
-                'id', 'name', 'slug', 'book_id',
-                'chapter_id', 'draft', 'template',
-                'created_at', 'updated_at',
-                'tags', 'type',
-            ]);
-            $result->setAttribute('type', $result->getType());
-        }
+        $data = (new ApiEntityListFormatter($results['results']->all()))
+            ->withType()->withTags()
+            ->withField('preview_html', function (Entity $entity) {
+                return [
+                    'name'    => (string) $entity->getAttribute('preview_name'),
+                    'content' => (string) $entity->getAttribute('preview_content'),
+                ];
+            })->format();
 
         return response()->json([
-            'data' => $results['results'],
+            'data'  => $data,
             'total' => $results['total'],
         ]);
     }
-
-
 }