Passed
Push — master ( 30f57b...f3320a )
by huang
02:57
created

CachePool::__construct()   A

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 0
Metric Value
cc 1
eloc 2
nc 1
nop 1
dl 0
loc 4
ccs 3
cts 3
cp 1
crap 1
rs 10
c 0
b 0
f 0
1
<?php
2
/**
3
 * @author    jan huang <[email protected]>
4
 * @copyright 2016
5
 *
6
 * @see      https://www.github.com/janhuang
7
 * @see      http://www.fast-d.cn/
8
 */
9
10
namespace FastD\Pool;
11
12
use Symfony\Component\Cache\Adapter\AbstractAdapter;
13
use Symfony\Component\Cache\Adapter\RedisAdapter;
14
15
/**
16
 * Class CachePool.
17
 */
18
class CachePool implements PoolInterface
19
{
20
    /**
21
     * @var AbstractAdapter[]
22
     */
23
    protected $caches = [];
24
25
    /**
26
     * @var array
27
     */
28
    protected $config;
29
30
    /**
31
     * Cache constructor.
32
     *
33
     * @param array $config
34
     */
35 43
    public function __construct(array $config)
36
    {
37 43
        $this->config = $config;
38 43
    }
39
40
    /**
41
     * @param $key
42
     *
43
     * @return AbstractAdapter
44
     */
45 4
    public function getCache($key)
46
    {
47 4
        if (!isset($this->caches[$key])) {
48 4
            if (!isset($this->config[$key])) {
49 1
                throw new \LogicException(sprintf('No set %s cache', $key));
50
            }
51 3
            $config = $this->config[$key];
52 3
            switch ($config['adapter']) {
53 3
                case RedisAdapter::class:
54
                    $this->caches[$key] = new RedisAdapter(
55
                        RedisAdapter::createConnection($config['params']['dsn']),
56
                        isset($config['params']['namespace']) ? $config['params']['namespace'] : '',
57
                        isset($config['params']['lifetime']) ? $config['params']['lifetime'] : ''
58
                    );
59
                    break;
60 3
                default:
61 3
                    $this->caches[$key] = new $config['adapter'](
62 3
                        isset($config['params']['namespace']) ? $config['params']['namespace'] : '',
63 3
                        isset($config['params']['lifetime']) ? $config['params']['lifetime'] : '',
64 3
                        isset($config['params']['directory']) ? $config['params']['directory'] : app()->getPath().'/runtime/cache'
65 3
                    );
66 3
            }
67 3
        }
68
69 3
        return $this->caches[$key];
70
    }
71
72
    /**
73
     * {@inheritdoc}
74
     */
75
    public function initPool()
76
    {
77
        foreach ($this->config as $name => $config) {
78
            $this->getCache($name);
79
        }
80
    }
81
}
82