X-Git-Url: http://source.bookstackapp.com/bookstack/blobdiff_plain/4cbd1a9eb526bcd5fe5d9446dbf27c5813042678..refs/pull/5312/head:/app/Api/ListingResponseBuilder.php diff --git a/app/Api/ListingResponseBuilder.php b/app/Api/ListingResponseBuilder.php index 06802808e..44117bad9 100644 --- a/app/Api/ListingResponseBuilder.php +++ b/app/Api/ListingResponseBuilder.php @@ -1,62 +1,90 @@ - + */ + protected array $resultModifiers = []; - protected $filterOperators = [ + /** + * @var array + */ + protected array $filterOperators = [ 'eq' => '=', 'ne' => '!=', 'gt' => '>', 'lt' => '<', 'gte' => '>=', 'lte' => '<=', - 'like' => 'like' + 'like' => 'like', ]; /** * ListingResponseBuilder constructor. + * The given fields will be forced visible within the model results. */ - public function __construct(Builder $query, Request $request, array $fields, array $hiddenFields ) + public function __construct(Builder $query, Request $request, array $fields) { $this->query = $query; $this->request = $request; $this->fields = $fields; - $this->hiddenFields = $hiddenFields; } /** * 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 = $data->makeVisible($this->hiddenFields); + $data = $this->fetchData($filteredQuery)->each(function ($model) { + foreach ($this->resultModifiers as $modifier) { + $modifier($model); + } + }); return response()->json([ - 'data' => $data, + 'data' => $data, 'total' => $total, ]); } /** - * 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 { $query = $this->countAndOffsetQuery($query); $query = $this->sortQuery($query); + return $query->get($this->fields); } @@ -98,6 +126,7 @@ class ListingResponseBuilder } $queryOperator = $this->filterOperators[$filterOperator]; + return [$field, $queryOperator, $value]; }