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