EnumAbstractFactory   A
last analyzed

Complexity

Total Complexity 8

Size/Duplication

Total Lines 46
Duplicated Lines 0 %

Test Coverage

Coverage 0%

Importance

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

3 Methods

Rating   Name   Duplication   Size   Complexity  
A canCreate() 0 5 1
A getClass() 0 14 4
A __invoke() 0 13 3
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Ecodev\Felix\Api\Enum;
6
7
use BackedEnum;
8
use Exception;
9
use Laminas\ServiceManager\Factory\AbstractFactoryInterface;
10
use Psr\Container\ContainerInterface;
11
12
/**
13
 * Will create GraphQL Enums for a short name or a FQCN of a PHP native backed enum.
14
 *
15
 * The PHP enum must live in `Application\Enum` namespace.
16
 */
17
class EnumAbstractFactory implements AbstractFactoryInterface
18
{
19
    /**
20
     * @var array<class-string<BackedEnum>, PhpEnumType>
21
     */
22
    private array $cache = [];
23
24
    public function canCreate(ContainerInterface $container, $requestedName)
25
    {
26
        $class = $this->getClass($requestedName);
27
28
        return (bool) $class;
29
    }
30
31
    public function __invoke(ContainerInterface $container, $requestedName, ?array $options = null)
32
    {
33
        $class = $this->getClass($requestedName);
34
        if (!$class) {
35
            throw new Exception('Cannot create a PhpEnumType for a name not matching a backed enum: ' . $requestedName);
36
        }
37
38
        // Share the same instance between short name and FQCN
39
        if (!array_key_exists($class, $this->cache)) {
40
            $this->cache[$class] = new PhpEnumType($class);
41
        }
42
43
        return $this->cache[$class];
44
    }
45
46
    /**
47
     * @return null|class-string<BackedEnum>
48
     */
49
    private function getClass(string $requestedName): ?string
50
    {
51
        $possibilities = [
52
            $requestedName,
53
            'Application\Enum\\' . $requestedName,
54
        ];
55
56
        foreach ($possibilities as $class) {
57
            if (class_exists($class) && is_a($class, BackedEnum::class, true)) {
58
                return $class;
59
            }
60
        }
61
62
        return null;
63
    }
64
}
65