Completed
Push — master ( 68a553...e9f254 )
by Milroy
01:21
created

QueryHelper   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 50
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 2

Importance

Changes 0
Metric Value
dl 0
loc 50
c 0
b 0
f 0
wmc 8
lcom 1
cbo 2
rs 10

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 5 1
A exact() 0 22 5
A alias() 0 12 2
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Sarala\Query;
6
7
use Illuminate\Database\Eloquent\Builder;
8
9
class QueryHelper
10
{
11
    /** @var Builder $query */
12
    private $query;
13
14
    /** @var QueryParamBag $includes*/
15
    private $includes;
16
17
    public function __construct(Builder $query, QueryParamBag $includes)
18
    {
19
        $this->query = $query;
20
        $this->includes = $includes;
21
    }
22
23
    public function exact($fields)
24
    {
25
        if (is_string($fields)) {
26
            if ($this->includes->has($fields)) {
27
                $this->query->with($fields);
28
            }
29
30
            return $this;
31
        }
32
33
        if (! is_array($fields)) {
34
            throw new \InvalidArgumentException(
35
                'The exact() method expects a string or an array. '.gettype($fields).' given'
36
            );
37
        }
38
39
        foreach (array_intersect($this->includes->keys(), $fields) as $field) {
40
            $this->query->with($field);
41
        }
42
43
        return $this;
44
    }
45
46
    public function alias(string $name, $value)
47
    {
48
        if (is_callable($value)) {
49
            $this->query->when($this->includes->has($name), $value);
50
        } else {
51
            $this->query->when($this->includes->has($name), function (Builder $query) use ($value) {
52
                $query->with($value);
53
            });
54
        }
55
56
        return $this;
57
    }
58
}
59