Passed
Push — master ( d8e957...a3e243 )
by Maksim
03:45
created

CompositeKeyScope::apply()   B

Complexity

Conditions 7
Paths 1

Size

Total Lines 33
Code Lines 18

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 18
dl 0
loc 33
rs 8.8333
c 0
b 0
f 0
cc 7
nc 1
nop 1
1
<?php
2
3
namespace MaksimM\CompositePrimaryKeys\Scopes;
4
5
use MaksimM\CompositePrimaryKeys\Exceptions\MissingPrimaryKeyValueException;
6
use MaksimM\CompositePrimaryKeys\Http\Traits\NormalizedKeysParser;
7
8
class CompositeKeyScope
9
{
10
    use NormalizedKeysParser;
11
12
    private $key;
13
    private $ids;
14
    private $inverse;
15
    private $binary_columns;
16
17
    public function __construct($key, $ids, $inverse, $binary_columns = [])
18
    {
19
        $this->key = $key;
20
        $this->ids = $ids;
21
        $this->inverse = $inverse;
22
        $this->binary_columns = $binary_columns;
23
    }
24
25
    /**
26
     * @return mixed
27
     */
28
    public function getBinaryColumns()
29
    {
30
        return $this->binary_columns;
31
    }
32
    /**
33
     * Apply a query scope.
34
     *
35
     * @param \Illuminate\Database\Query\Builder|\Illuminate\Database\Eloquent\Builder $query
36
     *
37
     * @return mixed
38
     */
39
    public function apply($query)
40
    {
41
        $query->where(function ($query) {
42
            foreach ($this->ids as $compositeKey) {
43
                // try to parse normalized key
44
                if (!is_array($compositeKey)) {
45
                    $compositeKey = $this->parseNormalizedKey($compositeKey);
46
                }
47
48
                $queryWriter = function ($query) use ($compositeKey) {
49
                    /*
50
                     * @var \Illuminate\Database\Query\Builder $query
51
                     */
52
                    foreach ($this->key as $key) {
53
                        if (!isset($compositeKey[$key])) {
54
                            throw new MissingPrimaryKeyValueException(
55
                                $key,
56
                                'Missing value for key '.$key.' in record '.json_encode($compositeKey)
57
                            );
58
                        }
59
60
                        if ($this->inverse) {
61
                            $query->orWhere($key, '!=', $compositeKey[$key]);
62
                        } else {
63
                            $query->where($key, $compositeKey[$key]);
64
                        }
65
                    }
66
                };
67
68
                if ($this->inverse) {
69
                    $query->where($queryWriter);
70
                } else {
71
                    $query->orWhere($queryWriter);
72
                }
73
            }
74
        });
75
    }
76
}
77