IncludedRelationship::__invoke()   A
last analyzed

Complexity

Conditions 2
Paths 1

Size

Total Lines 22

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 22
rs 9.568
c 0
b 0
f 0
cc 2
nc 1
nop 2
1
<?php
2
3
namespace Spatie\QueryBuilder\Includes;
4
5
use Illuminate\Database\Eloquent\Builder;
6
use Illuminate\Support\Collection;
7
8
class IncludedRelationship implements IncludeInterface
9
{
10
    public function __invoke(Builder $query, string $relationship)
11
    {
12
        $relatedTables = collect(explode('.', $relationship));
13
14
        $withs = $relatedTables
15
            ->mapWithKeys(function ($table, $key) use ($query, $relatedTables) {
16
                $fullRelationName = $relatedTables->slice(0, $key + 1)->implode('.');
17
18
                $fields = $query->getRequestedFieldsForRelatedTable($fullRelationName);
19
20
                if (empty($fields)) {
21
                    return [$fullRelationName];
22
                }
23
24
                return [$fullRelationName => function ($query) use ($fields) {
25
                    $query->select($fields);
26
                }];
27
            })
28
            ->toArray();
29
30
        $query->with($withs);
31
    }
32
33
    public static function getIndividualRelationshipPathsFromInclude(string $include): Collection
34
    {
35
        return collect(explode('.', $include))
36
            ->reduce(function (Collection $includes, string $relationship) {
37
                if ($includes->isEmpty()) {
38
                    return $includes->push($relationship);
39
                }
40
41
                return $includes->push("{$includes->last()}.{$relationship}");
42
            }, collect());
43
    }
44
}
45