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
|
|
|
|