Passed
Push — analysis-A7yJ5k ( c97a2e )
by Arnaud
10:56 queued 05:11
created

ContainerFactory::create()   A

Complexity

Conditions 4
Paths 6

Size

Total Lines 33
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

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