Passed
Pull Request — master (#2285)
by Arnaud
10:02 queued 03:47
created

ContainerFactory::create()   A

Complexity

Conditions 4
Paths 6

Size

Total Lines 36
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 11
CRAP Score 4.3035

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 4
eloc 14
c 1
b 0
f 0
nc 6
nop 2
dl 0
loc 36
ccs 11
cts 15
cp 0.7332
crap 4.3035
rs 9.7998
1
<?php
2
3
/**
4
 * This file is part of Cecil.
5
 *
6
 * (c) Arnaud Ligny <[email protected]>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
declare(strict_types=1);
13
14
namespace Cecil\Container;
15
16
use Cecil\Config;
17
use DI\Container;
18
use DI\ContainerBuilder;
19
use Psr\Log\LoggerInterface;
20
21
/**
22
 * Factory to create and configure the dependency injection container.
23
 *
24
 * Uses PHP-DI for automatic autowiring and simple configuration.
25
 *
26
 * @see https://php-di.org/
27
 */
28
class ContainerFactory
29
{
30
    /**
31
     * Creates and configures the DI container with Cecil dependencies.
32
     *
33
     * @param Config          $config Application configuration
34
     * @param LoggerInterface $logger Application logger
35
     *
36
     * @return Container The configured and ready-to-use container
37
     */
38 1
    public static function create(
39
        Config $config,
40
        LoggerInterface $logger
41
    ): Container {
42 1
        $builder = new ContainerBuilder();
43
44
        // Enable PHP 8 attributes for dependency injection
45 1
        $builder->useAttributes(true);
46
47
        // Load dependencies configuration
48 1
        $definitionsFile = __DIR__ . '/../../config/dependencies.php';
49 1
        if (file_exists($definitionsFile)) {
50 1
            $builder->addDefinitions($definitionsFile);
51
        }
52
53
        // Enable compilation cache in production
54 1
        if (!$config->get('debug')) {
55
            $cacheDir = $config->getCachePath() . '/di';
56
            if (!is_dir($cacheDir)) {
57
                mkdir($cacheDir, 0755, true);
58
            }
59
            $builder->enableCompilation($cacheDir);
60
        }
61
62
        // Build the container
63 1
        $container = $builder->build();
64
65
        // Inject Config and Logger instances from Builder
66
        // These objects are already instantiated and configured
67 1
        $container->set(Config::class, $config);
68 1
        $container->set(LoggerInterface::class, $logger);
69
70
        // Note: Builder cannot be injected here because it creates the container itself
71
        // Services that need Builder receive it as a constructor parameter
72
73 1
        return $container;
74
    }
75
}
76