Completed
Pull Request — master (#257)
by
unknown
01:57
created

ElementsAwareTrait::getElementsGenerator()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 2.032

Importance

Changes 0
Metric Value
dl 0
loc 8
ccs 4
cts 5
cp 0.8
rs 10
c 0
b 0
f 0
cc 2
nc 2
nop 0
crap 2.032
1
<?php declare(strict_types=1);
2
/*
3
 * This file is part of the feed-io package.
4
 *
5
 * (c) Alexandre Debril <[email protected]>
6
 *
7
 * For the full copyright and license information, please view the LICENSE
8
 * file that was distributed with this source code.
9
 */
10
11
namespace FeedIo\Feed;
12
13
use FeedIo\Feed\Node\Element;
14
use FeedIo\Feed\Node\ElementInterface;
15
use FeedIo\Feed\Node\ElementIterator;
16
17
trait ElementsAwareTrait
18
{
19
    /**
20
     * @var \ArrayIterator
21
     */
22
    protected $elements;
23
24
    /**
25
     * initialize the elements property before use
26
     */
27 3
    protected function initElements() : void
28
    {
29 3
        $this->elements = new \ArrayIterator();
30 3
    }
31
32
    /**
33
     * @return ElementInterface
34
     */
35 3
    public function newElement() : ElementInterface
36
    {
37 3
        return new Element();
38
    }
39
40
    /**
41
     * @param  string $name element name
42
     * @return ElementIterator
43
     */
44
    public function getElementIterator(string $name) : ElementIterator
45
    {
46
        return new ElementIterator($this->elements, $name);
47
    }
48
49
    /**
50
     * @param  string $name element name
51
     * @return boolean true if the element exists
52
     */
53
    public function hasElement(string $name) : bool
54
    {
55
        $filter = $this->getElementIterator($name);
56
57
        return $filter->count() > 0;
58
    }
59
60
    /**
61
     * @param  ElementInterface $element
62
     * @return $this
63
     */
64 3
    public function addElement(ElementInterface $element)
65
    {
66 3
        $this->elements->append($element);
67
68 3
        return $this;
69
    }
70
71
    /**
72
     * Returns all the item's optional elements
73
     * @return iterable
74
     */
75 1
    public function getAllElements() : iterable
76
    {
77 1
        return $this->elements;
78
    }
79
80
    /**
81
     * Returns the item's optional elements tag names
82
     * @return iterable
83
     */
84
    public function listElements() : iterable
85
    {
86
        foreach ($this->elements as $element) {
87
            yield ($element->getName());
88
        }
89
    }
90
91
    /**
92
     * @return \Generator
93
     */
94 1
    public function getElementsGenerator() : \Generator
95
    {
96 1
        $elements = $this->getAllElements();
97
98 1
        foreach ($elements as $element) {
99 1
            yield $element->getName() => $element->getValue();
100
        }
101
    }
102
}
103