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