Completed
Push — master ( 450e0e...3bb600 )
by Kirill
05:06
created

SimpleLexer::lex()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 3

Importance

Changes 0
Metric Value
dl 0
loc 8
ccs 5
cts 5
cp 1
rs 10
c 0
b 0
f 0
cc 3
nc 3
nop 1
crap 3
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\Lexer\Driver;
11
12
use Railt\Io\Readable;
13
use Railt\Lexer\Definition\TokenDefinition;
14
use Railt\Lexer\LexerInterface;
15
use Railt\Lexer\SimpleLexerInterface;
16
use Railt\Lexer\TokenInterface;
17
18
/**
19
 * Class BaseLexer
20
 */
21
abstract class SimpleLexer implements SimpleLexerInterface
22
{
23
    /**
24
     * @var array|string[]
25
     */
26
    protected $skipped = [];
27
28
    /**
29
     * @var array|string[]
30
     */
31
    protected $tokens = [];
32
33
    /**
34
     * @param Readable $input
35
     * @return \Traversable|TokenInterface[]
36
     */
37 6
    public function lex(Readable $input): \Traversable
38
    {
39 6
        foreach ($this->exec($input) as $token) {
40 6
            if (! \in_array($token->getName(), $this->skipped, true)) {
41 6
                yield $token;
42
            }
43
        }
44 6
    }
45
46
    /**
47
     * @param string $token
48
     * @param string $pcre
49
     * @return LexerInterface
50
     */
51
    public function add(string $token, string $pcre): LexerInterface
52
    {
53
        $this->tokens[$token] = $pcre;
54
55
        return $this;
56
    }
57
58
    /**
59
     * @param string $name
60
     * @return LexerInterface
61
     */
62 1
    public function skip(string $name): LexerInterface
63
    {
64 1
        $this->skipped[] = $name;
65
66 1
        return $this;
67
    }
68
69
    /**
70
     * @param Readable $file
71
     * @return \Traversable|TokenInterface[]
72
     */
73
    abstract protected function exec(Readable $file): \Traversable;
74
75
    /**
76
     * @return iterable|TokenDefinition[]
77
     */
78
    public function getTokenDefinitions(): iterable
79
    {
80 View Code Duplication
        foreach ($this->tokens as $name => $pcre) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
81
            yield new TokenDefinition($name, $pcre, ! \in_array($name, $this->skipped, true));
82
        }
83
    }
84
}
85