Completed
Push — master ( 1d77f8...1d8075 )
by Richan
01:31
created

CacheableObserver::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 1
1
<?php
2
3
namespace Suitmedia\Cacheable;
4
5
use Illuminate\Contracts\Events\Dispatcher;
6
use Illuminate\Database\Eloquent\Model;
7
use Suitmedia\Cacheable\Contracts\CacheableModel;
8
use Suitmedia\Cacheable\Events\CacheableEvent;
9
use Suitmedia\Cacheable\Events\CacheableInvalidated;
10
use Suitmedia\Cacheable\Events\CacheableInvalidating;
11
12
class CacheableObserver
13
{
14
    /**
15
     * Event dispatcher object.
16
     *
17
     * @var \Illuminate\Contracts\Events\Dispatcher
18
     */
19
    protected $events;
20
21
    /**
22
     * Cacheable observer constructor.
23
     *
24
     * @param \Illuminate\Contracts\Events\Dispatcher $events
25
     */
26
    public function __construct(Dispatcher $events)
27
    {
28
        $this->events = $events;
29
    }
30
31
    /**
32
     * Fire cacheable events.
33
     *
34
     * @param \Suitmedia\Cacheable\Events\CacheableEvent $event
35
     *
36
     * @return mixed
37
     */
38
    public function fireEvent(CacheableEvent $event)
39
    {
40
        if (method_exists($this->events, 'fire')) {
41
            return $this->events->fire($event);
42
        }
43
44
        return $this->events->dispatch($event);
45
    }
46
47
    /**
48
     * Tell the cacheable service to flush all cache
49
     * that related to the given model.
50
     *
51
     * @param \Suitmedia\Cacheable\Contracts\CacheableModel $model
52
     *
53
     * @return void
54
     */
55
    protected function flushCache(CacheableModel $model)
56
    {
57
        $tags = $model->cacheTags();
58
59
        $this->fireEvent(new CacheableInvalidating($model, $tags));
60
61
        \Cacheable::flush($tags);
62
63
        $this->fireEvent(new CacheableInvalidated($model, $tags));
64
    }
65
66
    /**
67
     * Saved event handler.
68
     *
69
     * @param \Suitmedia\Cacheable\Contracts\CacheableModel $model
70
     *
71
     * @return void
72
     */
73
    public function saved(CacheableModel $model)
74
    {
75
        $this->flushCache($model);
76
    }
77
78
    /**
79
     * Deleted event handler.
80
     *
81
     * @param \Suitmedia\Cacheable\Contracts\CacheableModel $model
82
     *
83
     * @return void
84
     */
85
    public function deleted(CacheableModel $model)
86
    {
87
        $this->flushCache($model);
88
    }
89
90
    /**
91
     * Restored event handler.
92
     *
93
     * @param \Suitmedia\Cacheable\Contracts\CacheableModel $model
94
     *
95
     * @return void
96
     */
97
    public function restored(CacheableModel $model)
98
    {
99
        $this->flushCache($model);
100
    }
101
}
102