AbstractReader::read()   A
last analyzed

Complexity

Conditions 5
Paths 5

Size

Total Lines 23
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 5
eloc 11
nc 5
nop 0
dl 0
loc 23
rs 9.6111
c 0
b 0
f 0
1
<?php declare(strict_types=1);
2
/**
3
 * portable-game-notation (https://github.com/chesszebra/portable-game-notation)
4
 *
5
 * @link https://github.com/chesszebra/portable-game-notation for the canonical source repository
6
 * @copyright Copyright (c) 2017 Chess Zebra (https://chesszebra.com)
7
 * @license https://github.com/chesszebra/portable-game-notation/blob/master/LICENSE.md MIT
8
 */
9
10
namespace ChessZebra\PortableGameNotation\Reader;
11
12
use ChessZebra\PortableGameNotation\Lexer\Exception\InvalidTokenException;
13
use ChessZebra\PortableGameNotation\Lexer\LexerInterface;
14
use ChessZebra\PortableGameNotation\Token\TagPair;
15
use ChessZebra\PortableGameNotation\Token\TokenIterator;
16
17
abstract class AbstractReader implements ReaderInterface
18
{
19
    /**
20
     * @var LexerInterface
21
     */
22
    private $lexer;
23
24
    /**
25
     * Initializes a new instance of this class.
26
     *
27
     * @param LexerInterface $lexer
28
     */
29
    public function __construct(LexerInterface $lexer)
30
    {
31
        $this->lexer = $lexer;
32
    }
33
34
    /**
35
     * Reads a collection of tokens that form a game.
36
     *
37
     * @return TokenIterator|null Returns null when no tokens are left; an TokenIterator otherwise.
38
     * @throws InvalidTokenException Thrown when an invalid token was found during reading.
39
     */
40
    public function read(): ?TokenIterator
41
    {
42
        if ($this->lexer->peekNextToken() === null) {
43
            return null;
44
        }
45
46
        $token = $this->lexer->getNextToken();
47
48
        $tokens = [];
49
50
        while ($token instanceof TagPair) {
51
            $tokens[] = $token;
52
53
            $token = $this->lexer->getNextToken();
54
        }
55
56
        while ($token && !$token instanceof TagPair) {
57
            $tokens[] = $token;
58
59
            $token = $this->lexer->getNextToken();
60
        }
61
62
        return new TokenIterator($tokens);
63
    }
64
}
65