ReaderFactory::create()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 12
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

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