TagFactory   A
last analyzed

Complexity

Total Complexity 3

Size/Duplication

Total Lines 52
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 4
Bugs 0 Features 0
Metric Value
eloc 20
c 4
b 0
f 0
dl 0
loc 52
ccs 17
cts 17
cp 1
rs 10
wmc 3

2 Methods

Rating   Name   Duplication   Size   Complexity  
A build() 0 6 1
A getInstance() 0 31 2
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