Passed
Push — master ( 6717a8...7f2250 )
by Andrew
02:30
created

Config   A

Complexity

Total Complexity 10

Size/Duplication

Total Lines 52
Duplicated Lines 0 %

Test Coverage

Coverage 84.21%

Importance

Changes 1
Bugs 0 Features 1
Metric Value
wmc 10
eloc 25
c 1
b 0
f 1
dl 0
loc 52
ccs 16
cts 19
cp 0.8421
rs 10

3 Methods

Rating   Name   Duplication   Size   Complexity  
A createDictionary() 0 22 5
A getDictionary() 0 3 1
A __construct() 0 7 4
1
<?php
2
3
declare(strict_types=1);
4
5
namespace KRDigital\NamesDetector\Config;
6
7
use KRDigital\NamesDetector\Exception\InvalidDictionarySourceException;
8
9
class Config implements ConfigInterface
10
{
11
    private const EXTENSION_JSON = 'json';
12
13
    private const EXTENSION_PHP = 'php';
14
15
    private const ALLOWED_EXTENSIONS = [
16
        self::EXTENSION_JSON,
17
        self::EXTENSION_PHP,
18
    ];
19
20
    /**
21
     * @var DictionaryInterface
22
     */
23
    protected $dictionary;
24
25 4
    public function __construct(string $dictionaryPath, array $dictionary = [])
26
    {
27 4
        if (empty($dictionary) && !\file_exists($dictionaryPath)) {
28 1
            throw new InvalidDictionarySourceException(\sprintf('Path %s is invalid', $dictionaryPath));
29
        }
30
31 3
        $this->dictionary = !empty($dictionary) ? $dictionary : $this->createDictionary($dictionaryPath);
32 2
    }
33
34 2
    public function getDictionary(): DictionaryInterface
35
    {
36 2
        return $this->dictionary;
37
    }
38
39 3
    protected function createDictionary(string $dictionaryPath): DictionaryInterface
40
    {
41 3
        $dictionaryExtension = \pathinfo($dictionaryPath, PATHINFO_EXTENSION);
42
43
        switch ($dictionaryExtension) {
44 3
            case self::EXTENSION_PHP:
45
                try {
46 1
                    $data = include $dictionaryPath;
47
48 1
                    return Dictionary::fromArray($data);
49
                } catch (\ParseError $error) {
50
                    throw new InvalidDictionarySourceException('Dictionary php file is invalid');
51
                }
52 2
            case self::EXTENSION_JSON:
53
                // JSON_THROW_ON_ERROR polyfill
54 1
                if (null === $data = \json_decode(\file_get_contents($dictionaryPath), true)) {
55
                    throw new InvalidDictionarySourceException('Dictionary json file is invalid');
56
                }
57
58 1
                return Dictionary::fromArray($data);
59
            default:
60 1
                throw new InvalidDictionarySourceException(\sprintf('Extension %s is not valid, allowed extensions are %s', $dictionaryExtension, \implode(', ', self::ALLOWED_EXTENSIONS)));
61
        }
62
    }
63
}
64