]> BookStack Code Mirror - bookstack/blob - app/Api/ListingResponseBuilder.php
5245a5d907e8229d3330443448f013c3243c958f
[bookstack] / app / Api / ListingResponseBuilder.php
1 <?php namespace BookStack\Api;
2
3 use Illuminate\Database\Eloquent\Builder;
4 use Illuminate\Database\Eloquent\Collection;
5 use Illuminate\Http\Request;
6
7 class ListingResponseBuilder
8 {
9
10     protected $query;
11     protected $request;
12     protected $fields;
13
14     protected $filterOperators = [
15         'eq'   => '=',
16         'ne'   => '!=',
17         'gt'   => '>',
18         'lt'   => '<',
19         'gte'  => '>=',
20         'lte'  => '<=',
21         'like' => 'like'
22     ];
23
24     /**
25      * ListingResponseBuilder constructor.
26      */
27     public function __construct(Builder $query, Request $request, array $fields)
28     {
29         $this->query = $query;
30         $this->request = $request;
31         $this->fields = $fields;
32     }
33
34     /**
35      * Get the response from this builder.
36      */
37     public function toResponse()
38     {
39         $this->applyFiltering($this->query);
40
41         $total = $this->query->count();
42         $data = $this->fetchData();
43
44         return response()->json([
45             'data' => $data,
46             'total' => $total,
47         ]);
48     }
49
50     /**
51      * Fetch the data to return in the response.
52      */
53     protected function fetchData(): Collection
54     {
55         $this->applyCountAndOffset($this->query);
56         $this->applySorting($this->query);
57
58         return $this->query->get($this->fields);
59     }
60
61     /**
62      * Apply any filtering operations found in the request.
63      */
64     protected function applyFiltering(Builder $query)
65     {
66         $requestFilters = $this->request->get('filter', []);
67         if (!is_array($requestFilters)) {
68             return;
69         }
70
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();
76
77         $query->where($queryFilters);
78     }
79
80     /**
81      * Convert a request filter query key/value pair into a [field, op, value] where condition.
82      */
83     protected function requestFilterToQueryFilter($fieldKey, $value): ?array
84     {
85         $splitKey = explode(':', $fieldKey);
86         $field = $splitKey[0];
87         $filterOperator = $splitKey[1] ?? 'eq';
88
89         if (!in_array($field, $this->fields)) {
90             return null;
91         }
92
93         if (!in_array($filterOperator, array_keys($this->filterOperators))) {
94             $filterOperator = 'eq';
95         }
96
97         $queryOperator = $this->filterOperators[$filterOperator];
98         return [$field, $queryOperator, $value];
99     }
100
101     /**
102      * Apply sorting operations to the query from given parameters
103      * otherwise falling back to the first given field, ascending.
104      */
105     protected function applySorting(Builder $query)
106     {
107         $defaultSortName = $this->fields[0];
108         $direction = 'asc';
109
110         $sort = $this->request->get('sort', '');
111         if (strpos($sort, '-') === 0) {
112             $direction = 'desc';
113         }
114
115         $sortName = ltrim($sort, '+- ');
116         if (!in_array($sortName, $this->fields)) {
117             $sortName = $defaultSortName;
118         }
119
120         $query->orderBy($sortName, $direction);
121     }
122
123     /**
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.
126      */
127     protected function applyCountAndOffset(Builder $query)
128     {
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);
133
134         $query->skip($offset)->take($count);
135     }
136 }