]> BookStack Code Mirror - bookstack/blob - app/Api/ListingResponseBuilder.php
Updated styles to use logical properties/values
[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         $data = $this->fetchData();
40         $total = $this->query->count();
41
42         return response()->json([
43             'data' => $data,
44             'total' => $total,
45         ]);
46     }
47
48     /**
49      * Fetch the data to return in the response.
50      */
51     protected function fetchData(): Collection
52     {
53         $this->applyCountAndOffset($this->query);
54         $this->applySorting($this->query);
55         $this->applyFiltering($this->query);
56
57         return $this->query->get($this->fields);
58     }
59
60     /**
61      * Apply any filtering operations found in the request.
62      */
63     protected function applyFiltering(Builder $query)
64     {
65         $requestFilters = $this->request->get('filter', []);
66         if (!is_array($requestFilters)) {
67             return;
68         }
69
70         $queryFilters = collect($requestFilters)->map(function ($value, $key) {
71             return $this->requestFilterToQueryFilter($key, $value);
72         })->filter(function ($value) {
73             return !is_null($value);
74         })->values()->toArray();
75
76         $query->where($queryFilters);
77     }
78
79     /**
80      * Convert a request filter query key/value pair into a [field, op, value] where condition.
81      */
82     protected function requestFilterToQueryFilter($fieldKey, $value): ?array
83     {
84         $splitKey = explode(':', $fieldKey);
85         $field = $splitKey[0];
86         $filterOperator = $splitKey[1] ?? 'eq';
87
88         if (!in_array($field, $this->fields)) {
89             return null;
90         }
91
92         if (!in_array($filterOperator, array_keys($this->filterOperators))) {
93             $filterOperator = 'eq';
94         }
95
96         $queryOperator = $this->filterOperators[$filterOperator];
97         return [$field, $queryOperator, $value];
98     }
99
100     /**
101      * Apply sorting operations to the query from given parameters
102      * otherwise falling back to the first given field, ascending.
103      */
104     protected function applySorting(Builder $query)
105     {
106         $defaultSortName = $this->fields[0];
107         $direction = 'asc';
108
109         $sort = $this->request->get('sort', '');
110         if (strpos($sort, '-') === 0) {
111             $direction = 'desc';
112         }
113
114         $sortName = ltrim($sort, '+- ');
115         if (!in_array($sortName, $this->fields)) {
116             $sortName = $defaultSortName;
117         }
118
119         $query->orderBy($sortName, $direction);
120     }
121
122     /**
123      * Apply count and offset for paging, based on params from the request while falling
124      * back to system defined default, taking the max limit into account.
125      */
126     protected function applyCountAndOffset(Builder $query)
127     {
128         $offset = max(0, $this->request->get('offset', 0));
129         $maxCount = config('api.max_item_count');
130         $count = $this->request->get('count', config('api.default_item_count'));
131         $count = max(min($maxCount, $count), 1);
132
133         $query->skip($offset)->take($count);
134     }
135 }