Completed
Push — master ( bf1c9e...8c1053 )
by Woody
13s
created

LoaderFactory   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 55
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 1

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
dl 0
loc 55
ccs 14
cts 14
cp 1
rs 10
c 0
b 0
f 0
wmc 6
lcom 1
cbo 1

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A forType() 0 8 2
A make() 0 12 3
1
<?php
2
3
namespace Northwoods\Config\Loader;
4
5
class LoaderFactory
6
{
7
    /**
8
     * @var array
9
     */
10
    private $loaders = [
11
        'php' => PhpLoader::class,
12
        'yaml' => YamlLoader::class,
13
    ];
14
15
    /**
16
     * @var LoaderInterface[]
17
     */
18
    private $instances = [];
19
20
    /**
21
     * @param array $loaders
22
     */
23 8
    public function __construct(array $loaders = [])
24
    {
25 8
        $this->loaders = array_replace($this->loaders, $loaders);
26 8
    }
27
28
    /**
29
     * @param string $extension
30
     * @return LoaderInterface
31
     */
32 8
    public function forType($extension)
33
    {
34 8
        if (empty($this->instances[$extension])) {
35 8
            $this->instances[$extension] = $this->make($this->loaders[$extension]);
36 6
        }
37
38 6
        return $this->instances[$extension];
39
    }
40
41
    /**
42
     * @param string $loader
43
     * @return LoaderInterface
44
     * @throws LoaderException
45
     *  If the requested loader cannot be created.
46
     */
47 8
    private function make($loader)
48
    {
49 8
        if (!is_a($loader, LoaderInterface::class, true)) {
50 1
            throw LoaderException::invalidLoader($loader);
51
        }
52
53 7
        if (!call_user_func([$loader, 'isSupported'])) {
54 1
            throw LoaderException::unsupportedLoader($loader);
55
        }
56
57 6
        return new $loader();
58
    }
59
}
60