Issues (214)

src/Service/Traits/WithTrait.php (2 issues)

Severity
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
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
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