Completed
Push — 1.x ( 0f5ece...c9692e )
by Asao
36:16
created

BreadCrumb::getIterator()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 11
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 0
loc 11
rs 9.2
cc 4
eloc 6
nc 3
nop 0
1
<?php
2
namespace Tuum\Form\Components;
3
4
class BreadCrumb implements \IteratorAggregate
5
{
6
    const LINK = 'link';
7
    const NAME = 'name';
8
    const LAST = 'last';
9
10
    private $breads = [];
11
12
    /**
13
     * @var bool
14
     */
15
    private $isLast;
16
17
    /**
18
     * @param string $label
19
     * @param string $link
20
     */
21
    public function __construct($label, $link = null)
22
    {
23
        $this->breads[] = [
24
            self::NAME => $label,
25
            self::LINK => $link,
26
            self::LAST => true
27
        ];
28
    }
29
30
    /**
31
     * @param string $label
32
     * @param string|null $link
33
     * @return BreadCrumb
34
     */
35
    public static function forge($label, $link = null)
36
    {
37
        return new self($label, $link);
38
    }
39
40
    /**
41
     * @param string $label
42
     * @param string $link
43
     * @return $this
44
     */
45
    public function add($label, $link)
46
    {
47
        $this->breads[] = [self::NAME => $label, self::LINK => $link];
48
        return $this;
49
    }
50
51
    /**
52
     * @return array
53
     */
54
    public function getReversed()
55
    {
56
        $reverse = [];
57
        for($idx = count($this->breads) - 1; $idx >= 0; $idx--) {
58
            $reverse[] = $this->breads[$idx];
59
        }
60
        return $reverse;
61
    }
62
63
    /**
64
     * @return bool
65
     */
66
    public function isLast()
67
    {
68
        return $this->isLast === true
69
            ? true
70
            : false;
71
    }
72
73
    /**
74
     * @return \Generator
75
     */
76
    public function getIterator()
77
    {
78
        $bread = $this->getReversed();
79
80
        foreach($bread as $row) {
81
            if (isset($row[self::LAST]) && $row[self::LAST]) {
82
                $this->isLast = true;
83
            }
84
            yield $row[self::LINK] => $row[self::NAME];
85
        }
86
    }
87
}
88