Passed
Pull Request — master (#124)
by Erik
05:08
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  \Illuminate\Database\Eloquent\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
            $with = array_map(function ($with) use ($path) {
31
                return $path ? "{$path}.{$with}" : $with;
32
            }, $field->getWith() ?? []);
33
34
            $query->with($with);
35
36
            if ($field->isRelationship() && ! $field instanceof PolymorphicField) {
37
                $accessor = $field->getAccessor();
38
                $related = $schema->getModel()->{$accessor}()->getRelated();
39
                $relatedSchema = $this->registry->getSchemaForModel($related);
40
                $this->eagerLoadRelations($query, $subFields, $relatedSchema, $path ? "{$path}.{$accessor}" : $accessor);
41
            }
42
        }
43
    }
44
}
45