X-Git-Url: http://source.bookstackapp.com/bookstack/blobdiff_plain/1c43602f4bed60a84f47735ca8bc4a399018e013..refs/pull/3391/head:/app/Api/ListingResponseBuilder.php diff --git a/app/Api/ListingResponseBuilder.php b/app/Api/ListingResponseBuilder.php index 02b3f680c..7de5ddf07 100644 --- a/app/Api/ListingResponseBuilder.php +++ b/app/Api/ListingResponseBuilder.php @@ -2,8 +2,10 @@ namespace BookStack\Api; +use BookStack\Model; use Illuminate\Database\Eloquent\Builder; use Illuminate\Database\Eloquent\Collection; +use Illuminate\Http\JsonResponse; use Illuminate\Http\Request; class ListingResponseBuilder @@ -12,6 +14,11 @@ class ListingResponseBuilder protected $request; protected $fields; + /** + * @var array + */ + protected $resultModifiers = []; + protected $filterOperators = [ 'eq' => '=', 'ne' => '!=', @@ -24,6 +31,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 +43,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 +61,17 @@ class ListingResponseBuilder } /** - * Fetch the data to return in the response. + * Add a callback to modify each element of the results. + * + * @param (callable(Model)) $modifier + */ + public function modifyResults($modifier): void + { + $this->resultModifiers[] = $modifier; + } + + /** + * Fetch the data to return within the response. */ protected function fetchData(Builder $query): Collection {