-
Notifications
You must be signed in to change notification settings - Fork 225
/
Copy pathCacheTags.php
68 lines (57 loc) · 1.7 KB
/
CacheTags.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
<?php namespace GeneaLabs\LaravelModelCaching;
use GeneaLabs\LaravelModelCaching\Traits\CachePrefixing;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\Relation;
use Illuminate\Support\Str;
class CacheTags
{
use CachePrefixing;
protected $eagerLoad;
protected $model;
protected $query;
public function __construct(
array $eagerLoad,
$model,
$query
) {
$this->eagerLoad = $eagerLoad;
$this->model = $model;
$this->query = $query;
}
public function make() : array
{
$tags = collect($this->eagerLoad)
->keys()
->map(function ($relationName) {
$relation = $this->getRelation($relationName);
return $this->getCachePrefix()
. (new Str)->slug(get_class($relation->getQuery()->getModel()));
})
->prepend($this->getTagName())
->values()
->toArray();
// dump($tags);
return $tags;
}
protected function getRelatedModel($carry) : Model
{
if ($carry instanceof Relation) {
return $carry->getQuery()->getModel();
}
return $carry;
}
protected function getRelation(string $relationName) : Relation
{
return collect(explode('.', $relationName))
->reduce(function ($carry, $name) {
$carry = $carry ?: $this->model;
$carry = $this->getRelatedModel($carry);
return $carry->{$name}();
});
}
protected function getTagName() : string
{
return $this->getCachePrefix()
. (new Str)->slug(get_class($this->model));
}
}