ElementsAwareTrait::newElement()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 2
cts 2
cp 1
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 0
crap 1
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 129
    protected function initElements() : void
28
    {
29 129
        $this->elements = new \ArrayIterator();
30 129
    }
31
32
    /**
33
     * @return ElementInterface
34
     */
35 26
    public function newElement() : ElementInterface
36
    {
37 26
        return new Element();
38
    }
39
40
    /**
41
     * @param  string $name element name
42
     * @return ElementIterator
43
     */
44 17
    public function getElementIterator(string $name) : ElementIterator
45
    {
46 17
        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 4
    public function hasElement(string $name) : bool
54
    {
55 4
        $filter = $this->getElementIterator($name);
56
57 4
        return $filter->count() > 0;
58
    }
59
60
    /**
61
     * @param  ElementInterface $element
62
     * @return $this
63
     */
64 30
    public function addElement(ElementInterface $element)
65
    {
66 30
        $this->elements->append($element);
67
68 30
        return $this;
69
    }
70
71
    /**
72
     * Returns all the item's optional elements
73
     * @return iterable
74
     */
75 17
    public function getAllElements() : iterable
76
    {
77 17
        return $this->elements;
78
    }
79
80
    /**
81
     * Returns the item's optional elements tag names
82
     * @return iterable
83
     */
84 10
    public function listElements() : iterable
85
    {
86 10
        foreach ($this->elements as $element) {
87 4
            yield ($element->getName());
88
        }
89 10
    }
90
91
    /**
92
     * @return \Generator
93
     */
94 6
    public function getElementsGenerator() : \Generator
95
    {
96 6
        $elements = $this->getAllElements();
97
98 6
        foreach ($elements as $element) {
99 2
            yield $element->getName() => $element->getValue();
100
        }
101 5
    }
102
}
103