创建 PHP 语言解析器

时间:2021-01-03 11:45:44

标签: php parsing php-stream-wrappers

我正在尝试使用 streamwrapper class 使用 PHP 创建解析器,这里我使用文件包装器来包含一个外部文件,该外部文件名为 new-lang-code-file.php,我编写了一个简单的语法:< /p>

$f = 'x';
cetak $f;

在名为_parseCode的私有方法中,哪个cetak关键字将被替换为echo,在这个方法中我在返回中添加了php open标签像这样。

return "<?php\n".$content;

我尝试使用 var_dump 包含的 $content 值来检查它

<?php
$f = 'x';
echo $f;

但是,当我尝试使用 php cli 运行时

<块引用>

php NewLangParser.php

它向我显示了此错误消息:

<块引用>

PHP 解析错误:语法错误,文件意外结束 /var/www/html/new-lang-code-file.php 第 3 行

我已经尝试添加 php 关闭标签,但错误信息仍然存在

这里是类解析器的完整代码:

<?php

class NewLangParser  {
  private $_handler;
  
  private $_path;
  
  public function stream_open($path, $mode, $options, &$opened_path) {           
    stream_wrapper_restore('file');
    $this->_handler = fopen($path, 'r');
    $this->_path = $path;
    self::registerLang();
    return true;
  }             
  
  public function stream_read($count) {

    $content = fread($this->_handler, $count);
    $content = $this->_parseCode($content);
    
    return "<?php\n".$content;
  }             
  
  private function _parseCode($content) {
    $content = str_replace('cetak ', 'echo ', $content);
    return $content;
  }
  
  public function stream_eof() { 
    return true;
  }             
  
  public function stream_stat() {      
    return fstat($this->_handler);
  }                           
  
  public function url_stat() {  
    return stat($this->_path);
  }    

  public function stream_set_option()
  {
    return true;
  }
  
  public static function registerLang() {
    stream_wrapper_unregister('file');
    stream_wrapper_register('file', 'NewLangParser');
  }
}

NewLangParser::registerLang();

include 'new-lang-code-file.php';

有人可以帮我吗?

0 个答案:

没有答案