1 <?php namespace BookStack\Api;
3 use Illuminate\Database\Eloquent\Builder;
4 use Illuminate\Database\Eloquent\Collection;
5 use Illuminate\Http\Request;
7 class ListingResponseBuilder
14 protected $filterOperators = [
25 * ListingResponseBuilder constructor.
27 public function __construct(Builder $query, Request $request, array $fields)
29 $this->query = $query;
30 $this->request = $request;
31 $this->fields = $fields;
35 * Get the response from this builder.
37 public function toResponse()
39 $filteredQuery = $this->filterQuery($this->query);
41 $total = $filteredQuery->count();
42 $data = $this->fetchData($filteredQuery);
44 return response()->json([
51 * Fetch the data to return in the response.
53 protected function fetchData(Builder $query): Collection
55 $query = $this->countAndOffsetQuery($query);
56 $query = $this->sortQuery($query);
57 return $query->get($this->fields);
61 * Apply any filtering operations found in the request.
63 protected function filterQuery(Builder $query): Builder
65 $query = clone $query;
66 $requestFilters = $this->request->get('filter', []);
67 if (!is_array($requestFilters)) {
71 $queryFilters = collect($requestFilters)->map(function ($value, $key) {
72 return $this->requestFilterToQueryFilter($key, $value);
73 })->filter(function ($value) {
74 return !is_null($value);
75 })->values()->toArray();
77 return $query->where($queryFilters);
81 * Convert a request filter query key/value pair into a [field, op, value] where condition.
83 protected function requestFilterToQueryFilter($fieldKey, $value): ?array
85 $splitKey = explode(':', $fieldKey);
86 $field = $splitKey[0];
87 $filterOperator = $splitKey[1] ?? 'eq';
89 if (!in_array($field, $this->fields)) {
93 if (!in_array($filterOperator, array_keys($this->filterOperators))) {
94 $filterOperator = 'eq';
97 $queryOperator = $this->filterOperators[$filterOperator];
98 return [$field, $queryOperator, $value];
102 * Apply sorting operations to the query from given parameters
103 * otherwise falling back to the first given field, ascending.
105 protected function sortQuery(Builder $query): Builder
107 $query = clone $query;
108 $defaultSortName = $this->fields[0];
111 $sort = $this->request->get('sort', '');
112 if (strpos($sort, '-') === 0) {
116 $sortName = ltrim($sort, '+- ');
117 if (!in_array($sortName, $this->fields)) {
118 $sortName = $defaultSortName;
121 return $query->orderBy($sortName, $direction);
125 * Apply count and offset for paging, based on params from the request while falling
126 * back to system defined default, taking the max limit into account.
128 protected function countAndOffsetQuery(Builder $query): Builder
130 $query = clone $query;
131 $offset = max(0, $this->request->get('offset', 0));
132 $maxCount = config('api.max_item_count');
133 $count = $this->request->get('count', config('api.default_item_count'));
134 $count = max(min($maxCount, $count), 1);
136 return $query->skip($offset)->take($count);