Passed
Push — develop ( dbe6dd...9ad1aa )
by Michał
02:36
created

Common   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 65
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
dl 0
loc 65
ccs 23
cts 23
cp 1
rs 10
c 0
b 0
f 0
wmc 7

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 5 1
A registerStorage() 0 17 4
A factoryStorage() 0 10 2
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 25
    public function __construct(array $config = [])
36
    {
37 25
        $this->config = array_merge($this->config, $config);
38
39 25
        $this->registerStorage();
40 23
    }
41
42
    /**
43
     * @return $this
44
     * @throws \BlueCache\CacheException
45
     */
46 25
    protected function registerStorage()
47
    {
48 25
        switch (true) {
49 25
            case $this->config['storage_class'] instanceof StorageInterface:
50 2
                $this->storage = $this->config['storage_class'];
51 2
                break;
52
53 23
            case $this->config['storage_class'] === File::class:
54 23
            case is_string($this->config['storage_class']):
55 21
                $this->factoryStorage();
56 21
                break;
57
58 2
            default:
59 2
                throw new CacheException('Incorrect storage type: ' . get_class($this->storage));
60 2
        }
61
62 23
        return $this;
63
    }
64
65
    /**
66
     * @return $this
67
     * @throws \BlueCache\CacheException
68
     */
69 21
    protected function factoryStorage()
70
    {
71 21
        $config = ['cache_path' => $this->config['storage_directory']];
72 21
        $this->storage = new $this->config['storage_class']($config);
73
74 21
        if (!($this->storage instanceof StorageInterface)) {
75 2
            throw new CacheException('Incorrect storage type: ' . $this->config['storage_class']);
76
        }
77
78 21
        return $this;
79
    }
80
}
81