Skip to content

Commit 4a7e189

Browse files
author
Jordan Hall
authored
Merge pull request #8 from dextermb/feature/set-response-meta
Add the ability to add custom meta to the response
2 parents df50cc4 + 9e74206 commit 4a7e189

File tree

1 file changed

+57
-3
lines changed

1 file changed

+57
-3
lines changed

src/DataTableResponder.php

+57-3
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
use Illuminate\Database\Eloquent\Model;
55
use Illuminate\Database\Eloquent\Builder;
66
use Illuminate\Http\Request;
7+
use Illuminate\Support\Collection;
78
use Illuminate\Support\Str;
89

910
/**
@@ -42,6 +43,11 @@ class DataTableResponder
4243
*/
4344
private $perPage = 15;
4445

46+
/**
47+
* @var array
48+
*/
49+
private $meta = [];
50+
4551
/**
4652
* DataTableResponder constructor.
4753
*
@@ -110,6 +116,20 @@ public function collectionManipulator(callable $collectionManipulator)
110116
return $this;
111117
}
112118

119+
/**
120+
* Sets the meta for the API response
121+
*
122+
* @see DataTableResponder::makeMeta
123+
*
124+
* @param callable $collectionManipulator
125+
* @return DataTableResponder
126+
*/
127+
public function setResponseMeta(array $meta = [])
128+
{
129+
$this->meta = $meta;
130+
return $this;
131+
}
132+
113133
/**
114134
* Builds the Eloquent query based on the request.
115135
*
@@ -172,6 +192,41 @@ private function manipulateCollection($results)
172192
return $results;
173193
}
174194

195+
/**
196+
* Make response meta
197+
*
198+
* If a callable is given as an element value then
199+
* the query and collection as parameters
200+
*
201+
* `disallow_ordering_by` will always be overwritten
202+
* as it is managed internally
203+
*
204+
* @param Builder $query
205+
* @param Collection $collection
206+
* @return array
207+
*/
208+
private function makeMeta(Builder $query, Collection $collection)
209+
{
210+
$meta = $this->meta;
211+
$out = [];
212+
213+
foreach($meta as $element => $value) {
214+
if (is_callable($value)) {
215+
$out[$element] = call_user_func_array(
216+
$value, [$query, $collection]
217+
);
218+
219+
continue;
220+
}
221+
222+
$out[$element] = $value;
223+
}
224+
225+
$out['disallow_ordering_by'] = $this->disallowOrderingBy();
226+
227+
return $out;
228+
}
229+
175230
/**
176231
* @return array|string[]
177232
*/
@@ -210,9 +265,8 @@ public function respond()
210265

211266
$results = $this->paginateQuery($query);
212267
$results = $this->manipulateCollection($results);
268+
$meta = $this->makeMeta($query, $results->getCollection());
213269

214-
$disallowOrderingBy = $this->disallowOrderingBy();
215-
216-
return DataTableResponse::success($results, ['disallow_ordering_by' => $disallowOrderingBy])->json();
270+
return DataTableResponse::success($results, $meta)->json();
217271
}
218272
}

0 commit comments

Comments
 (0)