Completed
Push — master ( 03d9da...2dac9a )
by Tom
13s
created

ReaderFactory::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 1
1
<?php
2
3
namespace TomPHP\ContainerConfigurator\FileReader;
4
5
use Assert\Assertion;
6
use InvalidArgumentException;
7
use TomPHP\ContainerConfigurator\Exception\UnknownFileTypeException;
8
9
final class ReaderFactory
10
{
11
    /**
12
     * @var string[]
13
     */
14
    private $config;
15
16
    /**
17
     * @var FileReader[]
18
     */
19
    private $readers = [];
20
21
    /**
22
     * @param array $config
23
     */
24
    public function __construct(array $config)
25
    {
26
        $this->config = $config;
27
    }
28
29
    /**
30
     * @param string $filename
31
     *
32
     * @return FileReader
33
     *
34
     * @throws InvalidArgumentException
35
     */
36
    public function create($filename)
37
    {
38
        Assertion::file($filename);
39
40
        $readerClass = $this->getReaderClass($filename);
41
42
        if (!isset($this->readers[$readerClass])) {
43
            $this->readers[$readerClass] = new $readerClass();
44
        }
45
46
        return $this->readers[$readerClass];
47
    }
48
49
    /**
50
     * @param string $filename
51
     *
52
     * @return string
53
     */
54
    private function getReaderClass($filename)
55
    {
56
        $readerClass = null;
57
58
        foreach ($this->config as $extension => $className) {
59
            if ($this->endsWith($filename, $extension)) {
60
                $readerClass = $className;
61
                break;
62
            }
63
        }
64
65
        if ($readerClass === null) {
66
            throw UnknownFileTypeException::fromFileExtension(
67
                $filename,
68
                array_keys($this->config)
69
            );
70
        }
71
72
        return $readerClass;
73
    }
74
75
    /**
76
     * @param string $haystack
77
     * @param string $needle
78
     *
79
     * @return bool
80
     */
81
    private function endsWith($haystack, $needle)
82
    {
83
        return $needle === substr($haystack, -strlen($needle));
84
    }
85
}
86