1: <?php
2: 3: 4: 5: 6: 7: 8: 9:
10:
11: namespace Autarky\Config;
12:
13: use Autarky\Config\Loaders\CachingYamlFileLoader;
14: use Autarky\Config\Loaders\YamlFileLoader;
15: use Autarky\Container\ContainerInterface;
16: use Autarky\Files\PathResolver;
17: use Autarky\Providers\AbstractProvider;
18:
19: 20: 21: 22: 23:
24: class ConfigProvider extends AbstractProvider
25: {
26: 27: 28: 29: 30:
31: protected $configPath;
32:
33: 34: 35:
36: public function __construct($configPath)
37: {
38: $this->configPath = $configPath;
39: }
40:
41: 42: 43:
44: public function register()
45: {
46: $this->app->setConfig($store = $this->getConfigStore());
47:
48: if ($store->has('app.configurators')) {
49: foreach ($store->get('app.configurators') as $configurator) {
50: $this->app->config($configurator);
51: }
52: }
53: }
54:
55: protected function getConfigStore()
56: {
57: $dic = $this->app->getContainer();
58:
59:
60: $loaderFactory = new LoaderFactory($dic);
61: $dic->instance('Autarky\Config\Loaders\LoaderFactory', $loaderFactory);
62:
63:
64: $store = new FileStore(
65: new PathResolver($this->configPath),
66: $loaderFactory,
67: $this->app->getEnvironment()
68: );
69: $dic->instance('Autarky\Config\FileStore', $store);
70: $dic->alias('Autarky\Config\FileStore', 'Autarky\Config\ConfigInterface');
71:
72:
73: $dic->share('Autarky\Config\Loaders\PhpFileLoader');
74: $loaderFactory->addLoader('.php', 'Autarky\Config\Loaders\PhpFileLoader');
75:
76:
77: $dic->define('Autarky\Config\Loaders\YamlFileLoader', function(ContainerInterface $dic) {
78: return new YamlFileLoader(
79: $dic->resolve('Symfony\Component\Yaml\Parser')
80: );
81: });
82: $dic->share('Autarky\Config\Loaders\YamlFileLoader');
83:
84: $yamlCachePath = $this->getYamlCachePath($store);
85: $dic->define('Autarky\Config\Loaders\CachingYamlFileLoader', function(ContainerInterface $dic) use($yamlCachePath) {
86: return new CachingYamlFileLoader(
87: $dic->resolve('Symfony\Component\Yaml\Parser'),
88: $yamlCachePath
89: );
90: });
91: $dic->share('Autarky\Config\Loaders\CachingYamlFileLoader');
92:
93: $loader = $yamlCachePath
94: ? 'Autarky\Config\Loaders\CachingYamlFileLoader'
95: : 'Autarky\Config\Loaders\YamlFileLoader';
96: $loaderFactory->addLoader(['.yml', '.yaml'], $loader);
97:
98:
99: return $store;
100: }
101:
102: protected function getYamlCachePath(ConfigInterface $config = null)
103: {
104: if (file_exists($this->configPath.'/path.yml')) {
105: throw new \RuntimeException("The 'path' config file cannot be YAML when using the caching YAML config file loader.");
106: }
107:
108: $config = $config ?: $this->app->getConfig();
109:
110: $path = $config->get('path.storage').'/yaml';
111:
112: if (is_dir($path) && is_writable($path)) {
113: return $path;
114: }
115:
116: return null;
117: }
118: }
119: