Passed
Pull Request — master (#124)
by Erik
03:07
created

EagerLoadRelationships::getRelationFieldByKey()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 2
c 0
b 0
f 0
dl 0
loc 4
rs 10
cc 1
nc 1
nop 2
1
<?php
2
3
namespace Bakery\Queries\Concerns;
4
5
use Bakery\Eloquent\ModelSchema;
6
use Bakery\Support\TypeRegistry;
7
use Bakery\Fields\PolymorphicField;
8
use Illuminate\Database\Eloquent\Builder;
9
10
trait EagerLoadRelationships
11
{
12
    /**
13
     * @var TypeRegistry
14
     */
15
    protected $registry;
16
17
    /**
18
     * Eager load the relations.
19
     *
20
     * @param  Builder       $query
21
     * @param  bool[]|array  $fields
22
     * @param  ModelSchema   $schema
23
     * @param  string        $path
24
     */
25
    protected function eagerLoadRelations(Builder $query, array $fields, ModelSchema $schema, $path = '')
26
    {
27
        foreach ($fields as $key => $subFields) {
28
            $field = $schema->getFieldByKey($key);
29
30
            // Skip if this is not a defined field.
31
            if (! $field) {
32
                continue;
33
            }
34
35
            $with = array_map(function ($with) use ($path) {
36
                return $path ? "{$path}.{$with}" : $with;
37
            }, $field->getWith() ?? []);
38
39
            $query->with($with);
40
41
            if ($field->isRelationship() && ! $field instanceof PolymorphicField) {
42
                $accessor = $field->getAccessor();
43
                $related = $schema->getModel()->{$accessor}()->getRelated();
44
                $relatedSchema = $this->registry->getSchemaForModel($related);
45
                $this->eagerLoadRelations($query, $subFields, $relatedSchema, $path ? "{$path}.{$accessor}" : $accessor);
46
            }
47
        }
48
    }
49
}
50