1
|
|
|
<?php |
2
|
|
|
/* |
3
|
|
|
* This file is part of the Laravel Platfourm package. |
4
|
|
|
* |
5
|
|
|
* (c) Avtandil Kikabidze aka LONGMAN <[email protected]> |
6
|
|
|
* |
7
|
|
|
* For the full copyright and license information, please view the LICENSE |
8
|
|
|
* file that was distributed with this source code. |
9
|
|
|
*/ |
10
|
|
|
|
11
|
|
|
namespace Longman\Platfourm\Repository\Criteria; |
12
|
|
|
|
13
|
|
|
use Illuminate\Database\Eloquent\Builder as EloquentBuilder; |
14
|
|
|
use Longman\Platfourm\Contracts\Repository\Criteria; |
15
|
|
|
use Longman\Platfourm\Contracts\Repository\Repository; |
16
|
|
|
|
17
|
|
|
/** |
18
|
|
|
* Class RequestCriteria. |
19
|
|
|
*/ |
20
|
|
|
class SearchCriteria implements Criteria |
21
|
|
|
{ |
22
|
|
|
protected $search; |
23
|
|
|
|
24
|
|
|
protected $searchFields; |
25
|
|
|
|
26
|
|
|
public function __construct($search, $searchFields = null) |
27
|
|
|
{ |
28
|
|
|
$this->search = $search; |
29
|
|
|
$this->searchFields = $searchFields; |
30
|
|
|
} |
31
|
|
|
|
32
|
|
|
/** |
33
|
|
|
* Apply criteria in query repository. |
34
|
|
|
* |
35
|
|
|
* @param $model |
36
|
|
|
* @param Repository $repository |
37
|
|
|
* @return mixed |
38
|
|
|
*/ |
39
|
|
|
public function apply($model, Repository $repository) |
40
|
|
|
{ |
41
|
|
|
if ($model instanceof EloquentBuilder) { |
42
|
|
|
$searchableFields = $model->getModel()->getSearchableFields(); |
43
|
|
|
} else { |
44
|
|
|
$searchableFields = $model->getSearchableFields(); |
45
|
|
|
} |
46
|
|
|
|
47
|
|
|
$search = $this->search; |
48
|
|
|
$searchFields = $this->searchFields; |
49
|
|
|
$searchFields = !empty($searchFields) ? explode(',', $searchFields) : $searchableFields; |
50
|
|
|
|
51
|
|
View Code Duplication |
if ($search && $searchableFields) { |
|
|
|
|
52
|
|
|
$model = $model->where(function ($query) use ($searchableFields, $searchFields, $search) { |
53
|
|
|
|
54
|
|
|
$isFirstField = true; |
55
|
|
|
|
56
|
|
|
foreach ($searchFields as $field) { |
57
|
|
|
if (!in_array($field, $searchableFields)) { |
58
|
|
|
continue; |
59
|
|
|
} |
60
|
|
|
|
61
|
|
|
$value = "%{$search}%"; |
62
|
|
|
|
63
|
|
|
if ($isFirstField && !is_null($value)) { |
64
|
|
|
$query->where($field, 'like', $value); |
65
|
|
|
$isFirstField = false; |
66
|
|
|
} elseif (!is_null($value)) { |
67
|
|
|
$query->orWhere($field, 'like', $value); |
68
|
|
|
} |
69
|
|
|
} |
70
|
|
|
}); |
71
|
|
|
} |
72
|
|
|
|
73
|
|
|
return $model; |
74
|
|
|
} |
75
|
|
|
|
76
|
|
|
} |
77
|
|
|
|
Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.
You can also find more detailed suggestions in the “Code” section of your repository.