Passed
Push — master ( d11c82...442210 )
by Evgenii
02:49
created

Breadcrumbs::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
eloc 1
c 1
b 0
f 1
dl 0
loc 3
rs 10
cc 1
nc 1
nop 1
1
<?php
2
3
4
namespace floor12\Breadcrumbs;
5
6
7
class Breadcrumbs
8
{
9
    const HTML_OL = '<ol itemscope itemtype="http://schema.org/BreadcrumbList" class="%s" id="%s">%s</ol>';
10
    const HTML_LI = '<li itemprop="itemListElement" itemscope itemtype="http://schema.org/ListItem">%s</li>';
11
    const HTML_A = '<a data-pjax="0" itemprop="item" href="%s">%s</a>';
12
    const HTML_SPAN = '<span itemprop="name">%s</span>';
13
    const HTML_META_POSITION = '<meta itemprop="position" content="%d">';
14
15
    protected $cssClass = 'f12-breadcrumbs';
16
    protected $mainId = 'f12-breadcrumbs';
17
    protected $elements = [];
18
19
    public function __construct(array $elements = [])
20
    {
21
        $this->elements = $elements;
22
    }
23
24
    public function addElement(string $name, string $url = null): self
25
    {
26
        $this->elements[$url] = $name;
27
        return $this;
28
    }
29
30
    public function getHtml(): ?string
31
    {
32
        if (\count($this->elements) === 0) {
33
            return null;
34
        }
35
        $renderedElements = [];
36
        $position = 0;
37
        foreach ($this->elements as $url => $name) {
38
            $position++;
39
            $element = $element = sprintf(self::HTML_SPAN, $name) . sprintf(self::HTML_META_POSITION, $position);
0 ignored issues
show
Unused Code introduced by
The assignment to $element is dead and can be removed.
Loading history...
40
            if (!is_numeric($url)) {
41
                $element = sprintf(self::HTML_A, $url, $element);
42
            }
43
            $renderedElements[] = sprintf(self::HTML_LI, $element);
44
        }
45
46
        return sprintf(
47
            self::HTML_OL,
48
            $this->cssClass,
49
            $this->mainId,
50
            implode($renderedElements)
51
        );
52
    }
53
54
    public function setCssClass(string $cssClass): self
55
    {
56
        $this->cssClass = $cssClass;
57
        return $this;
58
    }
59
60
    public function setMainId(string $mainId): self
61
    {
62
        $this->mainId = $mainId;
63
        return $this;
64
    }
65
}
66