Passed
Push — master ( 1ee36e...1b5a73 )
by Jonas
03:15
created

Builder   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 59
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 23
c 1
b 0
f 0
dl 0
loc 59
ccs 25
cts 25
cp 1
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
8
class Builder extends Base
9
{
10
    /**
11
     * Get the hydrated models without eager loading.
12
     *
13
     * @param array $columns
14
     * @return \Illuminate\Database\Eloquent\Model[]
15
     */
16 32
    public function getModels($columns = ['*'])
17
    {
18 32
        $items = $this->query->get($columns)->all();
19
20 32
        $models = [];
21
22 32
        foreach ($items as $item) {
23 32
            $class = $item->laravel_model;
24
25 32
            $unset = ['laravel_model', 'laravel_placeholders'];
26
27 32
            if ($item->laravel_placeholders) {
28 8
                array_push($unset, ...explode(',', $item->laravel_placeholders));
29
            }
30
31 32
            foreach ($unset as $key) {
32 32
                unset($item->$key);
33
            }
34
35 32
            $models[] = (new $class)->hydrate([$item])[0];
36
        }
37
38 32
        return $models;
39
    }
40
41
    /**
42
     * Eager load the relationships for the models.
43
     *
44
     * @param array $models
45
     * @return array
46
     */
47 32
    public function eagerLoadRelations(array $models)
48
    {
49 32
        collect($models)->groupBy(function ($model) {
50 32
            return get_class($model);
51 32
        })->each(function ($models) {
52 32
            $model = $models[0];
53
54 32
            $relations = array_merge(
55 32
                $this->eagerLoad,
56 32
                $model->laravel_with ? explode(',', $model->laravel_with) : []
57
            );
58
59 32
            (new Collection($models))->load($relations);
60 32
        });
61
62 32
        foreach ($models as $model) {
63 32
            unset($model->laravel_with);
64
        }
65
66 32
        return $models;
67
    }
68
}
69