Completed
Pull Request — master (#9)
by ANTHONIUS
03:17
created

ApplicationFactory::processCoreConfig()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 13
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 13
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 9
nc 2
nop 2
1
<?php
2
3
declare(strict_types=1);
4
5
/*
6
 * This file is part of the dotfiles project.
7
 *
8
 *     (c) Anthonius Munthi <[email protected]>
9
 *
10
 * For the full copyright and license information, please view the LICENSE
11
 * file that was distributed with this source code.
12
 */
13
14
namespace Dotfiles\Core;
15
16
use Composer\Autoload\ClassLoader;
17
use Dotfiles\Core\DI\Compiler\CommandPass;
18
use Dotfiles\Core\DI\Compiler\ListenerPass;
19
use Dotfiles\Core\DI\Parameters;
20
use Dotfiles\Core\Util\Toolkit;
21
use Symfony\Component\Config\ConfigCache;
22
use Symfony\Component\Config\Definition\Processor;
23
use Symfony\Component\Config\FileLocator;
24
use Symfony\Component\Config\Resource\FileResource;
25
use Symfony\Component\DependencyInjection\Container;
0 ignored issues
show
Bug introduced by
This use statement conflicts with another class in this namespace, Dotfiles\Core\Container. Consider defining an alias.

Let?s assume that you have a directory layout like this:

.
|-- OtherDir
|   |-- Bar.php
|   `-- Foo.php
`-- SomeDir
    `-- Foo.php

and let?s assume the following content of Bar.php:

// Bar.php
namespace OtherDir;

use SomeDir\Foo; // This now conflicts the class OtherDir\Foo

If both files OtherDir/Foo.php and SomeDir/Foo.php are loaded in the same runtime, you will see a PHP error such as the following:

PHP Fatal error:  Cannot use SomeDir\Foo as Foo because the name is already in use in OtherDir/Foo.php

However, as OtherDir/Foo.php does not necessarily have to be loaded and the error is only triggered if it is loaded before OtherDir/Bar.php, this problem might go unnoticed for a while. In order to prevent this error from surfacing, you must import the namespace with a different alias:

// Bar.php
namespace OtherDir;

use SomeDir\Foo as SomeDirFoo; // There is no conflict anymore.
Loading history...
26
use Symfony\Component\DependencyInjection\ContainerBuilder;
27
use Symfony\Component\DependencyInjection\Dumper\PhpDumper;
28
use Symfony\Component\DependencyInjection\Loader\YamlFileLoader;
29
use Symfony\Component\Dotenv\Dotenv;
30
use Symfony\Component\Finder\Finder;
31
use Symfony\Component\Finder\SplFileInfo;
32
use Symfony\Component\Yaml\Yaml;
33
34
class ApplicationFactory
35
{
36
    /**
37
     * @var Container
38
     */
39
    private $container;
40
41
    /**
42
     * @var bool
43
     */
44
    private $debug = false;
45
46
    /**
47
     * @var string
48
     */
49
    private $env;
50
51
    /**
52
     * @var array
53
     */
54
    private $envFiles = array();
55
56
    /**
57
     * @var Plugin[]
58
     */
59
    private $plugins = array();
60
61
    public function __construct()
62
    {
63
        $files = array(__DIR__.'/Resources/default.env');
64
65
        // $PWD/.env always win
66
        $cwd = getcwd();
67
        if (is_file($file = $cwd.'/.env.dist')) {
68
            $files[] = $file;
69
        }
70
        if (is_file($file = $cwd.'/.env')) {
71
            $files[] = $file;
72
        }
73
74
        $this->envFiles = $files;
75
    }
76
77
    /**
78
     * @return $this
79
     */
80
    public function boot(): self
81
    {
82
        $this->loadDotEnv();
83
        $this->addAutoload();
84
        $this->loadPlugins();
85
        $this->compileContainer();
86
        $this->ensureDir();
87
88
        return $this;
89
    }
90
91
    /**
92
     * @return Container
93
     */
94
    public function getContainer(): Container
95
    {
96
        return $this->container;
97
    }
98
99
    /**
100
     * @param string $name
101
     *
102
     * @return bool
103
     */
104
    public function hasPlugin(string $name): bool
105
    {
106
        return array_key_exists($name, $this->plugins);
107
    }
108
109
    protected function compileContainer(): void
110
    {
111
        $configs = $this->getConfiguration();
112
        $builder = new ContainerBuilder();
113
        $this->processCoreConfig($configs, $builder);
114
        // processing core configuration
115
116
        /* @var Plugin $plugin */
117
        foreach ($this->plugins as $name => $plugin) {
118
            $pluginConfig[$name] = array_key_exists($name, $configs) ? $configs[$name] : array();
119
120
            $plugin->load($pluginConfig, $builder);
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $pluginConfig seems to be defined later in this foreach loop on line 118. Are you sure it is defined here?
Loading history...
121
        }
122
123
        $cachePath = $this->getCachePathPrefix().'/container.php';
124
        $cache = new ConfigCache($cachePath, $this->debug);
125
126
        // always compile container in dev environment
127
        if (!$cache->isFresh() || 'dev' === $this->env) {
128
            $builder->addCompilerPass(new CommandPass());
129
            $builder->addCompilerPass(new ListenerPass());
130
            $builder->compile(true);
131
            $dumper = new PhpDumper($builder);
132
            $resources = $this->envFiles;
133
            array_walk($resources, function (&$item): void {
134
                $item = new FileResource($item);
135
            });
136
            $resources = array_merge($resources, $builder->getResources());
137
            $cache->write($dumper->dump(array('class' => 'CachedContainer')), $resources);
0 ignored issues
show
Bug introduced by
It seems like $dumper->dump(array('cla... => 'CachedContainer')) can also be of type array; however, parameter $content of Symfony\Component\Config...kerConfigCache::write() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

137
            $cache->write(/** @scrutinizer ignore-type */ $dumper->dump(array('class' => 'CachedContainer')), $resources);
Loading history...
138
        }
139
        if (!class_exists('CachedContainer')) {
140
            include_once $cachePath;
141
        }
142
        $container = new \CachedContainer();
0 ignored issues
show
Bug introduced by
The type CachedContainer was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
143
144
        $parameters = new Parameters();
145
        $parameters->setConfigs($container->getParameterBag()->all());
146
        $container->set('dotfiles.parameters', $parameters);
147
        $this->container = $container;
148
    }
149
150
    private function addAutoload(): void
151
    {
152
        $baseDir = getenv('DOTFILES_BACKUP_DIR');
153
        $autoloadFile = $baseDir.'/vendor/autoload.php';
154
155
        // ignore if files is already loaded in phar file
156
        if (
157
            is_file($autoloadFile)
158
        ) {
159
            include_once $autoloadFile;
160
        }
161
    }
162
163
    private function ensureDir(): void
164
    {
165
        /* @var Parameters $parameters */
166
        $parameters = $this->container->get('dotfiles.parameters');
167
        Toolkit::ensureDir($parameters->get('dotfiles.install_dir'));
168
        Toolkit::ensureDir($parameters->get('dotfiles.bin_dir'));
169
        Toolkit::ensureDir($parameters->get('dotfiles.vendor_dir'));
170
    }
171
172
    private function getCachePathPrefix()
173
    {
174
        // using argv command to differ each dotfiles executable file
175
        global $argv;
176
        $command = $argv[0];
177
        $cacheDir = getenv('DOTFILES_CACHE_DIR');
178
        $env = getenv('DOTFILES_ENV');
179
180
        return $cacheDir.DIRECTORY_SEPARATOR.crc32($command).DIRECTORY_SEPARATOR.$env;
181
    }
182
183
    private function getConfiguration()
184
    {
185
        $configDir = getenv('DOTFILES_CONFIG_DIR');
186
        if (!is_dir($configDir)) {
187
            return array();
188
        }
189
        $cacheFile = $this->getCachePathPrefix().'/config.php';
190
        $cache = new ConfigCache($cacheFile, $this->debug);
191
        if (!$cache->isFresh() || 'dev' === $this->env) {
192
            $finder = Finder::create()
193
                ->name('*.yaml')
194
                ->name('*.yml')
195
                ->in($configDir)
196
            ;
197
            $configs = array();
198
            $configFiles = array();
199
            /* @var SplFileInfo $file */
200
            foreach ($finder->files() as $file) {
201
                $parsed = Yaml::parseFile($file->getRealPath());
202
                if (is_array($parsed)) {
203
                    $configs = array_merge_recursive($configs, $parsed);
204
                }
205
                $configFiles[] = new FileResource($file->getRealPath());
206
            }
207
            $template = "<?php\n/* ParameterBag Cache File Generated at %s */\nreturn %s;\n";
208
            $time = new \DateTime();
209
            $contents = sprintf(
210
                $template,
211
                $time->format('Y-m-d H:i:s'),
212
                var_export($configs, true)
213
            );
214
            $cache->write($contents, $configFiles);
215
        }
216
217
        return include $cacheFile;
218
    }
219
220
    /**
221
     * Load available plugins directory.
222
     *
223
     * @return array
224
     */
225
    private function loadDirectoryFromAutoloader()
226
    {
227
        $spl = spl_autoload_functions();
228
229
        $dirs = array();
230
        foreach ($spl as $item) {
231
            $object = $item[0];
232
            if (!$object instanceof ClassLoader) {
233
                continue;
234
            }
235
            $temp = array_merge($object->getPrefixes(), $object->getPrefixesPsr4());
236
            foreach ($temp as $name => $dir) {
237
                if (false === strpos($name, 'Dotfiles')) {
238
                    continue;
239
                }
240
                foreach ($dir as $num => $path) {
241
                    $path = realpath($path);
242
                    if ($path && is_dir($path) && !in_array($path, $dirs)) {
243
                        $dirs[] = $path;
244
                    }
245
                }
246
            }
247
        }
248
249
        return $dirs;
250
    }
251
252
    private function loadDotEnv(): void
253
    {
254
        global $argv;
255
        // set temp dir based on OS
256
        putenv('DOTFILES_TEMP_DIR='.sys_get_temp_dir().'/dotfiles');
257
        $dryRun = in_array('--dry-run', $argv) ? true : false;
258
        putenv('DOTFILES_DRY_RUN='.$dryRun);
259
260
        $files = $this->envFiles;
261
        $env = new Dotenv();
262
        if (count($files) > 0) {
263
            call_user_func_array(array($env, 'load'), $files);
264
        }
265
266
        $dev = getenv('DOTFILES_ENV');
267
        if (
268
            'dev' !== $dev && is_file($file = getenv('HOME').'/.dotfiles_profile')) {
269
            $env->load($file);
270
        }
271
272
        $this->debug = (bool) getenv('DOTFILES_DEBUG');
273
        $this->env = getenv('DOTFILES_ENV');
274
275
        $homeDir = getenv('DOTFILES_HOME_DIR');
276
        $backupDir = getenv('DOTFILES_BACKUP_DIR');
277
        if (!getenv('DOTFILES_INSTALL_DIR')) {
278
            putenv('DOTFILES_INSTALL_DIR='.$homeDir.'/.dotfiles');
279
        }
280
281
        if (!getenv('DOTFILES_CONFIG_DIR')) {
282
            putenv('DOTFILES_CONFIG_DIR='.getenv('DOTFILES_BACKUP_DIR').'/config');
283
        }
284
285
        if (!getenv('DOTFILES_CACHE_DIR')) {
286
            putenv('DOTFILES_CACHE_DIR='.$backupDir.'/var/cache');
287
        }
288
        if (!getenv('DOTFILES_LOG_DIR')) {
289
            putenv('DOTFILES_LOG_DIR='.$backupDir.'/var/log');
290
        }
291
    }
292
293
    /**
294
     * Load available plugins.
295
     */
296
    private function loadPlugins(): void
297
    {
298
        $finder = Finder::create();
299
        $finder
300
            ->name('*Plugin.php')
301
        ;
302
        if (is_dir($dir = __DIR__.'/../Plugins')) {
303
            $finder->in(__DIR__.'/../Plugins');
304
        }
305
        $dirs = $this->loadDirectoryFromAutoloader();
306
        $finder->in($dirs);
307
        foreach ($finder->files() as $file) {
308
            $namespace = 'Dotfiles\\Plugins\\'.str_replace('Plugin.php', '', $file->getFileName());
309
            $className = $namespace.'\\'.str_replace('.php', '', $file->getFileName());
310
            if (class_exists($className)) {
311
                /* @var \Dotfiles\Core\Plugin $plugin */
312
                $plugin = new $className();
313
                $this->registerPlugin($plugin);
314
            }
315
        }
316
    }
317
318
    private function processCoreConfig(array $configs, ContainerBuilder $builder): void
319
    {
320
        $dotfileConfig = array_key_exists('dotfiles', $configs) ? $configs['dotfiles'] : array();
321
        $processor = new Processor();
322
        $parameters = $processor->processConfiguration(new Configuration(), $dotfileConfig);
323
        $parameters = array('dotfiles' => $parameters);
324
        Toolkit::flattenArray($parameters);
325
326
        $builder->getParameterBag()->add($parameters);
327
328
        $locator = new FileLocator(__DIR__.'/Resources/config');
329
        $loader = new YamlFileLoader($builder, $locator);
330
        $loader->load('services.yaml');
331
    }
332
333
    /**
334
     * Register plugin.
335
     *
336
     * @param Plugin $plugin
337
     */
338
    private function registerPlugin(Plugin $plugin): void
339
    {
340
        if ($this->hasPlugin($plugin->getName())) {
341
            return;
342
        }
343
344
        $this->plugins[$plugin->getName()] = $plugin;
345
    }
346
}
347