Completed
Push — master ( 77de06...45cc8d )
by
unknown
01:29
created

IncludedRelationship   A

Complexity

Total Complexity 4

Size/Duplication

Total Lines 37
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 3

Importance

Changes 0
Metric Value
wmc 4
lcom 0
cbo 3
dl 0
loc 37
rs 10
c 0
b 0
f 0

2 Methods

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