AbstractFactory   A
last analyzed

Complexity

Total Complexity 8

Size/Duplication

Total Lines 57
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 8
eloc 19
c 1
b 0
f 0
dl 0
loc 57
ccs 14
cts 14
cp 1
rs 10

5 Methods

Rating   Name   Duplication   Size   Complexity  
A getProvidedDependency() 0 3 1
A getContainer() 0 9 2
A createContainerWithProvidedDependencies() 0 18 3
A singleton() 0 3 1
A resetCache() 0 3 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Gacela\Framework;
6
7
use Gacela\Framework\ClassResolver\Provider\DependencyProviderResolver;
8
use Gacela\Framework\ClassResolver\Provider\ProviderNotFoundException;
9
use Gacela\Framework\ClassResolver\Provider\ProviderResolver;
10
use Gacela\Framework\Config\Config;
11
use Gacela\Framework\Container\Container;
12
13
abstract class AbstractFactory
14
{
15
    use ConfigResolverAwareTrait;
16
17
    /** @var array<string,Container> */
18
    private static array $containers = [];
19
20
    /** @var array<string,mixed> */
21 58
    private array $instances = [];
22
23 58
    /**
24
     * @internal
25
     */
26 18
    public static function resetCache(): void
27
    {
28 18
        self::$containers = [];
29
    }
30
31 18
    protected function singleton(string $key, callable $creator): mixed
32
    {
33 18
        return $this->instances[$key] ??= $creator();
34
    }
35 18
36 10
    protected function getProvidedDependency(string $key): mixed
37
    {
38
        return $this->getContainer()->get($key);
39 17
    }
40
41
    private function getContainer(): Container
42 10
    {
43
        $containerKey = static::class;
44 10
45
        if (!isset(self::$containers[$containerKey])) {
46 10
            self::$containers[$containerKey] = $this->createContainerWithProvidedDependencies();
47 9
        }
48
49 9
        return self::$containers[$containerKey];
50
    }
51
52
    private function createContainerWithProvidedDependencies(): Container
53
    {
54
        $container = Container::withConfig(Config::getInstance());
55
56
        $resolver = (new ProviderResolver())->resolve($this);
57
        $resolver?->provideModuleDependencies($container);
58
59
        {
60
            // Temporal solution to keep BC with the AbstractDependencyProvider
61
            $dpResolver = (new DependencyProviderResolver())->resolve($this);
62
            $dpResolver?->provideModuleDependencies($container);
63
64
            if (!$resolver instanceof AbstractProvider && !$dpResolver instanceof AbstractProvider) {
0 ignored issues
show
introduced by
$dpResolver is always a sub-type of Gacela\Framework\AbstractProvider.
Loading history...
65
                throw new ProviderNotFoundException(static::class);
66
            }
67
        }
68
69
        return $container;
70
    }
71
}
72