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
|
|
|
|