Passed
Pull Request — main (#55)
by Thierry
05:38
created

WithTrait::addWith()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 2
nc 1
nop 1
dl 0
loc 4
rs 10
c 1
b 0
f 0
1
<?php
2
3
namespace Siak\Tontine\Service\Traits;
4
5
use Illuminate\Database\Eloquent\Builder;
6
use Illuminate\Database\Eloquent\Relations\Relation;
7
8
use function count;
9
use function is_string;
10
11
trait WithTrait
12
{
13
    /**
14
     * @var array
15
     */
16
    protected array $withs = [];
17
18
    /**
19
     * @var array
20
     */
21
    protected array $withCounts = [];
22
23
    /**
24
     * @param array|string $relation
25
     *
26
     * @return self
27
     */
28
    public function with(array|string $relation): self
29
    {
30
        $this->withs = is_string($relation) ?
0 ignored issues
show
introduced by
The condition is_string($relation) is always false.
Loading history...
31
            [...$this->withs, $relation] :
32
            [...$this->withs, ...$relation];
33
        return $this;
34
    }
35
36
    /**
37
     * @param array|string $relation
38
     *
39
     * @return self
40
     */
41
    public function withCount(array|string $relation): self
42
    {
43
        $this->withCounts = is_string($relation) ?
0 ignored issues
show
introduced by
The condition is_string($relation) is always false.
Loading history...
44
            [...$this->withCounts, $relation] :
45
            [...$this->withCounts, ...$relation];
46
        return $this;
47
    }
48
49
    /**
50
     * @param Builder|Relation $query
51
     *
52
     * @return void
53
     */
54
    protected function addWith(Builder|Relation $query)
55
    {
56
        $query->when(count($this->withs) > 0, fn() => $query->with($this->withs))
57
            ->when(count($this->withCounts) > 0, fn() => $query->withCount($this->withCounts));
58
    }
59
}
60