Passed
Pull Request — master (#108)
by Marco
02:35
created

Changes::getIterator()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 13
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 6
nc 4
nop 0
dl 0
loc 13
rs 10
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Roave\BackwardCompatibility;
6
7
use Countable;
8
use Generator;
9
use IteratorAggregate;
10
use function count;
11
use function iterator_to_array;
12
13
final class Changes implements IteratorAggregate, Countable
14
{
15
    /** @var Change[] */
16
    private $bufferedChanges;
17
18
    /** @var iterable|Change[]|null */
19
    private $unBufferedChanges;
20
21
    private function __construct()
22
    {
23
    }
24
25
    public static function empty() : self
26
    {
27
        static $empty;
28
29
        if ($empty) {
30
            return $empty;
31
        }
32
33
        $empty = new self();
34
35
        $empty->bufferedChanges = [];
36
37
        return $empty;
38
    }
39
40
    /** @param iterable|Change[] $changes */
41
    public static function fromIterator(iterable $changes) : self
42
    {
43
        $instance = new self();
44
45
        $instance->bufferedChanges   = [];
46
        $instance->unBufferedChanges = $changes;
47
48
        return $instance;
49
    }
50
51
    public static function fromList(Change ...$changes) : self
52
    {
53
        $instance = new self();
54
55
        $instance->bufferedChanges = $changes;
56
57
        return $instance;
58
    }
59
60
    public function mergeWith(self $other) : self
61
    {
62
        $instance = new self();
63
64
        $instance->bufferedChanges   = [];
65
        $instance->unBufferedChanges = (function () use ($other) : Generator {
66
            foreach ($this as $change) {
67
                yield $change;
68
            }
69
70
            foreach ($other as $change) {
71
                yield $change;
72
            }
73
        })();
74
75
        return $instance;
76
    }
77
78
    /**
79
     * {@inheritDoc}
80
     *
81
     * @return iterable|Change[]
82
     */
83
    public function getIterator() : iterable
84
    {
85
        foreach ($this->bufferedChanges as $change) {
86
            yield $change;
0 ignored issues
show
Bug Best Practice introduced by
The expression yield $change returns the type Generator which is incompatible with the documented return type iterable|Roave\BackwardCompatibility\Change[].
Loading history...
87
        }
88
89
        foreach ($this->unBufferedChanges ?? [] as $change) {
90
            $this->bufferedChanges[] = $change;
91
92
            yield $change;
93
        }
94
95
        $this->unBufferedChanges = null;
96
    }
97
98
    /**
99
     * {@inheritDoc}
100
     */
101
    public function count() : int
102
    {
103
        return count(iterator_to_array($this));
104
    }
105
}
106