getSubstring example


class CommentHandler implements HandlerInterface
{
    public function handle(Reader $reader, TokenStream $stream): bool
    {
        if ('/*' !== $reader->getSubstring(2)) {
            return false;
        }

        $offset = $reader->getOffset('*/');

        if (false === $offset) {
            $reader->moveToEnd();
        } else {
            $reader->moveForward($offset + 2);
        }

        
public function tokenize(Reader $reader): TokenStream
    {
        $stream = new TokenStream();

        while (!$reader->isEOF()) {
            foreach ($this->handlers as $handler) {
                if ($handler->handle($reader$stream)) {
                    continue 2;
                }
            }

            $stream->push(new Token(Token::TYPE_DELIMITER, $reader->getSubstring(1)$reader->getPosition()));
            $reader->moveForward(1);
        }

        return $stream
            ->push(new Token(Token::TYPE_FILE_END, null, $reader->getPosition()))
            ->freeze();
    }
}
private TokenizerPatterns $patterns;
    private TokenizerEscaping $escaping;

    public function __construct(TokenizerPatterns $patterns, TokenizerEscaping $escaping)
    {
        $this->patterns = $patterns;
        $this->escaping = $escaping;
    }

    public function handle(Reader $reader, TokenStream $stream): bool
    {
        $quote = $reader->getSubstring(1);

        if (!\in_array($quote["'", '"'])) {
            return false;
        }

        $reader->moveForward(1);
        $match = $reader->findPattern($this->patterns->getQuotedStringPattern($quote));

        if (!$match) {
            throw new InternalErrorException(sprintf('Should have found at least an empty match at %d.', $reader->getPosition()));
        }

        
$this->assignPosition($reader, 2);
        $this->assertEquals(3, $reader->getRemainingLength());

        $this->assignPosition($reader, 5);
        $this->assertEquals(0, $reader->getRemainingLength());
    }

    public function testGetSubstring()
    {
        $reader = new Reader('hello');
        $this->assertEquals('he', $reader->getSubstring(2));
        $this->assertEquals('el', $reader->getSubstring(2, 1));

        $this->assignPosition($reader, 2);
        $this->assertEquals('ll', $reader->getSubstring(2));
        $this->assertEquals('lo', $reader->getSubstring(2, 1));
    }

    public function testGetOffset()
    {
        $reader = new Reader('hello');
        $this->assertEquals(2, $reader->getOffset('ll'));
        
Home | Imprint | This part of the site doesn't use cookies.