AdapterFactory   A
last analyzed

Complexity

Total Complexity 7

Size/Duplication

Total Lines 53
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 7
eloc 20
dl 0
loc 53
rs 10
c 0
b 0
f 0

4 Methods

Rating   Name   Duplication   Size   Complexity  
A getClass() 0 10 2
A getAdapter() 0 4 1
A instance() 0 7 2
A registerAdapter() 0 11 2
1
<?php
2
3
namespace devtoolboxuk\storage\Adapter;
4
5
class AdapterFactory
6
{
7
    protected static $instance;
8
9
    protected $adapters = [
10
        'mysql' => 'devtoolboxuk\storage\Adapter\DoctrineAdapter'
11
    ];
12
13
    public static function instance()
14
    {
15
        if (!static::$instance) {
16
            static::$instance = new static();
17
        }
18
19
        return static::$instance;
20
    }
21
22
    public function registerAdapter($name, $class)
23
    {
24
        if (!is_subclass_of($class, 'devtoolboxuk\storage\AdapterInterface')) {
25
            throw new \RuntimeException(sprintf(
26
                'Adapter class "%s" must implement devtoolboxuk\\storage\\Adapter\\AdapterInterface',
27
                $class
28
            ));
29
        }
30
        $this->adapters[$name] = $class;
31
32
        return $this;
33
    }
34
35
    public function getAdapter($name, array $options)
36
    {
37
        $class = $this->getClass($name);
38
        return new $class($options);
39
    }
40
41
    /**
42
     * Get an adapter class by name.
43
     *
44
     * @throws \RuntimeException
45
     * @param  string $name
46
     * @return string
47
     */
48
    protected function getClass($name)
49
    {
50
        if (empty($this->adapters[$name])) {
51
            throw new \RuntimeException(sprintf(
52
                'Adapter "%s" has not been registered',
53
                $name
54
            ));
55
        }
56
57
        return $this->adapters[$name];
58
    }
59
}
60