]> BookStack Code Mirror - bookstack/blob - app/Api/ListingResponseBuilder.php
Addressed test failures from users API changes
[bookstack] / app / Api / ListingResponseBuilder.php
1 <?php
2
3 namespace BookStack\Api;
4
5 use BookStack\Model;
6 use Illuminate\Database\Eloquent\Builder;
7 use Illuminate\Database\Eloquent\Collection;
8 use Illuminate\Http\JsonResponse;
9 use Illuminate\Http\Request;
10
11 class ListingResponseBuilder
12 {
13     protected $query;
14     protected $request;
15     protected $fields;
16
17     /**
18      * @var array<callable>
19      */
20     protected $resultModifiers = [];
21
22     protected $filterOperators = [
23         'eq'   => '=',
24         'ne'   => '!=',
25         'gt'   => '>',
26         'lt'   => '<',
27         'gte'  => '>=',
28         'lte'  => '<=',
29         'like' => 'like',
30     ];
31
32     /**
33      * ListingResponseBuilder constructor.
34      * The given fields will be forced visible within the model results.
35      */
36     public function __construct(Builder $query, Request $request, array $fields)
37     {
38         $this->query = $query;
39         $this->request = $request;
40         $this->fields = $fields;
41     }
42
43     /**
44      * Get the response from this builder.
45      */
46     public function toResponse(): JsonResponse
47     {
48         $filteredQuery = $this->filterQuery($this->query);
49
50         $total = $filteredQuery->count();
51         $data = $this->fetchData($filteredQuery)->each(function($model) {
52             foreach ($this->resultModifiers as $modifier) {
53                 $modifier($model);
54             }
55         });
56
57         return response()->json([
58             'data'  => $data,
59             'total' => $total,
60         ]);
61     }
62
63     /**
64      * Add a callback to modify each element of the results
65      * @param (callable(Model)) $modifier
66      */
67     public function modifyResults($modifier): void
68     {
69         $this->resultModifiers[] = $modifier;
70     }
71
72     /**
73      * Fetch the data to return within the response.
74      */
75     protected function fetchData(Builder $query): Collection
76     {
77         $query = $this->countAndOffsetQuery($query);
78         $query = $this->sortQuery($query);
79
80         return $query->get($this->fields);
81     }
82
83     /**
84      * Apply any filtering operations found in the request.
85      */
86     protected function filterQuery(Builder $query): Builder
87     {
88         $query = clone $query;
89         $requestFilters = $this->request->get('filter', []);
90         if (!is_array($requestFilters)) {
91             return $query;
92         }
93
94         $queryFilters = collect($requestFilters)->map(function ($value, $key) {
95             return $this->requestFilterToQueryFilter($key, $value);
96         })->filter(function ($value) {
97             return !is_null($value);
98         })->values()->toArray();
99
100         return $query->where($queryFilters);
101     }
102
103     /**
104      * Convert a request filter query key/value pair into a [field, op, value] where condition.
105      */
106     protected function requestFilterToQueryFilter($fieldKey, $value): ?array
107     {
108         $splitKey = explode(':', $fieldKey);
109         $field = $splitKey[0];
110         $filterOperator = $splitKey[1] ?? 'eq';
111
112         if (!in_array($field, $this->fields)) {
113             return null;
114         }
115
116         if (!in_array($filterOperator, array_keys($this->filterOperators))) {
117             $filterOperator = 'eq';
118         }
119
120         $queryOperator = $this->filterOperators[$filterOperator];
121
122         return [$field, $queryOperator, $value];
123     }
124
125     /**
126      * Apply sorting operations to the query from given parameters
127      * otherwise falling back to the first given field, ascending.
128      */
129     protected function sortQuery(Builder $query): Builder
130     {
131         $query = clone $query;
132         $defaultSortName = $this->fields[0];
133         $direction = 'asc';
134
135         $sort = $this->request->get('sort', '');
136         if (strpos($sort, '-') === 0) {
137             $direction = 'desc';
138         }
139
140         $sortName = ltrim($sort, '+- ');
141         if (!in_array($sortName, $this->fields)) {
142             $sortName = $defaultSortName;
143         }
144
145         return $query->orderBy($sortName, $direction);
146     }
147
148     /**
149      * Apply count and offset for paging, based on params from the request while falling
150      * back to system defined default, taking the max limit into account.
151      */
152     protected function countAndOffsetQuery(Builder $query): Builder
153     {
154         $query = clone $query;
155         $offset = max(0, $this->request->get('offset', 0));
156         $maxCount = config('api.max_item_count');
157         $count = $this->request->get('count', config('api.default_item_count'));
158         $count = max(min($maxCount, $count), 1);
159
160         return $query->skip($offset)->take($count);
161     }
162 }