MutableBlock::getAttribute()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 7
c 0
b 0
f 0
rs 9.4285
cc 2
eloc 4
nc 2
nop 1
1
<?php
2
declare(strict_types=1);
3
4
namespace Midnight\Block;
5
6
use Midnight\Block\Type\BlockTypeInterface;
7
use Ramsey\Uuid\Uuid;
8
9
class MutableBlock implements MutableBlockInterface
10
{
11
    /** @var string */
12
    private $id;
13
    /** @var string[] */
14
    private $attributes = [];
15
    /** @var BlockTypeInterface */
16
    private $blockType;
17
18
    /**
19
     * @param string[] $attributes
20
     */
21
    public function __construct(BlockTypeInterface $blockType, array $attributes)
22
    {
23
        $this->id = Uuid::uuid4()->toString();
24
        $this->blockType = $blockType;
25
        $blockType->validateAttributeValues($attributes);
26
        $this->attributes = $attributes;
27
    }
28
29
    public function getId(): string
30
    {
31
        return $this->id;
32
    }
33
34
    /**
35
     * @throws Exception\UnknownAttributeException
36
     */
37
    public function getAttribute(string $name): string
38
    {
39
        if (!isset($this->attributes[$name])) {
40
            throw Exception\UnknownAttributeException::fromName($name);
41
        }
42
        return $this->attributes[$name];
43
    }
44
45
    public function setAttribute(string $name, ?string $value): void
46
    {
47
        $this->blockType->validateAttributeValue($name, $value);
48
        if ($value === null) {
49
            unset($this->attributes['name']);
50
            return;
51
        }
52
        $this->attributes[$name] = $value;
53
    }
54
55
    public function getTypeName(): string
56
    {
57
        return $this->blockType->getName();
58
    }
59
}
60