ContainerFactory::createContainer()   A
last analyzed

Complexity

Conditions 3
Paths 3

Size

Total Lines 14

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 14
rs 9.7998
c 0
b 0
f 0
cc 3
nc 3
nop 2
1
<?php
2
3
declare(strict_types=1);
4
5
/*
6
 * This file is part of the ContextServiceExtension package.
7
 *
8
 * (c) Kamil Kokot <[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 FriendsOfBehat\ContextServiceExtension\ServiceContainer\Scenario;
15
16
use ProxyManager\Configuration as ProxyManagerConfiguration;
17
use Symfony\Bridge\ProxyManager\LazyProxy\Instantiator\RuntimeInstantiator;
18
use Symfony\Component\Config\FileLocator;
19
use Symfony\Component\Config\Loader\DelegatingLoader;
20
use Symfony\Component\Config\Loader\LoaderInterface;
21
use Symfony\Component\Config\Loader\LoaderResolver;
22
use Symfony\Component\DependencyInjection\ContainerBuilder;
23
use Symfony\Component\DependencyInjection\Loader;
24
25
/**
26
 * @internal
27
 */
28
final class ContainerFactory
29
{
30
    /**
31
     * @param string $basePath
32
     * @param array $importedFiles
33
     *
34
     * @return ContainerBuilder
35
     */
36
    public function createContainer(string $basePath, array $importedFiles = []): ContainerBuilder
37
    {
38
        $container = new ContainerBuilder();
39
40
        $this->enableSupportForLazyServicesIfPossible($container);
41
42
        $loader = $this->createLoader($container, $basePath);
43
        foreach ($importedFiles as $file) {
44
            $type = false !== mb_strpos($file, '*') ? 'glob' : null;
45
            $loader->load($file, $type);
46
        }
47
48
        return $container;
49
    }
50
51
    /**
52
     * @param ContainerBuilder $container
53
     * @param string $basePath
54
     *
55
     * @return LoaderInterface
56
     */
57
    private function createLoader(ContainerBuilder $container, string $basePath): LoaderInterface
58
    {
59
        $fileLocator = new FileLocator($basePath);
60
        $loader = new DelegatingLoader(new LoaderResolver([
61
            new Loader\XmlFileLoader($container, $fileLocator),
62
            new Loader\YamlFileLoader($container, $fileLocator),
63
            new Loader\PhpFileLoader($container, $fileLocator),
64
            new Loader\GlobFileLoader($container, $fileLocator)
65
        ]));
66
67
        return $loader;
68
    }
69
70
    /**
71
     * @param ContainerBuilder $container
72
     */
73
    private function enableSupportForLazyServicesIfPossible(ContainerBuilder $container): void
74
    {
75
        if (class_exists(ProxyManagerConfiguration::class) && class_exists(RuntimeInstantiator::class)) {
76
            $container->setProxyInstantiator(new RuntimeInstantiator());
77
        }
78
    }
79
}
80