Passed
Push — master ( 6b401d...38fb34 )
by Mike
02:33
created

Builder::eagerLoadRelation()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 10
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 10
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 7
nc 1
nop 3
1
<?php namespace GeneaLabs\LaravelModelCaching;
2
3
use Closure;
4
use Illuminate\Cache\TaggableStore;
5
use Illuminate\Database\Eloquent\Builder as EloquentBuilder;
6
use Illuminate\Database\Eloquent\Relations\Pivot;
7
use Illuminate\Support\Collection;
8
use Illuminate\Database\Eloquent\Relations\Relation;
9
10
class Builder extends EloquentBuilder
11
{
12
    protected function eagerLoadRelation(array $models, $name, Closure $constraints)
13
    {
14
        $relation = $this->getRelation($name);
15
        $relation->addEagerConstraints($models);
16
        $constraints($relation);
17
18
        return $relation->match(
19
            $relation->initRelation($models, $name),
20
            $this->cacheResults($relation, $models),
21
            $name
22
        );
23
    }
24
25
    protected function cacheResults(Relation $relation, array $models) : Collection
26
    {
27
        $parentIds = implode('_', collect($models)->pluck('id')->toArray());
28
        $parentName = str_slug(get_class($relation->getParent()));
29
        $childName = str_slug(get_class($relation->getRelated()));
30
        $cache = cache();
31
32
        if (is_subclass_of($cache->getStore(), TaggableStore::class)) {
33
            $cache->tags([$parentName, $childName]);
34
        }
35
36
        return cache()->tags([$parentName, $childName])
37
            ->rememberForever("{$parentName}_{$parentIds}-{$childName}s", function () use ($relation) {
38
                return $relation->getEager();
39
            });
40
    }
41
}
42