|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace Teebot\Configuration; |
|
4
|
|
|
|
|
5
|
|
|
use Symfony\Component\Config\Definition\Processor; |
|
6
|
|
|
use Symfony\Component\Config\Exception\FileLoaderLoadException; |
|
7
|
|
|
use Symfony\Component\Config\FileLocator; |
|
8
|
|
|
use Symfony\Component\Yaml\Yaml; |
|
9
|
|
|
use Dotenv\Dotenv; |
|
10
|
|
|
use Dotenv\Exception\InvalidPathException; |
|
11
|
|
|
|
|
12
|
|
|
abstract class AbstractLoader |
|
13
|
|
|
{ |
|
14
|
|
|
const FILE_NAME = 'config%s.yml'; |
|
15
|
|
|
|
|
16
|
|
|
/** |
|
17
|
|
|
* @var string $path |
|
18
|
|
|
*/ |
|
19
|
|
|
protected $path; |
|
20
|
|
|
|
|
21
|
|
|
/** |
|
22
|
|
|
* @var string $fileName |
|
23
|
|
|
*/ |
|
24
|
|
|
protected $fileName; |
|
25
|
|
|
|
|
26
|
|
|
public function __construct($path) |
|
27
|
|
|
{ |
|
28
|
|
|
$this->initEnv($path); |
|
29
|
|
|
|
|
30
|
|
|
$this->path = $path; |
|
31
|
|
|
$this->fileName = $this->getFileName(); |
|
32
|
|
|
} |
|
33
|
|
|
|
|
34
|
|
|
public function load() |
|
35
|
|
|
{ |
|
36
|
|
|
$configFile = $this->getConfigFile(); |
|
37
|
|
|
$data = Yaml::parse(file_get_contents($configFile)); |
|
38
|
|
|
|
|
39
|
|
|
return $this->loadFromArray($data); |
|
40
|
|
|
} |
|
41
|
|
|
|
|
42
|
|
|
public function loadFromArray($configData) |
|
43
|
|
|
{ |
|
44
|
|
|
$config = $this->processConfig($configData); |
|
45
|
|
|
|
|
46
|
|
|
return $this->initContainer($config); |
|
47
|
|
|
} |
|
48
|
|
|
|
|
49
|
|
|
protected function getFileName() |
|
50
|
|
|
{ |
|
51
|
|
|
$env = getenv('ENV') ? '_' . getenv('ENV') : ''; |
|
52
|
|
|
|
|
53
|
|
|
return sprintf(static::FILE_NAME, $env); |
|
54
|
|
|
} |
|
55
|
|
|
|
|
56
|
|
|
protected function initEnv($path) |
|
57
|
|
|
{ |
|
58
|
|
|
try { |
|
59
|
|
|
$dotenv = new Dotenv($path); |
|
60
|
|
|
$dotenv->load(); |
|
61
|
|
|
} catch (InvalidPathException $e) { |
|
|
|
|
|
|
62
|
|
|
} |
|
63
|
|
|
} |
|
64
|
|
|
|
|
65
|
|
|
protected function getConfigFile() |
|
66
|
|
|
{ |
|
67
|
|
|
$locator = new FileLocator($this->path); |
|
68
|
|
|
$configFile = $locator->locate($this->fileName, null, true); |
|
69
|
|
|
|
|
70
|
|
|
if (!is_readable($configFile)) { |
|
71
|
|
|
throw new FileLoaderLoadException('Config file is not readable!'); |
|
72
|
|
|
} |
|
73
|
|
|
|
|
74
|
|
|
return $configFile; |
|
75
|
|
|
} |
|
76
|
|
|
|
|
77
|
|
|
protected function processConfig($data) |
|
78
|
|
|
{ |
|
79
|
|
|
$processor = new Processor(); |
|
80
|
|
|
$configuration = $this->getConfiguration(); |
|
81
|
|
|
$processedConfig = $processor->processConfiguration($configuration, $data); |
|
82
|
|
|
|
|
83
|
|
|
return $processedConfig; |
|
84
|
|
|
} |
|
85
|
|
|
|
|
86
|
|
|
abstract protected function getConfiguration(); |
|
87
|
|
|
|
|
88
|
|
|
abstract protected function initContainer($config); |
|
89
|
|
|
} |
|
90
|
|
|
|