AttributeFactory::build()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 1
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 1
c 1
b 0
f 0
nc 1
nop 2
dl 0
loc 3
ccs 1
cts 1
cp 1
crap 1
rs 10
1
<?php
2
3
declare(strict_types=1);
4
5
namespace drupol\htmltag\Attribute;
6
7
use Exception;
8
use ReflectionClass;
9
10
use function in_array;
11
12
class AttributeFactory implements AttributeFactoryInterface
13
{
14
    /**
15
     * The classes registry.
16
     *
17
     * @var array<string, string>
18
     */
19
    public static $registry = [
20
        '*' => Attribute::class,
21
    ];
22 4
23
    public static function build(string $name, $value = null): AttributeInterface
24 4
    {
25
        return (new static())->getInstance($name, $value);
26
    }
27
28
    public function getInstance(string $name, $value = null): AttributeInterface
29
    {
30 32
        $attribute_classname = static::$registry[$name] ?? static::$registry['*'];
31
32 32
        if (!in_array(AttributeInterface::class, class_implements($attribute_classname), true)) {
33 1
            throw new Exception(
34 32
                sprintf(
35
                    'The class (%s) must implement the interface %s.',
36 32
                    $attribute_classname,
37 1
                    AttributeInterface::class
38 1
                )
39 1
            );
40 1
        }
41 1
42
        /** @var \drupol\htmltag\Attribute\AttributeInterface $attribute */
43
        $attribute = (new ReflectionClass($attribute_classname))
44
            ->newInstanceArgs([
45
                $name,
46
                $value,
47 31
            ]);
48 31
49 31
        return $attribute;
50 31
    }
51
}
52