Test Failed
Push — master ( ecd78b...d05c81 )
by Kirill
02:43
created

PrioritizeAnalyzer::analyze()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
nc 4
nop 1
dl 0
loc 12
rs 9.8666
c 0
b 0
f 0
1
<?php
2
/**
3
 * This file is part of Railt package.
4
 *
5
 * For the full copyright and license information, please view the LICENSE
6
 * file that was distributed with this source code.
7
 */
8
declare(strict_types=1);
9
10
namespace Railt\SDL\Frontend\Analyzer;
11
12
use Railt\SDL\Frontend\IR\OpcodeInterface;
13
14
/**
15
 * Class PrioritizeAnalyzer
16
 */
17
class PrioritizeAnalyzer implements AnalyzerInterface
18
{
19
    /**
20
     * @var int[]
21
     */
22
    protected const PRIORITIES = [
23
        OpcodeInterface::RL_OPEN => -1,
24
        OpcodeInterface::RL_DEFINE => -1,
25
    ];
26
27
    /**
28
     * @var array
29
     */
30
    private $priorities = [];
31
32
    /**
33
     * @param iterable|OpcodeInterface[] $opcodes
34
     * @return iterable|OpcodeInterface[]
35
     */
36
    public function analyze(iterable $opcodes): iterable
37
    {
38
        foreach ($opcodes as $opcode) {
39
            $priority = self::PRIORITIES[$opcode->getOperation()] ?? 0;
40
41
            $this->priority($priority)->push($opcode);
42
        }
43
44
        foreach ($this->priorities as $queue) {
45
            yield from $queue;
46
        }
47
    }
48
49
    /**
50
     * @param int $index
51
     * @return \SplQueue
52
     */
53
    private function priority(int $index): \SplQueue
54
    {
55
        $queue = $this->priorities[$index] ?? null;
56
57
        if (! $queue) {
58
            $this->priorities[$index] = new \SplQueue();
59
        }
60
61
        return $this->priorities[$index];
62
    }
63
}
64