3 namespace BookStack\Api;
5 use Illuminate\Database\Eloquent\Builder;
6 use Illuminate\Database\Eloquent\Collection;
7 use Illuminate\Database\Eloquent\Model;
8 use Illuminate\Http\JsonResponse;
9 use Illuminate\Http\Request;
11 class ListingResponseBuilder
13 protected Builder $query;
14 protected Request $request;
19 protected array $fields;
22 * @var array<callable>
24 protected array $resultModifiers = [];
27 * @var array<string, string>
29 protected array $filterOperators = [
40 * ListingResponseBuilder constructor.
41 * The given fields will be forced visible within the model results.
43 public function __construct(Builder $query, Request $request, array $fields)
45 $this->query = $query;
46 $this->request = $request;
47 $this->fields = $fields;
51 * Get the response from this builder.
53 public function toResponse(): JsonResponse
55 $filteredQuery = $this->filterQuery($this->query);
57 $total = $filteredQuery->count();
58 $data = $this->fetchData($filteredQuery)->each(function ($model) {
59 foreach ($this->resultModifiers as $modifier) {
66 return response()->json([
73 * Add a callback to modify each element of the results.
75 * @param (callable(Model): void) $modifier
77 public function modifyResults(callable $modifier): void
79 $this->resultModifiers[] = $modifier;
83 * Fetch the data to return within the response.
85 protected function fetchData(Builder $query): Collection
87 $query = $this->countAndOffsetQuery($query);
88 $query = $this->sortQuery($query);
90 return $query->get($this->fields);
94 * Apply any filtering operations found in the request.
96 protected function filterQuery(Builder $query): Builder
98 $query = clone $query;
99 $requestFilters = $this->request->get('filter', []);
100 if (!is_array($requestFilters)) {
104 $queryFilters = collect($requestFilters)->map(function ($value, $key) {
105 return $this->requestFilterToQueryFilter($key, $value);
106 })->filter(function ($value) {
107 return !is_null($value);
108 })->values()->toArray();
110 return $query->where($queryFilters);
114 * Convert a request filter query key/value pair into a [field, op, value] where condition.
116 protected function requestFilterToQueryFilter($fieldKey, $value): ?array
118 $splitKey = explode(':', $fieldKey);
119 $field = $splitKey[0];
120 $filterOperator = $splitKey[1] ?? 'eq';
122 if (!in_array($field, $this->fields)) {
126 if (!in_array($filterOperator, array_keys($this->filterOperators))) {
127 $filterOperator = 'eq';
130 $queryOperator = $this->filterOperators[$filterOperator];
132 return [$field, $queryOperator, $value];
136 * Apply sorting operations to the query from given parameters
137 * otherwise falling back to the first given field, ascending.
139 protected function sortQuery(Builder $query): Builder
141 $query = clone $query;
142 $defaultSortName = $this->fields[0];
145 $sort = $this->request->get('sort', '');
146 if (strpos($sort, '-') === 0) {
150 $sortName = ltrim($sort, '+- ');
151 if (!in_array($sortName, $this->fields)) {
152 $sortName = $defaultSortName;
155 return $query->orderBy($sortName, $direction);
159 * Apply count and offset for paging, based on params from the request while falling
160 * back to system defined default, taking the max limit into account.
162 protected function countAndOffsetQuery(Builder $query): Builder
164 $query = clone $query;
165 $offset = max(0, $this->request->get('offset', 0));
166 $maxCount = config('api.max_item_count');
167 $count = $this->request->get('count', config('api.default_item_count'));
168 $count = max(min($maxCount, $count), 1);
170 return $query->skip($offset)->take($count);