Skip to content

Instantly share code, notes, and snippets.

@CamKem
Last active July 28, 2023 15:34
Show Gist options
  • Save CamKem/f16674b60f6d4192f119df1ac08edb1f to your computer and use it in GitHub Desktop.
Save CamKem/f16674b60f6d4192f119df1ac08edb1f to your computer and use it in GitHub Desktop.
Abstract Filters Class
<?php
namespace App\Filters;
abstract class Filters
{
/**
* The protected request and query objects.
* @var object
*/
protected object $request, $query;
/**
* The protected filters array.
* @var array
*/
protected array $filters = [];
/**
* Filters class constructor.
* @param $request
*/
public function __construct($request)
{
$this->request = $request;
}
/**
* Apply the filters to the query.
* @param $query
* @return object
*/
public function apply($query): object
{
$this->query = $query;
foreach ($this->getFilters() as $filter => $value) {
if (method_exists($this, $filter)) {
$this->$filter($value);
}
}
return $this->query;
}
/**
* Get the filters from the request.
* @return mixed
*/
public function getFilters(): mixed
{
$filters = array_intersect(array_keys($this->request->all()), $this->filters);
return $this->request->only($filters);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment