Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- namespace app\components\filterBuilder;
- use Exception;
- use yii\db\ActiveQueryInterface;
- class FilterBuilder
- {
- const IN = 'in';
- const BETWEEN = 'between';
- const BETWEEN_FLOAT = 'between-float';
- const EQUAL = 'eq';
- const NOT_EQUAL = 'neq';
- private $filtersMap = [
- self::IN => ProcessIn::class,
- self::BETWEEN => ProcessBetween::class,
- self::EQUAL => ProcessEqual::class,
- self::NOT_EQUAL => ProcessNotEqual::class,
- self::BETWEEN_FLOAT => ProcessBetweenFloat::class
- ];
- /**
- * @var ActiveQueryInterface
- */
- private $query;
- /**
- * @var array
- */
- private $filters;
- public function __construct(ActiveQueryInterface $query, array $filters)
- {
- $this->query = $query;
- $this->filters = $filters;
- }
- public function build(array $params)
- {
- foreach ($params as $field => $type) {
- if (!in_array($type, array_keys($this->filtersMap))) {
- throw new Exception('O tipo de filtro "' . $type . '" não existe.');
- }
- if (!class_exists($this->filtersMap[$type])) {
- throw new Exception('Implementação do filtro "' . $type . '" não existe.');
- }
- if (!isset($this->filters[$field])) {
- continue;
- }
- if (empty($this->filters[$field]) || is_null($this->filters[$field])) {
- continue;
- }
- /** @var FilterBuilderProcessInterface $process */
- $process = new $this->filtersMap[$type];
- $this->query = $process->processQuery($this->query, $field, $this->filters[$field]);
- }
- return $this->query->all();
- }
- public function addFilterProcess(string $name, string $className)
- {
- $this->filtersMap[$name] = $className;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement