class-global-filter.php
97 lines
| 1 | <?php |
| 2 | |
| 3 | namespace SearchRegex\Filter; |
| 4 | |
| 5 | use SearchRegex\Schema; |
| 6 | use SearchRegex\Source; |
| 7 | use SearchRegex\Filter\Type; |
| 8 | |
| 9 | /** |
| 10 | * A global search filter that performs a string match on any column marked 'global' in the schema |
| 11 | */ |
| 12 | class Global_Filter extends Filter { |
| 13 | /** |
| 14 | * Global search phrase |
| 15 | * |
| 16 | * @readonly |
| 17 | */ |
| 18 | private string $search_phrase; |
| 19 | |
| 20 | /** |
| 21 | * Global search flags |
| 22 | * |
| 23 | * @readonly |
| 24 | * @var string[] |
| 25 | */ |
| 26 | private array $search_flags; |
| 27 | |
| 28 | /** |
| 29 | * Constructor |
| 30 | * |
| 31 | * @param string $search_phrase Search. |
| 32 | * @param string[] $search_flags Search flags. |
| 33 | * @phpstan-ignore constructor.missingParentCall |
| 34 | */ |
| 35 | public function __construct( $search_phrase, $search_flags ) { |
| 36 | $this->search_phrase = $search_phrase; |
| 37 | $this->search_flags = $search_flags; |
| 38 | } |
| 39 | |
| 40 | /** |
| 41 | * Is this filter for a given source? |
| 42 | * |
| 43 | * @param string $source Source name. |
| 44 | * @return boolean |
| 45 | */ |
| 46 | public function is_for_source( $source ) { |
| 47 | return true; |
| 48 | } |
| 49 | |
| 50 | /** |
| 51 | * Is this filter for this column? |
| 52 | * |
| 53 | * @param Schema\Column $column Column. |
| 54 | * @return boolean |
| 55 | */ |
| 56 | public function is_for( Schema\Column $column ) { |
| 57 | return $column->is_global(); |
| 58 | } |
| 59 | |
| 60 | /** |
| 61 | * Get the filter items |
| 62 | * |
| 63 | * @param Source\Source $source Source. |
| 64 | * @return list<Type\Filter_Type> |
| 65 | */ |
| 66 | public function get_items( Source\Source $source ) { |
| 67 | $schema = new Schema\Source( $source->get_schema_for_source() ); |
| 68 | $items = []; |
| 69 | |
| 70 | foreach ( $schema->get_global_columns() as $column ) { |
| 71 | $filter = [ |
| 72 | 'column' => $column->get_column(), |
| 73 | 'flags' => $this->search_flags, |
| 74 | 'value' => $this->search_phrase, |
| 75 | 'logic' => 'contains', |
| 76 | ]; |
| 77 | |
| 78 | $items[] = new Type\Filter_String( $filter, $column ); |
| 79 | } |
| 80 | |
| 81 | return [ |
| 82 | ...$items, |
| 83 | ...array_filter( |
| 84 | $this->items, fn( $item ) => $item->get_schema()->get_type() === $source->get_type() |
| 85 | ), |
| 86 | ]; |
| 87 | } |
| 88 | |
| 89 | public function has_column( $column, Schema\Column $schema ) { |
| 90 | return $schema->is_global(); |
| 91 | } |
| 92 | |
| 93 | public function is_advanced() { |
| 94 | return in_array( 'regex', $this->search_flags, true ); |
| 95 | } |
| 96 | } |
| 97 |