FullScopes   A
last analyzed

Complexity

Total Complexity 11

Size/Duplication

Total Lines 87
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 2

Importance

Changes 0
Metric Value
wmc 11
lcom 1
cbo 2
dl 0
loc 87
rs 10
c 0
b 0
f 0

4 Methods

Rating   Name   Duplication   Size   Complexity  
A setScopes() 0 8 2
A addScopes() 0 7 2
A assemble() 0 17 5
A apply() 0 10 2
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