NodeIterator::getIterator()   A
last analyzed

Complexity

Conditions 5
Paths 4

Size

Total Lines 18
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 11
CRAP Score 5

Importance

Changes 0
Metric Value
cc 5
eloc 10
nc 4
nop 0
dl 0
loc 18
ccs 11
cts 11
cp 1
crap 5
rs 9.6111
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
/*
6
 * This file is part of the league/commonmark package.
7
 *
8
 * (c) Colin O'Dell <[email protected]>
9
 *
10
 * For the full copyright and license information, please view the LICENSE
11
 * file that was distributed with this source code.
12
 */
13
14
namespace League\CommonMark\Node;
15
16
use League\CommonMark\Node\Block\AbstractBlock;
17
18
/**
19
 * @implements \IteratorAggregate<int, Node>
20
 */
21
final class NodeIterator implements \IteratorAggregate
22
{
23
    public const FLAG_BLOCKS_ONLY = 1;
24
25
    private Node $node;
26
    private bool $blocksOnly;
27
28 548
    public function __construct(Node $node, int $flags = 0)
29
    {
30 548
        $this->node       = $node;
31 548
        $this->blocksOnly = ($flags & self::FLAG_BLOCKS_ONLY) === self::FLAG_BLOCKS_ONLY;
32
    }
33
34
    /**
35
     * @return \Generator<int, Node>
36
     */
37 548
    public function getIterator(): \Generator
38
    {
39 548
        $stack = [$this->node];
40 548
        $index = 0;
41
42 548
        while ($stack) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $stack of type array<integer,League\CommonMark\Node\Node> is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
43 548
            $node = \array_pop($stack);
44
45 548
            yield $index++ => $node;
46
47
            // Push all children onto the stack in reverse order
48 546
            $child = $node->lastChild();
49 546
            while ($child !== null) {
50 536
                if (! $this->blocksOnly || $child instanceof AbstractBlock) {
51 536
                    $stack[] = $child;
52
                }
53
54 536
                $child = $child->previous();
55
            }
56
        }
57
    }
58
}
59