Completed
Push — master ( 8c1053...9934c8 )
by Woody
07:00
created

LoaderFactory::__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
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