Manager::get()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 2
c 1
b 0
f 0
dl 0
loc 4
rs 10
ccs 3
cts 3
cp 1
cc 1
nc 1
nop 2
crap 1
1
<?php
2
namespace RazonYang\Yii2\Setting;
3
4
use yii\base\Component;
5
use yii\caching\CacheInterface;
6
use yii\di\Instance;
7
use yii\mutex\Mutex;
8
9
/**
10
 * Manager is the base manager.
11
 */
12
abstract class Manager extends Component implements ManagerInterface
13
{
14
    /**
15
     * @var CacheInterface $cache
16
     */
17
    public $cache = 'cache';
18
19
    /**
20
     * @var bool $enableCache whether enable caching.
21
     */
22
    public $enableCache = true;
23
24
    /**
25
     * @var Mutex $mutex
26
     */
27
    public $mutex = 'mutex';
28
    
29
    /**
30
     * @var string $cacheKey
31
     */
32
    public $cacheKey = self::class;
33
34
    /**
35
     * @var int $duration
36
     */
37
    public $duration = 600;
38
39 8
    public function init()
40
    {
41 8
        parent::init();
42
43 8
        $this->cache = Instance::ensure($this->cache, CacheInterface::class);
44 8
        $this->mutex = Instance::ensure($this->mutex, Mutex::class);
45 8
    }
46
47
    private $data;
48
49 6
    public function get(string $id, ?string $defaultValue = null): ?string
50
    {
51 6
        $data = $this->getAll();
52 6
        return $data[$id] ?? $defaultValue;
53
    }
54
55 7
    public function getAll(): array
56
    {
57 7
        if ($this->data !== null) {
58 4
            return $this->data;
59
        }
60
61
        // retrieves from cache
62 7
        if ($this->enableCache && ($this->data = $this->cache->get($this->cacheKey)) !== false) {
63 3
            return $this->data;
64
        }
65
66
        // retrieves all data
67 7
        $this->data = $this->load();
68
            
69
        // cache
70 7
        if ($this->enableCache) {
71 5
            $lock = $this->cacheKey;
72
            // acquire lock avoid concurrence
73 5
            if ($this->mutex->acquire($lock, 0)) {
74 5
                $this->cache->set($this->cacheKey, $this->data, $this->duration);
75
            }
76
        }
77
        
78 7
        return $this->data;
79
    }
80
    
81
    /**
82
     * Loads all data as array that mapping from id to value.
83
     *
84
     * @return array
85
     */
86
    abstract protected function load(): array;
87
88 1
    public function flushCache(): bool
89
    {
90 1
        $this->data = null;
91
        // flush cache
92 1
        return $this->cache->delete($this->cacheKey);
93
    }
94
}
95