Passed
Push — add-with-all-to-modules-list ( 82b81d...0edb38 )
by Chema
03:40
created

FactoryResolverAwareTrait   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 32
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 3
Bugs 0 Features 0
Metric Value
eloc 11
c 3
b 0
f 0
dl 0
loc 32
ccs 13
cts 13
cp 1
rs 10
wmc 6

4 Methods

Rating   Name   Duplication   Size   Complexity  
A __callStatic() 0 7 2
A resetCache() 0 3 1
A doGetFactory() 0 4 1
A __call() 0 7 2
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Gacela\Framework;
6
7
use Gacela\Framework\ClassResolver\Factory\FactoryResolver;
8
use RuntimeException;
9
10
/**
11
 * The `__callStatic` and `__call` methods allow defining `getFactory` as static and non-static methods.
12
 *
13
 * @psalm-suppress MethodSignatureMismatch
14
 *
15
 * @method static AbstractFactory getFactory()
16
 * @method AbstractFactory getFactory()
17
 */
18
trait FactoryResolverAwareTrait
19
{
20
    /** @var array<string, AbstractFactory> */
21
    private static array $factories = [];
22
23 4
    public static function __callStatic(string $name = '', array $arguments = [])
24
    {
25 4
        if ($name === 'getFactory') {
26 2
            return self::doGetFactory();
27
        }
28
29 2
        throw new RuntimeException("Method unknown: '{$name}'");
30
    }
31
32 63
    public function __call(string $name = '', array $arguments = [])
33
    {
34 63
        if ($name === 'getFactory') {
35 62
            return self::doGetFactory();
36
        }
37
38 1
        throw new RuntimeException("Method unknown: '{$name}'");
39
    }
40
41 59
    public static function resetCache(): void
42
    {
43 59
        self::$factories = [];
44
    }
45
46 64
    private static function doGetFactory(): AbstractFactory
47
    {
48 64
        return self::$factories[static::class]
49 64
            ??= (new FactoryResolver())->resolve(static::class);
50
    }
51
}
52