Completed
Pull Request — master (#9)
by ANTHONIUS
02:26
created

ApplicationFactory::getConfiguration()   B

Complexity

Conditions 6
Paths 3

Size

Total Lines 35
Code Lines 25

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 35
rs 8.439
c 0
b 0
f 0
cc 6
eloc 25
nc 3
nop 0
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
87
        return $this;
88
    }
89
90
    /**
91
     * @return Container
92
     */
93
    public function getContainer(): Container
94
    {
95
        return $this->container;
96
    }
97
98
    /**
99
     * @param string $name
100
     *
101
     * @return bool
102
     */
103
    public function hasPlugin(string $name): bool
104
    {
105
        return array_key_exists($name, $this->plugins);
106
    }
107
108
    private function addAutoload(): void
109
    {
110
        $baseDir = Toolkit::getBaseDir();
111
        $autoloadFile = $baseDir.'/vendor/autoload.php';
112
113
        // ignore if files is already loaded in phar file
114
        if (
115
            is_file($autoloadFile) &&
116
            (false === strpos($autoloadFile, 'phar:///'))
117
        ) {
118
            include_once $autoloadFile;
119
        }
120
    }
121
122
    private function compileContainer(): void
123
    {
124
        $configs = $this->getConfiguration();
125
        //$paramaterBag = new ParameterBag();
126
        $builder = new ContainerBuilder();
127
        $this->processCoreConfig($configs, $builder);
128
        // processing core configuration
129
130
        /* @var Plugin $plugin */
131
        foreach ($this->plugins as $name => $plugin) {
132
            $pluginConfig = array_key_exists($name, $configs) ? $configs[$name] : array();
133
            $plugin->load($pluginConfig, $builder);
134
        }
135
136
        $cachePath = $this->getCachePathPrefix().'/container.php';
137
        $cache = new ConfigCache($cachePath, $this->debug);
138
        if (!$cache->isFresh() || 'dev' == $this->env) {
139
            $builder->addCompilerPass(new CommandPass());
140
            $builder->addCompilerPass(new ListenerPass());
141
            $builder->compile(true);
142
            $dumper = new PhpDumper($builder);
143
            $resources = $this->envFiles;
144
            array_walk($resources, function (&$item): void {
145
                $item = new FileResource($item);
146
            });
147
            $resources = array_merge($resources, $builder->getResources());
148
            $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

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