-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPluginConfigReader.php
62 lines (52 loc) · 1.5 KB
/
PluginConfigReader.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
<?php
declare(strict_types=1);
namespace GMTA\Velocita\Composer\Config;
use GMTA\Velocita\Composer\Exceptions\IOException;
use function array_key_exists;
use function file_get_contents;
use function is_array;
use function is_readable;
use function json_decode;
class PluginConfigReader
{
/**
* @param array{enabled?: bool, url?: string} $payload
*/
protected function getPluginConfigForPayload(array $payload): PluginConfig
{
$config = new PluginConfig();
if (array_key_exists('enabled', $payload)) {
$config->setEnabled($payload['enabled']);
}
if (array_key_exists('url', $payload)) {
$config->setURL($payload['url']);
}
return $config;
}
/**
* @throws IOException
*/
public function read(string $path): PluginConfig
{
if (!is_readable($path)) {
throw new IOException('Unable to read configuration');
}
$data = file_get_contents($path);
if ($data === false) {
throw new IOException('Failed to read configuration');
}
$data = json_decode($data, true);
if (!is_array($data)) {
throw new IOException('Could not decode configuration JSON');
}
return $this->getPluginConfigForPayload($data);
}
public function readOrNew(string $path): PluginConfig
{
try {
return $this->read($path);
} catch (IOException $e) {
return new PluginConfig();
}
}
}