|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace Storeman; |
|
4
|
|
|
|
|
5
|
|
|
use Storeman\Exception\ConfigurationException; |
|
6
|
|
|
use Storeman\Exception\Exception; |
|
7
|
|
|
use Symfony\Component\Validator\Validation; |
|
8
|
|
|
|
|
9
|
|
|
class ConfigurationFileReader |
|
10
|
|
|
{ |
|
11
|
|
|
public const CONFIG_CLASS = Configuration::class; |
|
12
|
|
|
|
|
13
|
|
|
|
|
14
|
|
|
public function getConfiguration(string $configurationFilePath): Configuration |
|
15
|
|
|
{ |
|
16
|
|
|
$configurationFilePath = PathUtils::getAbsolutePath($configurationFilePath); |
|
17
|
|
|
|
|
18
|
|
|
if (!is_file($configurationFilePath) || !is_readable($configurationFilePath)) |
|
19
|
|
|
{ |
|
20
|
|
|
throw new Exception("Configuration file {$configurationFilePath} is not a readable file."); |
|
21
|
|
|
} |
|
22
|
|
|
|
|
23
|
|
|
if (($json = file_get_contents($configurationFilePath)) === false) |
|
24
|
|
|
{ |
|
25
|
|
|
throw new Exception("Failed to read config file {$configurationFilePath}."); |
|
26
|
|
|
} |
|
27
|
|
|
|
|
28
|
|
|
if (($array = json_decode($json, true)) === null) |
|
29
|
|
|
{ |
|
30
|
|
|
throw new Exception("Malformed configuration file: {$configurationFilePath}."); |
|
31
|
|
|
} |
|
32
|
|
|
|
|
33
|
|
|
|
|
34
|
|
|
// default values |
|
35
|
|
|
$array = ArrayUtils::merge([ |
|
36
|
|
|
'path' => dirname($configurationFilePath), |
|
37
|
|
|
'identity' => sprintf('%s@%s', get_current_user(), gethostname()), |
|
38
|
|
|
], $array); |
|
39
|
|
|
|
|
40
|
|
|
|
|
41
|
|
|
try |
|
42
|
|
|
{ |
|
43
|
|
|
$className = static::CONFIG_CLASS; |
|
44
|
|
|
|
|
45
|
|
|
/** @var Configuration $configuration */ |
|
46
|
|
|
$configuration = new $className(); |
|
47
|
|
|
$configuration->exchangeArray($array); |
|
48
|
|
|
} |
|
49
|
|
|
catch (\InvalidArgumentException $exception) |
|
50
|
|
|
{ |
|
51
|
|
|
throw new ConfigurationException('', 0, $exception); |
|
52
|
|
|
} |
|
53
|
|
|
|
|
54
|
|
|
|
|
55
|
|
|
// validate configuration |
|
56
|
|
|
$validator = Validation::createValidatorBuilder() |
|
57
|
|
|
->addMethodMapping('loadValidatorMetadata') |
|
58
|
|
|
->getValidator(); |
|
59
|
|
|
|
|
60
|
|
|
$constraintViolations = $validator->validate($configuration); |
|
61
|
|
|
if ($constraintViolations->count()) |
|
62
|
|
|
{ |
|
63
|
|
|
$violation = $constraintViolations->get(0); |
|
64
|
|
|
|
|
65
|
|
|
throw new ConfigurationException("{$violation->getPropertyPath()} - {$violation->getMessage()}"); |
|
66
|
|
|
} |
|
67
|
|
|
|
|
68
|
|
|
return $configuration; |
|
69
|
|
|
} |
|
70
|
|
|
} |
|
71
|
|
|
|