-
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathFilterSearch.php
61 lines (54 loc) · 1.72 KB
/
FilterSearch.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
<?php
/**
* @link https://github.com/illuminatech
* @copyright Copyright (c) 2019 Illuminatech
* @license [New BSD License](http://www.opensource.org/licenses/bsd-license.php)
*/
namespace Illuminatech\DataProvider\Filters;
use Illuminatech\DataProvider\Exceptions\InvalidQueryException;
use Illuminatech\DataProvider\FilterContract;
/**
* FilterSearch picks up the records, with at least one of listed attribute contains a requested string.
*
* Usage example:
*
* ```php
* DataProvider(Item::class)
* ->filters([
* 'search' => ['name', 'description'], // short syntax, equals to `'search' => new FilterSearch(['name', 'description'])`
* 'text_search' => new FilterSearch(['name', 'description']),
* ]);
* ```
*
* @see \Illuminatech\DataProvider\Filters\FilterLike
*
* @package Illuminatech\DataProvider\Filters
*/
class FilterSearch implements FilterContract
{
/**
* @var string[]|array list of attributes to be searched against.
*/
public $attributes = [];
public function __construct(array $attributes)
{
$this->attributes = $attributes;
}
/**
* {@inheritdoc}
*/
public function apply(object $source, string $name, $value): object
{
if (!is_scalar($value)) {
throw new InvalidQueryException('Filter "' . $name . '" requires scalar value.');
}
$source->where(function ($innerSource) use ($name, $value) {
foreach ($this->attributes as $attribute) {
$innerSource->orWhere(function ($src) use ($attribute, $name, $value) {
return (new FilterLike($attribute, true))->apply($src, $name, $value);
});
}
});
return $source;
}
}