Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Callbacks to allow more query manipulation #3

Merged
merged 1 commit into from
Aug 18, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions src/ResourceFilters.php
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,11 @@ final public function __construct(
protected Request $request,
) {}

protected function before(Builder $query): void {}

final public function handle(Builder $query, Closure $next): Builder | Collection | LengthAwarePaginator {
$this->before($query);

foreach ($this->allowed_columns as $column => $operators) {
// ignore filter if not specified in params
if (is_null($param = $this->request->query($column))) {
Expand Down Expand Up @@ -101,9 +105,13 @@ final public function handle(Builder $query, Closure $next): Builder | Collectio
}
}

$this->after($query);

return $next($query);
}

protected function after(Builder $query): void {}

private function addQueryFilter(Builder $query, string $column, string $operator, $value): void {
// check if a method with the param name exists
if (method_exists($this, $method = lcfirst((string) str($column)->studly()))) {
Expand Down
8 changes: 8 additions & 0 deletions src/ResourceOrders.php
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,11 @@ final public function __construct(
protected Request $request,
) {}

protected function before(Builder $query): void {}

final public function handle(Builder $query, Closure $next): Builder | Collection | LengthAwarePaginator {
$this->before($query);

// check if query param was not defined
if (null === $order = $this->request->query('order')) {
// add default sorting fields
Expand All @@ -56,9 +60,13 @@ final public function handle(Builder $query, Closure $next): Builder | Collectio
$this->addQueryOrder($query, $value[$direction], $direction);
}

$this->after($query);

return $next($query);
}

protected function after(Builder $query): void {}

private function clean(array &$order): void {
sort($order);

Expand Down