|
1 | 1 | <?php namespace GeneaLabs\LaravelModelCaching\Traits; |
2 | 2 |
|
3 | 3 | use Carbon\Carbon; |
| 4 | +use Closure; |
| 5 | +use GeneaLabs\LaravelModelCaching\CachedBuilder; |
4 | 6 | use GeneaLabs\LaravelModelCaching\CacheKey; |
5 | 7 | use GeneaLabs\LaravelModelCaching\CacheTags; |
6 | 8 | use Illuminate\Cache\TaggableStore; |
7 | 9 | use Illuminate\Database\Eloquent\Model; |
| 10 | +use Illuminate\Database\Eloquent\Scope; |
8 | 11 | use Illuminate\Database\Query\Builder; |
9 | 12 |
|
10 | 13 | trait Caching |
11 | 14 | { |
12 | 15 | protected $isCachable = true; |
| 16 | + protected $scopesAreApplied = false; |
| 17 | + |
| 18 | + protected function applyScopesToInstance() |
| 19 | + { |
| 20 | + if (! property_exists($this, "scopes") |
| 21 | + || $this->scopesAreApplied |
| 22 | + ) { |
| 23 | + return; |
| 24 | + } |
| 25 | + |
| 26 | + foreach ($this->scopes as $identifier => $scope) { |
| 27 | + if (! isset($this->scopes[$identifier])) { |
| 28 | + continue; |
| 29 | + } |
| 30 | + |
| 31 | + $this->scopesAreApplied = true; |
| 32 | + |
| 33 | + $this->callScope(function () use ($scope) { |
| 34 | + if ($scope instanceof Closure) { |
| 35 | + $scope($this); |
| 36 | + } |
| 37 | + |
| 38 | + if ($scope instanceof Scope |
| 39 | + && $this instanceof CachedBuilder |
| 40 | + ) { |
| 41 | + $scope->apply($this, $this->getModel()); |
| 42 | + } |
| 43 | + }); |
| 44 | + } |
| 45 | + } |
13 | 46 |
|
14 | 47 | public function cache(array $tags = []) |
15 | 48 | { |
@@ -78,6 +111,7 @@ protected function makeCacheKey( |
78 | 111 | $idColumn = null, |
79 | 112 | string $keyDifferentiator = '' |
80 | 113 | ) : string { |
| 114 | + $this->applyScopesToInstance(); |
81 | 115 | $eagerLoad = $this->eagerLoad ?? []; |
82 | 116 | $model = $this; |
83 | 117 |
|
|
0 commit comments