|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace Baro\PipelineQueryCollection; |
| 4 | + |
| 5 | +use Baro\PipelineQueryCollection\Enums\WildcardPositionEnum; |
| 6 | + |
| 7 | +class FieldsRelativeFilter extends BaseFilter |
| 8 | +{ |
| 9 | + private $wildcardPosition; |
| 10 | + |
| 11 | + public function __construct($field, $columns, WildcardPositionEnum|string $wildcardPosition = null) |
| 12 | + { |
| 13 | + parent::__construct(); |
| 14 | + $this->field = $field; |
| 15 | + $this->searchColumns = $columns; |
| 16 | + if (is_null($wildcardPosition)) { |
| 17 | + $wildcardPosition = config('pipeline-query-collection.relative_wildcard_position', WildcardPositionEnum::BOTH); |
| 18 | + } |
| 19 | + if (!$wildcardPosition instanceof WildcardPositionEnum) { |
| 20 | + $wildcardPosition = WildcardPositionEnum::from($wildcardPosition); |
| 21 | + } |
| 22 | + $this->wildcardPosition = $wildcardPosition; |
| 23 | + } |
| 24 | + |
| 25 | + public static function make($field, $columns, WildcardPositionEnum|string $wildcardPosition = null) |
| 26 | + { |
| 27 | + return new self($field, $columns, $wildcardPosition); |
| 28 | + } |
| 29 | + |
| 30 | + protected function apply(): static |
| 31 | + { |
| 32 | + foreach ($this->getSearchValue() as $value) { |
| 33 | + foreach ($this->getSearchColumns() as $column) { |
| 34 | + $this->query->where($column, 'like', $this->computeSearchValue($value)); |
| 35 | + } |
| 36 | + } |
| 37 | + return $this; |
| 38 | + } |
| 39 | + |
| 40 | + private function computeSearchValue($value) |
| 41 | + { |
| 42 | + return match ($this->wildcardPosition) { |
| 43 | + WildcardPositionEnum::RIGHT => "$value%", |
| 44 | + WildcardPositionEnum::LEFT => "%$value", |
| 45 | + default => "%$value%", |
| 46 | + }; |
| 47 | + } |
| 48 | +} |
0 commit comments