Last active
July 28, 2023 15:34
-
-
Save CamKem/f16674b60f6d4192f119df1ac08edb1f to your computer and use it in GitHub Desktop.
Abstract Filters Class
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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