Passed
Push — master ( 5399ee...fe113d )
by Caen
03:32 queued 12s
created

MetadataBag   A

Complexity

Total Complexity 11

Size/Duplication

Total Lines 67
Duplicated Lines 0 %

Importance

Changes 7
Bugs 0 Features 0
Metric Value
eloc 27
c 7
b 0
f 0
dl 0
loc 67
rs 10
wmc 11

7 Methods

Rating   Name   Duplication   Size   Complexity  
A getPrefixedArray() 0 9 2
A render() 0 3 1
A get() 0 7 1
A add() 0 15 4
A addElement() 0 5 1
A addGenericElement() 0 5 1
A toHtml() 0 3 1
1
<?php
2
3
namespace Hyde\Framework\Modules\Metadata;
4
5
use Illuminate\Contracts\Support\Htmlable;
6
7
/**
8
 * Holds the metadata tags for a page or the site model.
9
 *
10
 * @see \Hyde\Framework\Testing\Feature\MetadataTest
11
 * @see \Hyde\Framework\Modules\Metadata\PageMetadataBag
12
 * @see \Hyde\Framework\Modules\Metadata\GlobalMetadataBag
13
 */
14
class MetadataBag implements Htmlable
15
{
16
    public array $links = [];
17
    public array $metadata = [];
18
    public array $properties = [];
19
    public array $generics = [];
20
21
    public function toHtml(): string
22
    {
23
        return $this->render();
24
    }
25
26
    public function render(): string
27
    {
28
        return implode("\n", $this->get());
29
    }
30
31
    public function get(): array
32
    {
33
        return array_merge(
34
            $this->getPrefixedArray('links'),
35
            $this->getPrefixedArray('metadata'),
36
            $this->getPrefixedArray('properties'),
37
            $this->getPrefixedArray('generics')
38
        );
39
    }
40
41
    public function add(MetadataElementContract|string $element): static
42
    {
43
        if ($element instanceof Models\LinkElement) {
44
            return $this->addElement('links', $element);
45
        }
46
47
        if ($element instanceof Models\MetadataElement) {
48
            return $this->addElement('metadata', $element);
49
        }
50
51
        if ($element instanceof Models\OpenGraphElement) {
52
            return $this->addElement('properties', $element);
53
        }
54
55
        return $this->addGenericElement($element);
56
    }
57
58
    protected function addElement(string $type, MetadataElementContract $element): MetadataBag
59
    {
60
        ($this->$type)[$element->uniqueKey()] = $element;
61
62
        return $this;
63
    }
64
65
    protected function addGenericElement(string $element): MetadataBag
66
    {
67
        $this->generics[] = $element;
68
69
        return $this;
70
    }
71
72
    protected function getPrefixedArray(string $type): array
73
    {
74
        $array = [];
75
76
        foreach ($this->{$type} as $key => $value) {
77
            $array["$type:$key"] = $value;
78
        }
79
80
        return $array;
81
    }
82
}
83