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