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

Analyzer::analyze()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
nc 2
nop 1
dl 0
loc 8
rs 10
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;
11
12
use Psr\Log\LoggerAwareInterface;
13
use Psr\Log\LoggerAwareTrait;
14
use Psr\Log\LoggerInterface;
15
use Railt\SDL\Frontend\Analyzer\AnalyzerInterface;
16
use Railt\SDL\Frontend\Analyzer\LoggerAnalyzer;
17
use Railt\SDL\Frontend\Analyzer\PrioritizeAnalyzer;
18
19
/**
20
 * Class Analyzer
21
 */
22
class Analyzer implements AnalyzerInterface, LoggerAwareInterface
23
{
24
    use LoggerAwareTrait;
25
26
    /**
27
     * @var AnalyzerInterface[]
28
     */
29
    private const DEFAULTS = [
30
        // Change opcodes priorities
31
        PrioritizeAnalyzer::class,
32
33
        // Should be last
34
        LoggerAnalyzer::class,
35
    ];
36
37
    /**
38
     * @var array|AnalyzerInterface[]
39
     */
40
    private $instances = [];
41
42
    /**
43
     * Analyzer constructor.
44
     */
45
    public function __construct()
46
    {
47
        $this->bootDefaults();
48
    }
49
50
    /**
51
     * @return void
52
     */
53
    private function bootDefaults(): void
54
    {
55
        foreach (self::DEFAULTS as $analyzer) {
56
            $this->addAnalyzer(new $analyzer);
57
        }
58
    }
59
60
    /**
61
     * @param AnalyzerInterface $analyzer
62
     * @return Analyzer
63
     */
64
    public function addAnalyzer(AnalyzerInterface $analyzer): Analyzer
65
    {
66
        $this->instances[] = $analyzer;
67
68
        if ($this->logger && $analyzer instanceof LoggerAwareInterface) {
69
            $analyzer->setLogger($this->logger);
70
        }
71
72
        return $this;
73
    }
74
75
    /**
76
     * @param LoggerInterface $logger
77
     * @return Analyzer
78
     */
79
    public function setLogger(LoggerInterface $logger): Analyzer
80
    {
81
        $this->logger = $logger;
82
83
        foreach ($this->instances as $instance) {
84
            if ($instance instanceof LoggerAwareInterface) {
85
                $instance->setLogger($logger);
86
            }
87
        }
88
89
        return $this;
90
    }
91
92
    /**
93
     * @param iterable $opcodes
94
     * @return iterable
95
     */
96
    public function analyze(iterable $opcodes): iterable
97
    {
98
        foreach ($this->instances as $instance) {
99
            $opcodes = $instance->analyze($opcodes);
100
        }
101
102
        yield from $opcodes;
103
    }
104
}
105