TagFactory::build()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
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 3
dl 0
loc 6
ccs 2
cts 2
cp 1
crap 1
rs 10
1
<?php
2
3
declare(strict_types=1);
4
5
namespace drupol\htmltag\Tag;
6
7
use drupol\htmltag\Attributes\AttributesFactory;
8
use drupol\htmltag\Attributes\AttributesInterface;
9
use Exception;
10
use ReflectionClass;
11
12
use function in_array;
13
14
class TagFactory implements TagFactoryInterface
15
{
16
    /**
17
     * The classes registry.
18
     *
19
     * @var array<string, string>
20
     */
21
    public static $registry = [
22
        'attributes_factory' => AttributesFactory::class,
23
        '!--' => Comment::class,
24
        '*' => Tag::class,
25
    ];
26
27 5
    public static function build(
28
        string $name,
29
        array $attributes = [],
30
        $content = null
31
    ): TagInterface {
32 5
        return (new static())->getInstance($name, $attributes, $content);
33
    }
34
35
    public function getInstance(
36
        string $name,
37
        array $attributes = [],
38 5
        $content = null
39
    ): TagInterface {
40
        $attributes_factory_classname = static::$registry['attributes_factory'];
41
42
        /** @var AttributesInterface $attributes */
43 5
        $attributes = $attributes_factory_classname::build($attributes);
44
45
        $tag_classname = static::$registry[$name] ?? static::$registry['*'];
46 5
47
        if (!in_array(TagInterface::class, class_implements($tag_classname), true)) {
48 5
            throw new Exception(
49 3
                sprintf(
50 5
                    'The class (%s) must implement the interface %s.',
51
                    $tag_classname,
52 5
                    TagInterface::class
53 1
                )
54 1
            );
55 1
        }
56 1
57 1
        /** @var \drupol\htmltag\Tag\TagInterface $tag */
58
        $tag = (new ReflectionClass($tag_classname))
59
            ->newInstanceArgs([
60
                $attributes,
61
                $name,
62
                $content,
63 4
            ]);
64 4
65 4
        return $tag;
66 4
    }
67
}
68