AbstractCachingService::refreshCacheUsing()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 5
ccs 4
cts 4
cp 1
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 1
crap 1
1
<?php
2
/**
3
 * Created by PhpStorm.
4
 * User: andy
5
 * Date: 02.08.15
6
 * Time: 23:33
7
 */
8
9
namespace JsLocalization\Caching;
10
11
use Cache;
12
use DateTime;
13
14
abstract class AbstractCachingService {
15
16
    /**
17
     * The key used to cache the data.
18
     *
19
     * @var string
20
     */
21
    protected $cacheKey;
22
23
    /**
24
     * The key used to cache the timestamp of the last
25
     * refreshCache() call.
26
     *
27
     * @var string
28
     */
29
    protected $cacheTimestampKey;
30
31
32
    /**
33
     * @param string $cacheKey
34
     * @param string $cacheTimestampKey
35
     */
36 12
    public function __construct($cacheKey, $cacheTimestampKey)
37
    {
38 12
        $this->cacheKey = $cacheKey;
39 12
        $this->cacheTimestampKey = $cacheTimestampKey;
40 12
    }
41
42
    /**
43
     * Returns the timestamp of the last refreshCache() call.
44
     *
45
     * @return DateTime
46
     */
47 4
    public function getLastRefreshTimestamp()
48
    {
49 4
        $unixTime = Cache::get($this->cacheTimestampKey);
50
        
51 4
        $dateTime = new DateTime;
52 4
        $dateTime->setTimestamp($unixTime);
53
        
54 4
        return $dateTime;
55
    }
56
57
    /**
58
     * Refresh the cached data.
59
     *
60
     * @param mixed $data
61
     */
62 8
    public function refreshCacheUsing($data)
63
    {
64 8
        Cache::forever($this->cacheKey, $data);
65 8
        Cache::forever($this->cacheTimestampKey, time());
66 8
    }
67
68
    /**
69
     * Create up-to-date data and update cache using refreshCacheUsing().
70
     * Trigger some event.
71
     * 
72
     * @return void
73
     */
74
    abstract public function refreshCache();
75
76
    /**
77
     * Return the cached data. Refresh cache if cache has not yet been initialized.
78
     * 
79
     * @return mixed
80
     */
81 5
    public function getData()
82
    {
83 5
        if (!Cache::has($this->cacheKey)) {
84 3
            $this->refreshCache();
85 3
        }
86
87 5
        return Cache::get($this->cacheKey);
88
    }
89
    
90
}