Completed
Pull Request — master (#52)
by Tom
04:13
created

ReaderFactory   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 73
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 1

Importance

Changes 0
Metric Value
wmc 8
lcom 1
cbo 1
dl 0
loc 73
rs 10
c 0
b 0
f 0

4 Methods

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