Completed
Push — master ( 0d5f52...0e93a7 )
by Maxime
30:53 queued 07:15
created

StatusScope::apply()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 2

Importance

Changes 3
Bugs 0 Features 1
Metric Value
c 3
b 0
f 1
dl 0
loc 9
ccs 7
cts 7
cp 1
rs 9.6666
cc 2
eloc 4
nc 2
nop 2
crap 2
1
<?php namespace Distilleries\Expendable\Scopes;
2
3
use Distilleries\Expendable\Helpers\UserUtils;
4
use Illuminate\Database\Eloquent\Builder;
5
use Illuminate\Database\Eloquent\Scope;
6
use Illuminate\Database\Eloquent\Model;
7
8
class StatusScope implements Scope{
9
10
    /**
11
     * All of the extensions to be added to the builder.
12
     *
13
     * @var array
14
     */
15
    protected $extensions = ['WithOffline', 'OnlyOffline'];
16
17
18
    /**
19
     * Apply the scope to a given Eloquent query builder.
20
     *
21
     * @param  \Illuminate\Database\Eloquent\Builder $builder
22
     * @param  \Illuminate\Database\Eloquent\Model $model
23
     * @return void
24
     */
25 344
    public function apply(Builder $builder, Model $model)
26
    {
27 344
        if (!UserUtils::hasDisplayAllStatus())
28 344
        {
29 344
            $builder->where($model->getQualifiedStatusColumn(), true);
30 344
        }
31 344
        $this->extend($builder);
32
33 344
    }
34
35
    /**
36
     * Extend the query builder with the needed functions.
37
     *
38
     * @param  \Illuminate\Database\Eloquent\Builder $builder
39
     * @return void
40
     */
41 364
    public function extend(Builder $builder)
42
    {
43 364
        foreach ($this->extensions as $extension)
44
        {
45 364
            $this->{"add{$extension}"}($builder);
46 364
        }
47
48 364
    }
49
50
51
    /**
52
     * Add the with-trashed extension to the builder.
53
     *
54
     * @param  \Illuminate\Database\Eloquent\Builder $builder
55
     * @return void
56
     */
57 364
    protected function addWithOffline(Builder $builder)
58
    {
59
        $builder->macro('withOffline', function(Builder $builder)
60
        {
61 4
            return $builder->withoutGlobalScope($this);
62 364
        });
63 364
    }
64
65
66
    /**
67
     * Add the only-trashed extension to the builder.
68
     *
69
     * @param  \Illuminate\Database\Eloquent\Builder $builder
70
     * @return void
71
     */
72
    protected function addOnlyOffline(Builder $builder)
73
    {
74 364
        $builder->macro('onlyOffline', function(Builder $builder)
75
        {
76 4
            $model = $builder->getModel();
77
78 4
            $builder->withoutGlobalScope($this)
79 4
                ->where($model->getQualifiedStatusColumn(), '=', false);
80
81 4
            return $builder;
82 364
        });
83 364
    }
84
85
}