X-Git-Url: http://source.bookstackapp.com/bookstack/blobdiff_plain/1c43602f4bed60a84f47735ca8bc4a399018e013..refs/pull/5721/head:/app/Api/ListingResponseBuilder.php diff --git a/app/Api/ListingResponseBuilder.php b/app/Api/ListingResponseBuilder.php index 02b3f680c..44117bad9 100644 --- a/app/Api/ListingResponseBuilder.php +++ b/app/Api/ListingResponseBuilder.php @@ -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 + */ + protected array $resultModifiers = []; + + /** + * @var array + */ + 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 {