Common::factoryStorage()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 10
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 2

Importance

Changes 0
Metric Value
cc 2
eloc 5
nc 2
nop 0
dl 0
loc 10
ccs 6
cts 6
cp 1
crap 2
rs 9.4285
c 0
b 0
f 0
1
<?php
2
/**
3
 * Created by PhpStorm.
4
 * User: michal
5
 * Date: 10/10/2017
6
 * Time: 14:27
7
 */
8
9
namespace BlueCache;
10
11
use \BlueCache\Storage\File;
12
use \BlueCache\Storage\StorageInterface;
13
14
trait Common
15
{
16
    /**
17
     * @var StorageInterface
18
     */
19
    protected $storage;
20
21
    /**
22
     * @var array
23
     */
24
    protected $config = [
25
        'storage_class' => File::class,
26
        'storage_directory' => './var/cache',
27
    ];
28
29
    /**
30
     * check that cache directory exist and create it if not
31
     *
32
     * @param array $config
33
     * @throws \BlueCache\CacheException
34
     */
35 28
    public function __construct(array $config = [])
36
    {
37 28
        $this->config = \array_merge($this->config, $config);
38
39 28
        $this->registerStorage();
40 26
    }
41
42
    /**
43
     * @return $this
44
     * @throws \BlueCache\CacheException
45
     */
46 28
    protected function registerStorage()
47
    {
48 28
        switch (true) {
49 28
            case $this->config['storage_class'] instanceof StorageInterface:
50 2
                $this->storage = $this->config['storage_class'];
51 2
                break;
52
53 26
            case $this->config['storage_class'] === File::class:
54 26
            case \is_string($this->config['storage_class']):
55 24
                $this->factoryStorage();
56 24
                break;
57
58 2
            default:
59 2
                throw new CacheException('Incorrect storage type: ' . \get_class($this->storage));
60 2
        }
61
62 26
        return $this;
63
    }
64
65
    /**
66
     * @return $this
67
     * @throws \BlueCache\CacheException
68
     */
69 24
    protected function factoryStorage()
70
    {
71 24
        $config = ['cache_path' => $this->config['storage_directory']];
72 24
        $this->storage = new $this->config['storage_class']($config);
73
74 24
        if (!($this->storage instanceof StorageInterface)) {
75 2
            throw new CacheException('Incorrect storage type: ' . $this->config['storage_class']);
76
        }
77
78 24
        return $this;
79
    }
80
}
81