PrioritizedList::getIterator()   A
last analyzed

Complexity

Conditions 4
Paths 2

Size

Total Lines 16
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 4

Importance

Changes 0
Metric Value
cc 4
eloc 8
nc 2
nop 0
dl 0
loc 16
ccs 9
cts 9
cp 1
crap 4
rs 10
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
/*
6
 * This file was originally part of the league/commonmark package.
7
 *
8
 * (c) Colin O'Dell <[email protected]>
9
 *
10
 * Original code based on the CommonMark JS reference parser (https://bitly.com/commonmark-js)
11
 *  - (c) John MacFarlane
12
 *
13
 * For the full copyright and license information, please view the LICENSE
14
 * file that was distributed with this source code.
15
 */
16
17
namespace League\Emoji\Util;
18
19
/**
20
 * @internal
21
 *
22
 * @template T
23
 * @implements \IteratorAggregate<T>
24
 */
25
final class PrioritizedList implements \IteratorAggregate
26
{
27
    /**
28
     * @var array<int, array<mixed>>
29
     * @phpstan-var array<int, array<T>>
30
     */
31
    private $list = [];
32
33
    /**
34
     * @var ?\Traversable<int, mixed>
35
     * @phpstan-var ?\Traversable<int, T>
36
     */
37
    private $optimized;
38
39
    /**
40
     * @param mixed $item
41
     *
42
     * @phpstan-param T $item
43
     */
44 672
    public function add($item, int $priority): void
45
    {
46 672
        $this->list[$priority][] = $item;
47 672
        $this->optimized         = null;
48 672
    }
49
50
    /**
51
     * @return \Traversable<int, mixed>
52
     *
53
     * @phpstan-return \Traversable<int, T>
54
     */
55 261
    public function getIterator(): \Traversable
56
    {
57 261
        if ($this->optimized === null) {
58 261
            \krsort($this->list);
59
60 261
            $sorted = [];
61 261
            foreach ($this->list as $group) {
62 258
                foreach ($group as $item) {
63 258
                    $sorted[] = $item;
64
                }
65
            }
66
67 261
            $this->optimized = new \ArrayIterator($sorted);
68
        }
69
70 261
        return $this->optimized;
71
    }
72
}
73