Advertisement
Guest User

Untitled

a guest
Feb 21st, 2019
84
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.90 KB | None | 0 0
  1. <?php
  2.  
  3. namespace app\components\filterBuilder;
  4.  
  5. use Exception;
  6. use yii\db\ActiveQueryInterface;
  7.  
  8. class FilterBuilder
  9. {
  10.     const IN = 'in';
  11.     const BETWEEN = 'between';
  12.     const BETWEEN_FLOAT = 'between-float';
  13.     const EQUAL = 'eq';
  14.     const NOT_EQUAL = 'neq';
  15.  
  16.     private $filtersMap = [
  17.         self::IN => ProcessIn::class,
  18.         self::BETWEEN => ProcessBetween::class,
  19.         self::EQUAL => ProcessEqual::class,
  20.         self::NOT_EQUAL => ProcessNotEqual::class,
  21.         self::BETWEEN_FLOAT => ProcessBetweenFloat::class
  22.     ];
  23.  
  24.     /**
  25.      * @var ActiveQueryInterface
  26.      */
  27.     private $query;
  28.  
  29.     /**
  30.      * @var array
  31.      */
  32.     private $filters;
  33.  
  34.     public function __construct(ActiveQueryInterface $query, array $filters)
  35.     {
  36.         $this->query = $query;
  37.         $this->filters = $filters;
  38.     }
  39.  
  40.     public function build(array $params)
  41.     {
  42.         foreach ($params as $field => $type) {
  43.             if (!in_array($type, array_keys($this->filtersMap))) {
  44.                 throw new Exception('O tipo de filtro "' . $type . '" não existe.');
  45.             }
  46.  
  47.             if (!class_exists($this->filtersMap[$type])) {
  48.                 throw new Exception('Implementação do filtro "' . $type . '" não existe.');
  49.             }
  50.  
  51.             if (!isset($this->filters[$field])) {
  52.                 continue;
  53.             }
  54.  
  55.             if (empty($this->filters[$field]) || is_null($this->filters[$field])) {
  56.                 continue;
  57.             }
  58.  
  59.             /** @var FilterBuilderProcessInterface $process */
  60.             $process = new $this->filtersMap[$type];
  61.  
  62.             $this->query = $process->processQuery($this->query, $field, $this->filters[$field]);
  63.         }
  64.  
  65.         return $this->query->all();
  66.     }
  67.  
  68.     public function addFilterProcess(string $name, string $className)
  69.     {
  70.         $this->filtersMap[$name] = $className;
  71.     }
  72. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement