124 lines
3.1 KiB
PHP
124 lines
3.1 KiB
PHP
<?php
|
|
/**
|
|
* @filename StringReader.php
|
|
* @author Jerry Yan <792602257@qq.com>
|
|
* @date 2020/12/17 14:58
|
|
*/
|
|
|
|
|
|
namespace JerryYan\DSL\Reader;
|
|
|
|
|
|
class StringReader extends ReaderInterface
|
|
{
|
|
protected $string;
|
|
protected $currentToken;
|
|
|
|
public function __construct(string $string)
|
|
{
|
|
$this->string = $string;
|
|
$this->moveToNextToken();
|
|
}
|
|
|
|
/**
|
|
* @inheritDoc
|
|
*/
|
|
public function getNextChar(int $startAt = null): string
|
|
{
|
|
if ($startAt === null) $startAt = $this->currentPosition;
|
|
return mb_substr($this->string, $startAt, 1);
|
|
}
|
|
|
|
/**
|
|
* @inheritDoc
|
|
*/
|
|
public function getCurrentToken(): string
|
|
{
|
|
return $this->currentToken;
|
|
}
|
|
|
|
/**
|
|
* @inheritDoc
|
|
*/
|
|
public function getNextToken(): string
|
|
{
|
|
$curToken = "";
|
|
$curPos = $this->nextPosition;
|
|
while ($curChar = $this->getNextChar($curPos)) {
|
|
switch ($curChar) {
|
|
case " ":
|
|
// 如果开始的时候就有空白,跳过它
|
|
if (empty($curToken)) {
|
|
continue 2;
|
|
}
|
|
// 否则就结束(已经匹配完成)
|
|
break 2;
|
|
case "\r":
|
|
case "\n":
|
|
break 2;
|
|
default:
|
|
$curToken .= $curChar;
|
|
}
|
|
}
|
|
return $curToken;
|
|
}
|
|
|
|
/**
|
|
* @inheritDoc
|
|
*/
|
|
public function moveToNextToken(): bool
|
|
{
|
|
$curToken = "";
|
|
$this->currentPosition = $this->nextPosition;
|
|
while ($curChar = $this->getNextChar($this->nextPosition)) {
|
|
$this->nextPosition++;
|
|
$this->currentLinePosition++;
|
|
switch ($curChar) {
|
|
case " ":
|
|
// 如果开始的时候就有空白,跳过它
|
|
if (empty($curToken)) {
|
|
$this->currentPosition++;
|
|
continue 2;
|
|
}
|
|
// 否则就结束(已经匹配完成)
|
|
break 2;
|
|
case "\r":
|
|
if ($this->getNextChar($this->nextPosition+1) === "\n") {
|
|
// CRLF换行
|
|
$this->nextPosition+=2;
|
|
}
|
|
// CR换行
|
|
$this->currentLine++;
|
|
$this->currentLinePosition=0;
|
|
break 2;
|
|
case "\n":
|
|
// LF换行
|
|
$this->currentLine++;
|
|
$this->currentLinePosition=0;
|
|
break 2;
|
|
default:
|
|
$curToken .= $curChar;
|
|
}
|
|
}
|
|
$this->currentToken = $curToken;
|
|
return true;
|
|
}
|
|
|
|
/**
|
|
* @inheritDoc
|
|
*/
|
|
public function skipCurrentLine(): bool
|
|
{
|
|
// TODO: Implement skipCurrentLine() method.
|
|
return true;
|
|
}
|
|
|
|
/**
|
|
* @inheritDoc
|
|
*/
|
|
public function skipUntil(string $end = "*/"): bool
|
|
{
|
|
// TODO: Implement skipUntil() method.
|
|
return true;
|
|
}
|
|
} |