Builder   A
last analyzed

Complexity

Total Complexity 7

Size/Duplication

Total Lines 59
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 23
c 1
b 0
f 0
dl 0
loc 59
rs 10
wmc 7

2 Methods

Rating   Name   Duplication   Size   Complexity  
A eagerLoadRelations() 0 20 3
A getModels() 0 23 4
1
<?php
2
3
namespace Staudenmeir\LaravelMergedRelations\Eloquent;
4
5
use Illuminate\Database\Eloquent\Builder as Base;
6
use Illuminate\Database\Eloquent\Collection;
7
use Illuminate\Database\Eloquent\Relations\Relation;
8
9
class Builder extends Base
10
{
11
    /**
12
     * Get the hydrated models without eager loading.
13
     *
14
     * @param array $columns
15
     * @return \Illuminate\Database\Eloquent\Model[]
16
     */
17
    public function getModels($columns = ['*'])
18
    {
19
        $items = $this->query->get($columns)->all();
20
21
        $models = [];
22
23
        foreach ($items as $item) {
24
            $class = Relation::getMorphedModel($item->laravel_model) ?? $item->laravel_model;
25
26
            $unset = ['laravel_model', 'laravel_placeholders'];
27
28
            if ($item->laravel_placeholders) {
29
                array_push($unset, ...explode(',', $item->laravel_placeholders));
30
            }
31
32
            foreach ($unset as $key) {
33
                unset($item->$key);
34
            }
35
36
            $models[] = (new $class())->hydrate([$item])[0];
37
        }
38
39
        return $models;
40
    }
41
42
    /**
43
     * Eager load the relationships for the models.
44
     *
45
     * @param array $models
46
     * @return array
47
     */
48
    public function eagerLoadRelations(array $models)
49
    {
50
        collect($models)->groupBy(function ($model) {
0 ignored issues
show
Bug introduced by
$models of type array is incompatible with the type Illuminate\Contracts\Support\Arrayable expected by parameter $value of collect(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

50
        collect(/** @scrutinizer ignore-type */ $models)->groupBy(function ($model) {
Loading history...
51
            return get_class($model);
52
        })->each(function ($models) {
53
            $model = $models[0];
54
55
            $relations = array_merge(
56
                $this->eagerLoad,
57
                $model->laravel_with ? explode(',', $model->laravel_with) : []
58
            );
59
60
            (new Collection($models))->load($relations);
61
        });
62
63
        foreach ($models as $model) {
64
            unset($model->laravel_with);
65
        }
66
67
        return $models;
68
    }
69
}
70