PhpGrammar.php

<?php

namespace Tlf\Lexer\Test\Document;

/**
 * This class is for writing documentation as code
 * So tests should be extremely clean & not seek to be unit tests, but seek to confirm broad functionality
 */
class PhpGrammar extends \Tlf\Lexer\Test\Tester {

    /**
     * Just an example of how to run the php grammar
     */
    public function testVerbose(){

        
        $input = 'const blm = "yes";';

        // php grammar uses the type of the head ast.
        $ast = new \Tlf\Lexer\Ast('class_body');

        $phpGram = new \Tlf\Lexer\PhpGrammar();
        $phpGram->directives = array_merge(
            $phpGram->_string_directives,
            $phpGram->_core_directives,
        );
        $lexer = new \Tlf\Lexer();
        $lexer->debug = true;
        // pass `true` instead of `false` to call `onGrammarAdded()`, which would prepare $phpGram->directives
        $lexer->addGrammar($phpGram, null, false);

        // adds directives to the top of the stack
        foreach ($phpGram->getDirectives(':php_code') as $directive){
            $lexer->addDirective($directive);
        }
        // alternate starting directive, if you're expecting a php open tag before php code
        // $lexer->addDirective($phpGram->getDirectives(':php_open')['php_open']);

        // runs the lexer with $ast as the head
        $ast = $lexer->lex($input, $ast);
        $tree = $ast->getTree();

        $expect = 
        [
            'type'=>'class_body',
            'const'=>[
                0=>[
                    'type'=>'const',
                    'name'=>'blm',
                    'value'=>'"yes"',
                    'declaration'=>'const blm = "yes";',
                ],
            ]
        ];
        $this->compare($expect,
            $tree
        );
    }
}