Completed
Branch master (111fe8)
by Niclas Leon
01:26
created

ActivatableScope::apply()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 22
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 22
rs 9.2
c 0
b 0
f 0
cc 1
eloc 12
nc 1
nop 2
1
<?php
2
namespace niclasleonbock\Eloquent;
3
4
use Illuminate\Database\Eloquent\Builder;
5
use Illuminate\Database\Eloquent\Model;
6
use Illuminate\Database\Eloquent\Scope;
7
8
class ActivatableScope implements Scope
9
{
10
    /**
11
     * Apply the scope to a given Eloquent query builder.
12
     *
13
     * @param  \Illuminate\Database\Eloquent\Builder  $builder
14
     * @return void
15
     */
16
    public function apply(Builder $builder, Model $model)
17
    {
18
        $builder->whereNotNull($model->getQualifiedActivatedAtColumn());
19
20
        $builder->macro('withDeactivated', function (Builder $builder) {
21
            $this->remove($builder);
22
23
            return $builder;
24
        });
25
26
        $builder->macro('onlyDeactivated', function (Builder $builder) {
27
            $model = $builder->getModel();
28
29
            $this->remove($builder);
30
31
            $builder
32
                ->getQuery()
33
                ->whereNotNull($model->getQualifiedActivatedAtColumn());
34
35
            return $builder;
36
        });
37
    }
38
39
    /**
40
     * Remove the scope from the given Eloquent query builder.
41
     *
42
     * @param  \Illuminate\Database\Eloquent\Builder  $builder
43
     * @return void
44
     */
45
    public function remove(Builder $builder)
46
    {
47
        $column = $builder->getModel()->getQualifiedActivatedAtColumn();
48
        $query = $builder->getQuery();
49
50
        foreach ((array) $query->wheres as $key => $where) {
51
            if ($this->isActivatedConstraint($where, $column)) {
52
                unset($query->wheres[$key]);
53
54
                $query->wheres = array_values($query->wheres);
55
            }
56
        }
57
    }
58
59
    /**
60
     * Determine if the given where clause is an activated constraint.
61
     *
62
     * @param  array   $where
63
     * @param  string  $column
64
     * @return bool
65
     */
66
    protected function isActivatedConstraint(array $where, $column)
67
    {
68
        return $where['type'] == 'NotNull' && $where['column'] == $column;
69
    }
70
}
71