|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
/** |
|
4
|
|
|
* eduVPN - End-user friendly VPN. |
|
5
|
|
|
* |
|
6
|
|
|
* Copyright: 2016-2017, The Commons Conservancy eduVPN Programme |
|
7
|
|
|
* SPDX-License-Identifier: AGPL-3.0+ |
|
8
|
|
|
*/ |
|
9
|
|
|
|
|
10
|
|
|
namespace SURFnet\VPN\Common; |
|
11
|
|
|
|
|
12
|
|
|
use SURFnet\VPN\Common\Exception\ConfigException; |
|
13
|
|
|
|
|
14
|
|
|
class Config |
|
15
|
|
|
{ |
|
16
|
|
|
/** @var array */ |
|
17
|
|
|
protected $configData; |
|
18
|
|
|
|
|
19
|
|
|
public function __construct(array $configData) |
|
20
|
|
|
{ |
|
21
|
|
|
$this->configData = $configData; |
|
22
|
|
|
$this->configData = array_merge(static::defaultConfig(), $configData); |
|
23
|
|
|
} |
|
24
|
|
|
|
|
25
|
|
|
public static function defaultConfig() |
|
26
|
|
|
{ |
|
27
|
|
|
return []; |
|
28
|
|
|
} |
|
29
|
|
|
|
|
30
|
|
|
public function hasSection($key) |
|
31
|
|
|
{ |
|
32
|
|
|
if (!array_key_exists($key, $this->configData)) { |
|
33
|
|
|
return false; |
|
34
|
|
|
} |
|
35
|
|
|
|
|
36
|
|
|
return is_array($this->configData[$key]); |
|
37
|
|
|
} |
|
38
|
|
|
|
|
39
|
|
|
public function getSection($key) |
|
40
|
|
|
{ |
|
41
|
|
|
if (false === $this->hasSection($key)) { |
|
42
|
|
|
throw new ConfigException(sprintf('"%s" is not a section', $key)); |
|
43
|
|
|
} |
|
44
|
|
|
|
|
45
|
|
|
// do not return the parent object if we were subclassed, but an actual |
|
46
|
|
|
// "Config" object to avoid copying in the defaults if set |
|
47
|
|
|
return new self($this->configData[$key]); |
|
48
|
|
|
} |
|
49
|
|
|
|
|
50
|
|
|
public function hasItem($key) |
|
51
|
|
|
{ |
|
52
|
|
|
return array_key_exists($key, $this->configData); |
|
53
|
|
|
} |
|
54
|
|
|
|
|
55
|
|
|
public function getItem($key) |
|
56
|
|
|
{ |
|
57
|
|
|
if (false === $this->hasItem($key)) { |
|
58
|
|
|
throw new ConfigException(sprintf('item "%s" not available', $key)); |
|
59
|
|
|
} |
|
60
|
|
|
|
|
61
|
|
|
return $this->configData[$key]; |
|
62
|
|
|
} |
|
63
|
|
|
|
|
64
|
|
|
public static function fromFile($configFile) |
|
65
|
|
|
{ |
|
66
|
|
|
if (false === @file_exists($configFile)) { |
|
67
|
|
|
throw new ConfigException(sprintf('unable to read "%s"', $configFile)); |
|
68
|
|
|
} |
|
69
|
|
|
|
|
70
|
|
|
return new static(require $configFile); |
|
71
|
|
|
} |
|
72
|
|
|
|
|
73
|
|
|
public function toArray() |
|
74
|
|
|
{ |
|
75
|
|
|
return $this->configData; |
|
76
|
|
|
} |
|
77
|
|
|
|
|
78
|
|
|
public static function toFile($configFile, array $configData, $mode = 0600) |
|
79
|
|
|
{ |
|
80
|
|
|
$fileData = sprintf('<?php return %s;', var_export($configData, true)); |
|
81
|
|
|
FileIO::writeFile($configFile, $fileData, $mode); |
|
82
|
|
|
} |
|
83
|
|
|
} |
|
84
|
|
|
|