<?php

namespace Kachkaev\JstmplBundle\Twig;

class JstmplTokenParser extends \Twig_TokenParser
{
    public function parse(\Twig_Token $token)
    {
        $lineno = $token->getLine();
        
        $stream = $this->parser->getStream();
        
        while (!$stream->test(\Twig_Token::BLOCK_END_TYPE)) {
            if ($stream->test(\Twig_Token::NAME_TYPE, 'id')) {
                // id='tmpl_id'
                $stream->next();
                $stream->expect(\Twig_Token::OPERATOR_TYPE, '=');
                $id = $stream->expect(\Twig_Token::STRING_TYPE)->getValue();
            } else {
                $token = $stream->getCurrent();
                throw new \Twig_Error_Syntax(sprintf('Unexpected token "%s" of value "%s"', \Twig_Token::typeToEnglish($token->getType(), $token->getLine()), $token->getValue()), $token->getLine());
            }
        }

        $stream->expect(\Twig_Token::BLOCK_END_TYPE);

        $endtag = 'end'.$this->getTag();
        $test = function(\Twig_Token $token) use($endtag) {
            return $token->test($endtag);
        };
        $body = $this->parser->subparse($test, true);

        $stream->expect(\Twig_Token::BLOCK_END_TYPE);

        return new JstmplNode($id, $body, $lineno, $this->getTag());
    }

    public function getTag()
    {
        return 'jstmpl';
    }
}
