LaravelCacheServiceProvider::boot()   A
last analyzed

Complexity

Conditions 2
Paths 1

Size

Total Lines 21
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 21
rs 9.3142
c 0
b 0
f 0
cc 2
eloc 12
nc 1
nop 0
1
<?php
2
3
namespace Anorgan\LaravelCache;
4
5
use AlternativeLaravelCache\Core\AlternativeCacheStore;
6
use AlternativeLaravelCache\Provider\AlternativeCacheStoresServiceProvider;
7
use Illuminate\Cache\CacheManager;
8
use Illuminate\Database\Eloquent\Model;
9
use Illuminate\Support\Facades\Event;
10
use Illuminate\Support\ServiceProvider;
11
12
/**
13
 * Class LaravelCacheServiceProvider
14
 * @package Anorgan\LaravelCache
15
 */
16
class LaravelCacheServiceProvider extends ServiceProvider
17
{
18
    /**
19
     * Bootstrap the application events.
20
     */
21
    public function boot()
22
    {
23
        $this->publishes([
24
            __DIR__.'/../config/laravel-cache.php' => config_path('laravel-cache.php'),
25
        ], 'config');
26
27
        $this->app->bind(AlternativeCacheStore::class, function () {
28
            return $this->app->make(CacheManager::class)->store()->getStore();
29
        });
30
31
        Event::listen(['eloquent.created: *', 'eloquent.updated: *', 'eloquent.deleted: *', 'eloquent.restored: *'], function (Model $model) {
32
            /** @var CacheInvalidator $cacheInvalidator */
33
            $cacheInvalidator = $this->app->make(CacheInvalidator::class);
34
            $cacheInvalidator->invalidateByModel($model);
35
36
            $invalidateRules = config('laravel-cache.invalidate');
37
            if (isset($invalidateRules[get_class($model)])) {
38
                $cacheInvalidator->invalidateByKeys($invalidateRules[get_class($model)]);
39
            }
40
        });
41
    }
42
43
    public function register()
44
    {
45
        $this->app->register(AlternativeCacheStoresServiceProvider::class);
46
        $this->app->afterResolving('cache', function () {
47
            $cacheManager = $this->app->make('cache');
48
            $cacheManager->extend('redis', function ($app, array $cacheConfig) use ($cacheManager) {
49
                $store = new AlternativeRedisCacheStore(
50
                    $app['redis'],
51
                    array_get($cacheConfig, 'prefix') ?: config('cache.prefix'),
52
                    array_get($cacheConfig, 'connection', 'default') ?: 'default'
53
                );
54
                return $cacheManager->repository($store);
55
            });
56
        });
57
        $this->mergeConfigFrom(__DIR__.'/../config/laravel-cache.php', 'laravel-cache');
58
    }
59
}
60