Changes   A
last analyzed

Complexity

Total Complexity 12

Size/Duplication

Total Lines 88
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 31
dl 0
loc 88
rs 10
c 1
b 0
f 0
wmc 12

7 Methods

Rating   Name   Duplication   Size   Complexity  
A mergeWith() 0 16 3
A __construct() 0 2 1
A empty() 0 13 2
A fromList() 0 7 1
A fromIterator() 0 8 1
A getIterator() 0 13 3
A count() 0 3 1
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 Traversable;
11
use function count;
12
use function iterator_to_array;
13
14
final class Changes implements IteratorAggregate, Countable
15
{
16
    /** @var Change[] */
17
    private $bufferedChanges;
18
19
    /** @var iterable|Change[]|null */
20
    private $unBufferedChanges;
21
22
    private function __construct()
23
    {
24
    }
25
26
    public static function empty() : self
27
    {
28
        static $empty;
29
30
        if ($empty) {
31
            return $empty;
32
        }
33
34
        $empty = new self();
35
36
        $empty->bufferedChanges = [];
37
38
        return $empty;
39
    }
40
41
    /** @param iterable|Change[] $changes */
42
    public static function fromIterator(iterable $changes) : self
43
    {
44
        $instance = new self();
45
46
        $instance->bufferedChanges   = [];
47
        $instance->unBufferedChanges = $changes;
48
49
        return $instance;
50
    }
51
52
    public static function fromList(Change ...$changes) : self
53
    {
54
        $instance = new self();
55
56
        $instance->bufferedChanges = $changes;
57
58
        return $instance;
59
    }
60
61
    public function mergeWith(self $other) : self
62
    {
63
        $instance = new self();
64
65
        $instance->bufferedChanges   = [];
66
        $instance->unBufferedChanges = (function () use ($other) : Generator {
67
            foreach ($this as $change) {
68
                yield $change;
69
            }
70
71
            foreach ($other as $change) {
72
                yield $change;
73
            }
74
        })();
75
76
        return $instance;
77
    }
78
79
    /**
80
     * {@inheritDoc}
81
     *
82
     * @return Traversable<int, Change>
83
     */
84
    public function getIterator() : iterable
85
    {
86
        foreach ($this->bufferedChanges as $change) {
87
            yield $change;
88
        }
89
90
        foreach ($this->unBufferedChanges ?? [] as $change) {
91
            $this->bufferedChanges[] = $change;
92
93
            yield $change;
94
        }
95
96
        $this->unBufferedChanges = null;
97
    }
98
99
    public function count() : int
100
    {
101
        return count(iterator_to_array($this));
102
    }
103
}
104