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 $this->applyFiltering($this->query);
41 $total = $this->query->count();
42 $data = $this->fetchData();
44 return response()->json([
51 * Fetch the data to return in the response.
53 protected function fetchData(): Collection
55 $this->applyCountAndOffset($this->query);
56 $this->applySorting($this->query);
58 return $this->query->get($this->fields);
62 * Apply any filtering operations found in the request.
64 protected function applyFiltering(Builder $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 $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 applySorting(Builder $query)
107 $defaultSortName = $this->fields[0];
110 $sort = $this->request->get('sort', '');
111 if (strpos($sort, '-') === 0) {
115 $sortName = ltrim($sort, '+- ');
116 if (!in_array($sortName, $this->fields)) {
117 $sortName = $defaultSortName;
120 $query->orderBy($sortName, $direction);
124 * Apply count and offset for paging, based on params from the request while falling
125 * back to system defined default, taking the max limit into account.
127 protected function applyCountAndOffset(Builder $query)
129 $offset = max(0, $this->request->get('offset', 0));
130 $maxCount = config('api.max_item_count');
131 $count = $this->request->get('count', config('api.default_item_count'));
132 $count = max(min($maxCount, $count), 1);
134 $query->skip($offset)->take($count);