Query   A
last analyzed

Complexity

Total Complexity 13

Size/Duplication

Total Lines 61
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
eloc 22
c 1
b 0
f 1
dl 0
loc 61
rs 10
wmc 13

8 Methods

Rating   Name   Duplication   Size   Complexity  
A attach() 0 9 2
A dumpBindingsTo() 0 8 3
A push() 0 3 1
A remove() 0 3 1
A setBindingTo() 0 7 2
A __construct() 0 4 1
A create() 0 3 1
A applyConstraints() 0 4 2
1
<?php
2
/**
3
 * Created by enea dhack - 19/06/2020 20:59.
4
 */
5
6
namespace Vaened\Searcher;
7
8
use Closure;
9
use Illuminate\Database\Eloquent\Builder;
10
use UnexpectedValueException;
11
12
final class Query
13
{
14
    private Builder $builder;
15
16
    public function __construct(Builder $builder, array $bindings)
17
    {
18
        $this->dumpBindingsTo($builder, $bindings);
19
        $this->builder = $builder;
20
    }
21
22
    public function create(array $loadRelationships = [], array $unloadRelationships = []): Builder
23
    {
24
        return $this->builder->with($loadRelationships)->without($unloadRelationships);
25
    }
26
27
    public function push(Constraint $constraint): void
28
    {
29
        $this->builder = $constraint->condition($this->builder);
30
    }
31
32
    public function remove(string $bindingName): void
33
    {
34
        $this->builder->withoutGlobalScope($bindingName);
35
    }
36
37
    public function attach(Closure $closure): void
38
    {
39
        $builder = $closure($this->builder);
40
41
        if (! $builder instanceof Builder) {
42
            throw new UnexpectedValueException("Attachment must be an instance of " . Builder::class);
43
        }
44
45
        $this->builder = $builder;
46
    }
47
48
    private function dumpBindingsTo(Builder &$builder, array $bindings): void
49
    {
50
        foreach ($bindings as $binding) {
51
            if (! $binding instanceof Binding) {
52
                throw new UnexpectedValueException("Bindings must be an instance of " . Binding::class);
53
            }
54
55
            $this->setBindingTo($binding, $builder);
56
        }
57
    }
58
59
    private function setBindingTo(Binding $binding, Builder $builder): void
60
    {
61
        if (! $binding->isNamed()) {
62
            $this->applyConstraints($builder, $binding->getConstraints());
63
        } else {
64
            $builder->withGlobalScope($binding->getName(), fn(Builder $eloquent
65
            ) => $this->applyConstraints($eloquent, $binding->getConstraints()));
66
        }
67
    }
68
69
    private function applyConstraints(Builder $builder, array $bindings): void
70
    {
71
        foreach ($bindings as $constraint) {
72
            $constraint->condition($builder);
73
        }
74
    }
75
}
76