]> BookStack Code Mirror - bookstack/blobdiff - app/Api/ListingResponseBuilder.php
ZIP Imports: Added API examples, finished testing
[bookstack] / app / Api / ListingResponseBuilder.php
index 02b3f680cf0a3bc1f362313468dfad88ff7401a0..44117bad9759e5108502485003c66fd3a599e96f 100644 (file)
@@ -4,15 +4,29 @@ namespace BookStack\Api;
 
 use Illuminate\Database\Eloquent\Builder;
 use Illuminate\Database\Eloquent\Collection;
+use Illuminate\Database\Eloquent\Model;
+use Illuminate\Http\JsonResponse;
 use Illuminate\Http\Request;
 
 class ListingResponseBuilder
 {
-    protected $query;
-    protected $request;
-    protected $fields;
+    protected Builder $query;
+    protected Request $request;
 
-    protected $filterOperators = [
+    /**
+     * @var string[]
+     */
+    protected array $fields;
+
+    /**
+     * @var array<callable>
+     */
+    protected array $resultModifiers = [];
+
+    /**
+     * @var array<string, string>
+     */
+    protected array $filterOperators = [
         'eq'   => '=',
         'ne'   => '!=',
         'gt'   => '>',
@@ -24,6 +38,7 @@ class ListingResponseBuilder
 
     /**
      * ListingResponseBuilder constructor.
+     * The given fields will be forced visible within the model results.
      */
     public function __construct(Builder $query, Request $request, array $fields)
     {
@@ -35,12 +50,16 @@ class ListingResponseBuilder
     /**
      * Get the response from this builder.
      */
-    public function toResponse()
+    public function toResponse(): JsonResponse
     {
         $filteredQuery = $this->filterQuery($this->query);
 
         $total = $filteredQuery->count();
-        $data = $this->fetchData($filteredQuery);
+        $data = $this->fetchData($filteredQuery)->each(function ($model) {
+            foreach ($this->resultModifiers as $modifier) {
+                $modifier($model);
+            }
+        });
 
         return response()->json([
             'data'  => $data,
@@ -49,7 +68,17 @@ class ListingResponseBuilder
     }
 
     /**
-     * Fetch the data to return in the response.
+     * Add a callback to modify each element of the results.
+     *
+     * @param (callable(Model): void) $modifier
+     */
+    public function modifyResults(callable $modifier): void
+    {
+        $this->resultModifiers[] = $modifier;
+    }
+
+    /**
+     * Fetch the data to return within the response.
      */
     protected function fetchData(Builder $query): Collection
     {