1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Goopil\RestFilter\Scopes; |
4
|
|
|
|
5
|
|
|
use Illuminate\Database\Eloquent\Model; |
6
|
|
|
use Illuminate\Database\Eloquent\Builder; |
7
|
|
|
use Illuminate\Database\Eloquent\Scope as ScopeInterface; |
8
|
|
|
|
9
|
|
|
/** |
10
|
|
|
* Class FullScopes. |
11
|
|
|
*/ |
12
|
|
|
class FullScopes extends BaseScope implements ScopeInterface |
13
|
|
|
{ |
14
|
|
|
/** |
15
|
|
|
* @var array |
16
|
|
|
*/ |
17
|
|
|
protected $scopes = [ |
18
|
|
|
InNotInScope::class, |
19
|
|
|
FilterScope::class, |
20
|
|
|
IncludeScope::class, |
21
|
|
|
OffsetLimitScope::class, |
22
|
|
|
SearchScope::class, |
23
|
|
|
OrderScope::class, |
24
|
|
|
]; |
25
|
|
|
|
26
|
|
|
/** |
27
|
|
|
* reset and set scopes to be executed. |
28
|
|
|
* |
29
|
|
|
* @param $scopes string|array |
30
|
|
|
* |
31
|
|
|
* @return $this |
32
|
|
|
*/ |
33
|
|
|
public function setScopes($scopes) |
34
|
|
|
{ |
35
|
|
|
$this->scopes = []; |
36
|
|
|
$scopes = is_array($scopes) ? $scopes : func_get_args(); |
37
|
|
|
$this->assemble($scopes); |
38
|
|
|
|
39
|
|
|
return $this; |
40
|
|
|
} |
41
|
|
|
|
42
|
|
|
/** |
43
|
|
|
* add scopes to existing ones. |
44
|
|
|
* |
45
|
|
|
* @param $scopes string|array |
46
|
|
|
* |
47
|
|
|
* @return $this |
48
|
|
|
*/ |
49
|
|
|
public function addScopes($scopes) |
50
|
|
|
{ |
51
|
|
|
$scopes = is_array($scopes) ? $scopes : func_get_args(); |
52
|
|
|
$this->assemble($scopes); |
53
|
|
|
|
54
|
|
|
return $this; |
55
|
|
|
} |
56
|
|
|
|
57
|
|
|
/** |
58
|
|
|
* assemble scopes. |
59
|
|
|
* |
60
|
|
|
* @param $scopes |
61
|
|
|
*/ |
62
|
|
|
protected function assemble(array $scopes) |
63
|
|
|
{ |
64
|
|
|
$errors = []; |
65
|
|
|
foreach ($scopes as $scope) { |
66
|
|
|
if ($scope instanceof ScopeInterface) { |
67
|
|
|
if (! in_array($scope, $this->scopes)) { |
68
|
|
|
$this->scopes[] = $scope; |
69
|
|
|
} |
70
|
|
|
} else { |
71
|
|
|
$errors[] = 'The class '.get_class($scope).'doesn\'t implements '.ScopeInterface::class; |
72
|
|
|
} |
73
|
|
|
} |
74
|
|
|
|
75
|
|
|
if (count($errors) > 0) { |
76
|
|
|
throw new \InvalidArgumentException(implode(' \n', $errors)); |
77
|
|
|
} |
78
|
|
|
} |
79
|
|
|
|
80
|
|
|
/** |
81
|
|
|
* Process scopes. |
82
|
|
|
* |
83
|
|
|
* @param Builder $builder |
84
|
|
|
* @param Model $model |
85
|
|
|
* |
86
|
|
|
* @return Builder |
87
|
|
|
*/ |
88
|
|
|
public function apply(Builder $builder, Model $model) |
89
|
|
|
{ |
90
|
|
|
foreach ($this->scopes as $scope) { |
91
|
|
|
/** @var $current ScopeInterface */ |
92
|
|
|
$current = new $scope($this->request, $this->primary, $this->secondary); |
93
|
|
|
$current->apply($builder, $model); |
94
|
|
|
} |
95
|
|
|
|
96
|
|
|
return $builder; |
97
|
|
|
} |
98
|
|
|
} |
99
|
|
|
|