Query::dumpBindingsTo()   A
last analyzed

Complexity

Conditions 3
Paths 3

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
cc 3
eloc 4
c 1
b 0
f 1
nc 3
nop 2
dl 0
loc 8
rs 10
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