This commit is contained in:
Ivan Shalganov
2013-01-25 18:36:16 +04:00
commit 164ab85594
21 changed files with 4299 additions and 0 deletions

649
src/Aspect.php Normal file
View File

@ -0,0 +1,649 @@
<?php
use Aspect\Template;
class Aspect {
const INLINE_COMPILER = 1;
const BLOCK_COMPILER = 2;
const INLINE_FUNCTION = 3;
const BLOCK_FUNCTION = 4;
const MODIFIER = 5;
const DENY_METHODS = 128;
const DENY_INLINE_FUNCS = 256;
const DENY_SET_VARS = 512;
const INCLUDE_SOURCES = 1024;
const CHECK_MTIME = 2048;
const FORCE_COMPILE = 4096;
/**
* @var array list of possible options, as associative array
* @see setOptions, addOptions, delOptions
*/
private static $_option_list = array(
"disable_methods" => self::DENY_METHODS,
"disable_native_funcs" => self::DENY_INLINE_FUNCS,
"disable_set_vars" => self::DENY_SET_VARS,
"include_sources" => self::INCLUDE_SOURCES,
"force_compile" => self::FORCE_COMPILE,
"compile_check" => self::CHECK_MTIME,
);
private static $_actions_defaults = array(
self::BLOCK_FUNCTION => array(
'type' => self::BLOCK_FUNCTION,
'open' => 'MF\Aspect\Compiler::stdFuncOpen',
'close' => 'MF\Aspect\Compiler::stdFuncClose',
'function' => null,
),
self::INLINE_FUNCTION => array(
'type' => self::INLINE_FUNCTION,
'parser' => 'MF\Aspect\Compiler::stdFuncParser',
'function' => null,
),
self::INLINE_FUNCTION => array(
'type' => self::INLINE_COMPILER,
'open' => null,
'close' => 'MF\Aspect\Compiler::stdClose',
'tags' => array(),
'float_tags' => array()
),
self::BLOCK_FUNCTION => array(
'type' => self::BLOCK_COMPILER,
'open' => null,
'close' => null,
'tags' => array(),
'float_tags' => array()
)
);
public $blocks = array();
/**
* @var array Templates storage
*/
protected $_storage = array();
/**
* @var array template directory
*/
protected $_tpl_path = array();
/**
* @var string compile directory
*/
protected $_compile_dir = "/tmp";
/**
* @var int masked options
*/
protected $_options = 0;
/**
* Modifiers loader
* @var callable
*/
protected $_loader_mod;
/**
* Functions loader
* @var callable
*/
protected $_loader_func;
/**
* @var array list of modifiers
*/
protected $_modifiers = array(
"upper" => 'strtoupper',
"lower" => 'strtolower',
"nl2br" => 'nl2br',
"date_format" => 'Aspect\Modifier::dateFormat',
"date" => 'Aspect\Modifier::date',
"truncate" => 'Aspect\Modifier::truncate',
"escape" => 'Aspect\Modifier::escape',
"e" => 'Aspect\Modifier::escape', // alias of escape
"unescape" => 'Aspect\Modifier::unescape',
"strip_tags" => 'strip_tags',
"strip" => 'Aspect\Modifier::strip',
"default" => 'Aspect\Modifier::defaultValue',
"isset" => 'isset',
"empty" => 'empty'
);
/**
* @var array list of allowed PHP functions
*/
protected $_allowed_funcs = array(
"empty" => 1, "isset" => 1, "count" => 1, "is_string" => 1, "is_array" => 1, "is_numeric" => 1, "is_int" => 1, "is_object" => 1
);
/**
* @var array list of compilers and functions
*/
protected $_actions = array(
'foreach' => array(
'type' => self::BLOCK_COMPILER,
'open' => 'Aspect\Compiler::foreachOpen',
'close' => 'Aspect\Compiler::foreachClose',
'tags' => array(
'foreachelse' => 'Aspect\Compiler::foreachElse',
'break' => 'Aspect\Compiler::tagBreak',
'continue' => 'Aspect\Compiler::tagContinue',
),
'float_tags' => array('break' => 1, 'continue' => 1)
),
'if' => array(
'type' => self::BLOCK_COMPILER,
'open' => 'Aspect\Compiler::ifOpen',
'close' => 'Aspect\Compiler::stdClose',
'tags' => array(
'elseif' => 'Aspect\Compiler::tagElseIf',
'else' => 'Aspect\Compiler::tagElse',
)
),
'switch' => array(
'type' => self::BLOCK_COMPILER,
'open' => 'Aspect\Compiler::switchOpen',
'close' => 'Aspect\Compiler::stdClose',
'tags' => array(
'case' => 'Aspect\Compiler::tagCase',
'default' => 'Aspect\Compiler::tagDefault',
'break' => 'Aspect\Compiler::tagBreak',
),
'float_tags' => array('break' => 1)
),
'for' => array(
'type' => self::BLOCK_COMPILER,
'open' => 'Aspect\Compiler::forOpen',
'close' => 'Aspect\Compiler::forClose',
'tags' => array(
'forelse' => 'Aspect\Compiler::forElse',
'break' => 'Aspect\Compiler::tagBreak',
'continue' => 'Aspect\Compiler::tagContinue',
),
'float_tags' => array('break' => 1, 'continue' => 1)
),
'while' => array(
'type' => self::BLOCK_COMPILER,
'open' => 'Aspect\Compiler::whileOpen',
'close' => 'Aspect\Compiler::stdClose',
'tags' => array(
'break' => 'Aspect\Compiler::tagBreak',
'continue' => 'Aspect\Compiler::tagContinue',
),
'float_tags' => array('break' => 1, 'continue' => 1)
),
'include' => array(
'type' => self::INLINE_COMPILER,
'parser' => 'Aspect\Compiler::tagInclude'
),
'var' => array(
'type' => self::INLINE_COMPILER,
'parser' => 'Aspect\Compiler::assign'
),
'block' => array(
'type' => self::BLOCK_COMPILER,
'open' => 'Aspect\Compiler::tagBlockOpen',
'close' => 'Aspect\Compiler::tagBlockClose',
),
'extends' => array(
'type' => self::INLINE_COMPILER,
'parser' => 'Aspect\Compiler::tagExtends'
),
'capture' => array(
'type' => self::BLOCK_FUNCTION,
'open' => 'Aspect\Compiler::stdFuncOpen',
'close' => 'Aspect\Compiler::stdFuncClose',
'function' => 'Aspect\Func::capture',
),
'mailto' => array(
'type' => self::INLINE_FUNCTION,
'parser' => 'Aspect\Compiler::stdFuncParser',
'function' => 'Aspect\Func::mailto',
)
);
public static function factory($template_dir, $compile_dir, $options = 0) {
$aspect = new static();
$aspect->setCompileDir($compile_dir);
$aspect->setTemplateDirs($template_dir);
if($options) {
$aspect->setOptions($options);
}
return $aspect;
}
public function setCompileCheck($state) {
$state && ($this->_options |= self::CHECK_MTIME);
return $this;
}
public function setForceCompile($state) {
$state && ($this->_options |= self::FORCE_COMPILE);
$this->_storage = $state ? new Aspect\BlackHole() : array();
return $this;
}
public function setCompileDir($dir) {
$this->_compile_dir = $dir;
return $this;
}
public function setTemplateDirs($dirs) {
$this->_tpl_path = (array)$dirs;
return $this;
}
/*public function addPostCompileFilter($cb) {
$this->_post_cmp[] = $cb;
}
public function addCompileFilter($cb) {
$this->_cmp[] = $cb;
}*/
/**
* Add modifier
*
* @param string $modifier
* @param string $callback
* @return Aspect
*/
public function setModifier($modifier, $callback) {
$this->_modifiers[$modifier] = $callback;
return $this;
}
/**
* @param $compiler
* @param $parser
* @return Aspect
*/
public function setCompiler($compiler, $parser) {
$this->_actions[$compiler] = array(
'type' => self::INLINE_COMPILER,
'parser' => $parser
);
return $this;
}
/**
* @param $compiler
* @param array $parsers
* @param array $tags
* @return Aspect
*/
public function setBlockCompiler($compiler, array $parsers, array $tags = array()) {
$this->_actions[$compiler] = array(
'type' => self::BLOCK_COMPILER,
'open' => $parsers["open"],
'close' => isset($parsers["close"]) ? $parsers["close"] : 'Aspect\Compiler::stdClose',
'tags' => $tags,
);
return $this;
}
/**
* @param $function
* @param $callback
* @param null $parser
* @return Aspect
*/
public function setFunction($function, $callback, $parser = null) {
$this->_actions[$function] = array(
'type' => self::INLINE_FUNCTION,
'parser' => $parser ?: 'Aspect\Compiler::stdFuncParser',
'function' => $callback,
);
return $this;
}
/**
* @param $function
* @param $callback
* @param null $parser_open
* @param null $parser_close
* @return Aspect
*/
public function setBlockFunction($function, $callback, $parser_open = null, $parser_close = null) {
$this->_actions[$function] = array(
'type' => self::BLOCK_FUNCTION,
'open' => $parser_open ?: 'Aspect\Compiler::stdFuncOpen',
'close' => $parser_close ?: 'Aspect\Compiler::stdFuncClose',
'function' => $callback,
);
return $this;
}
/**
* @param array $funcs
* @return Aspect
*/
public function setAllowedFunctions(array $funcs) {
$this->_allowed_funcs = $this->_allowed_funcs + array_flip($funcs);
return $this;
}
/**
* @param callable $callback
* @return Aspect
*/
public function setFunctionsLoader($callback) {
$this->_loader_func = $callback;
return $this;
}
/**
* @param callable $callback
* @return Aspect
*/
public function setModifiersLoader($callback) {
$this->_loader_mod = $callback;
return $this;
}
/**
* @param $modifier
* @return mixed
* @throws \Exception
*/
public function getModifier($modifier) {
if(isset($this->_modifiers[$modifier])) {
return $this->_modifiers[$modifier];
} elseif($this->isAllowedFunction($modifier)) {
return $modifier;
} elseif($this->_loader_mod && $this->_loadModifier($modifier)) {
return $this->_modifiers[$modifier];
} else {
throw new \Exception("Modifier $modifier not found");
}
}
/**
* @param string $function
* @return string|bool
*/
public function getFunction($function) {
if(isset($this->_actions[$function])) {
return $this->_actions[$function];
} elseif($this->_loader_func && $this->_loadFunction($function)) {
return $this->_actions[$function];
} else {
return false;
}
}
private function _loadModifier($modifier) {
$mod = call_user_func($this->_loader_mod, $modifier);
if($mod) {
$this->_modifiers[$modifier] = $mod;
return true;
} else {
return false;
}
}
private function _loadFunction($function) {
$func = call_user_func($this->_loader_func, $function);
if($func && isset(self::$_actions_defaults[ $func["type"] ])) {
$this->_actions[$function] = $func + self::$_actions_defaults[ $func["type"] ];
return true;
} else {
return false;
}
}
public function isAllowedFunction($function) {
if($this->_options & self::DENY_INLINE_FUNCS) {
return isset($this->_allowed_funcs[$function]);
} else {
return is_callable($function);
}
}
public function getTagOwners($tag) {
$tags = array();
foreach($this->_actions as $owner => $params) {
if(isset($params["tags"][$tag])) {
$tags[] = $owner;
}
}
return $tags;
}
/**
* Add template directory
* @static
* @param string $dir
* @throws \InvalidArgumentException
*/
public function addTemplateDir($dir) {
$_dir = realpath($dir);
if(!$_dir) {
throw new \InvalidArgumentException("Invalid template dir: $dir");
}
$this->_tpl_path[] = $_dir;
}
/**
* Set options. May be bitwise mask of constants DENY_METHODS, DENY_INLINE_FUNCS, DENY_SET_VARS, INCLUDE_SOURCES,
* FORCE_COMPILE, CHECK_MTIME, or associative array with boolean values:
* disable_methods - disable all call method in template
* disable_native_funcs - disable all native PHP functions in template
* disable_set_vars - forbidden rewrite variables
* include_sources - insert comments with source code into compiled template
* force_compile - recompile template every time (very slow!)
* compile_check - check template modifications (slow!)
* @param int|array $options
*/
public function setOptions($options) {
if(is_array($options)) {
$options = Aspect\Misc::makeMask($options, self::$_option_list);
}
$this->_storage = ($options & self::FORCE_COMPILE) ? new Aspect\BlackHole() : array();
$this->_options = $options;
}
/**
* Get options as bits
* @return int
*/
public function getOptions() {
return $this->_options;
}
/**
* Execute template and write result into stdout
*
*
* @param string $template
* @param array $vars
* @return Aspect\Render
*/
public function display($template, array $vars = array()) {
return $this->getTemplate($template)->display($vars);
}
/**
*
* @param string $template
* @param array $vars
* @internal param int $options
* @return mixed
*/
public function fetch($template, array $vars = array()) {
return $this->getTemplate($template)->fetch($vars);
}
/**
* Return template by name
*
* @param string $template
* @return Aspect\Template
*/
public function getTemplate($template) {
if(isset($this->_storage[ $template ])) {
if(($this->_options & self::CHECK_MTIME) && !$this->_check($template)) {
return $this->_storage[ $template ] = $this->compile($template);
} else {
return $this->_storage[ $template ];
}
} elseif($this->_options & self::FORCE_COMPILE) {
return $this->compile($template);
} else {
return $this->_storage[ $template ] = $this->_load($template);
}
}
/**
* Add custom template into storage
* @param Aspect\Render $template
*/
public function storeTemplate(Aspect\Render $template) {
$this->_storage[ $template->getName() ] = $template;
$template->setStorage($this);
}
/**
* Return template from storage or create if template doesn't exists.
*
* @param string $tpl
* @throws \RuntimeException
* @return Aspect\Template|mixed
*/
protected function _load($tpl) {
$file_name = $this->_getHash($tpl);
if(!is_file($this->_compile_dir."/".$file_name) || ($this->_options & self::CHECK_MTIME) && !$this->_check($tpl)) {
return $this->compile($tpl);
} else {
/** @var Aspect\Render $tpl */
$tpl = include($this->_compile_dir."/".$file_name);
$tpl->setStorage($this);
return $tpl;
}
}
/**
* @param string $template
* @return bool
*/
private function _check($template) {
return $this->_isActual($template, filemtime($this->_compile_dir."/".$this->_getHash($template)));
}
/**
* Check, if template is actual
* @param $template
* @param $compiled_time
* @return bool
*/
protected function _isActual($template, $compiled_time) {
clearstatcache(false, $template = $this->_getTemplatePath($template));
return filemtime($template) < $compiled_time;
}
/**
* Generate unique name of compiled template
*
* @param string $tpl
* @return string
*/
private function _getHash($tpl) {
$hash = $tpl.":".$this->_options;
return basename($tpl).".".crc32($hash).".".strlen($hash).".php";
}
/**
* Compile and save template
*
*
* @param string $tpl
* @throws \RuntimeException
* @return \Aspect\Template
*/
public function compile($tpl) {
$file_name = $this->_compile_dir."/".$this->_getHash($tpl);
$template = new Template($this, $this->_loadCode($tpl), $tpl);
$tpl_tmp = tempnam($this->_compile_dir, basename($tpl));
$tpl_fp = fopen($tpl_tmp, "w");
if(!$tpl_fp) {
throw new \RuntimeException("Can not open temporary file $tpl_tmp. Directory ".$this->_compile_dir." is writable?");
}
fwrite($tpl_fp, $template->getTemplateCode());
fclose($tpl_fp);
if(!rename($tpl_tmp, $file_name)) {
throw new \RuntimeException("Can not to move $tpl_tmp to $tpl");
}
return $template;
}
/**
* Remove all compiled templates. Warning! Do cleanup the compiled directory.
* @return int
* @api
*/
public function compileAll() {
//return FS::rm($this->_compile_dir.'/*');
}
/**
* @param string $tpl
* @return bool
* @api
*/
public function clearCompileTemplate($tpl) {
$file_name = $this->_compile_dir."/".$this->_getHash($tpl);
if(file_exists($file_name)) {
return unlink($file_name);
} else {
return true;
}
}
/**
* @return int
* @api
*/
public function clearAllCompiles() {
}
/**
* Get template path
* @param $tpl
* @return string
* @throws \RuntimeException
*/
private function _getTemplatePath($tpl) {
foreach($this->_tpl_path as $tpl_path) {
if(($path = stream_resolve_include_path($tpl_path."/".$tpl)) && strpos($path, $tpl_path) === 0) {
return $path;
}
}
throw new \RuntimeException("Template $tpl not found");
}
/**
* Code loader
*
* @param string $tpl
* @return string
* @throws \RuntimeException
*/
protected function _loadCode(&$tpl) {
return file_get_contents($tpl = $this->_getTemplatePath($tpl));
}
/**
* Compile code to template
*
* @param string $code
* @param string $name
* @return Aspect\Template
*/
public function compileCode($code, $name = 'Runtime compile') {
return new Template($this, $code, $name);
}
}

100
src/Aspect/BlackHole.php Normal file
View File

@ -0,0 +1,100 @@
<?php
namespace Aspect;
/**
* Class blackhole
* @author Ivan Shalganov <bzick@megagroup.ru>
* @copyright MegaGroup.ru
*/
class BlackHole implements \ArrayAccess, \Countable, \Iterator {
/**
* Whether a offset exists
* @link http://php.net/manual/en/arrayaccess.offsetexists.php
* @param mixed $offset <p>
* An offset to check for.
* @return boolean true on success or false on failure.
* The return value will be casted to boolean if non-boolean was returned.
*/
public function offsetExists($offset) {
return false;
}
/**
* Offset to retrieve
* @link http://php.net/manual/en/arrayaccess.offsetget.php
* @param mixed $offset
* @return mixed Can return all value types.
*/
public function offsetGet($offset) {
return null;
}
/**
* Offset to set
* @link http://php.net/manual/en/arrayaccess.offsetset.php
* @param mixed $offset
* @param mixed $value
* @return void
*/
public function offsetSet($offset, $value) {}
/**
* Offset to unset
* @link http://php.net/manual/en/arrayaccess.offsetunset.php
* @param mixed $offset
* @return void
*/
public function offsetUnset($offset) {}
/**
* Count elements of an object
* @link http://php.net/manual/en/countable.count.php
* @return int The custom count as an integer.
* The return value is cast to an integer.
*/
public function count() {
return 0;
}
/**
* Return the current element
* @link http://php.net/manual/en/iterator.current.php
* @return mixed Can return any type.
*/
public function current() {
return null;
}
/**
* Move forward to next element
* @link http://php.net/manual/en/iterator.next.php
* @return void Any returned value is ignored.
*/
public function next() {}
/**
* Return the key of the current element
* @link http://php.net/manual/en/iterator.key.php
* @return mixed scalar on success, or null on failure.
*/
public function key() {
return null;
}
/**
* Checks if current position is valid
* @link http://php.net/manual/en/iterator.valid.php
* @return boolean The return value will be casted to boolean and then evaluated.
* Returns true on success or false on failure.
*/
public function valid() {
return false;
}
/**
* Rewind the Iterator to the first element
* @link http://php.net/manual/en/iterator.rewind.php
* @return void Any returned value is ignored.
*/
public function rewind() {}
}

493
src/Aspect/Compiler.php Normal file
View File

@ -0,0 +1,493 @@
<?php
namespace Aspect;
use Aspect\Tokenizer;
use Aspect\Template;
use Aspect\Scope;
class Compiler {
/**
* Tag {include ...}
*
* @static
* @param Tokenizer $tokens
* @param Template $tpl
* @throws \Exception
* @return string
*/
public static function tagInclude(Tokenizer $tokens, Template $tpl) {
$p = $tpl->parseParams($tokens);
if(isset($p[0])) {
$file_name = $p[0];
} elseif (isset($p["file"])) {
$file_name = $p["file"];
} else {
throw new \Exception("{include} require 'file' parameter");
}
unset($p["file"], $p[0]);
if($p) {
return '$tpl->getStorage()->getTemplate('.$file_name.')->display('.self::_toArray($p).'+(array)$tpl);';
} else {
return '$tpl->getStorage()->getTemplate('.$file_name.')->display((array)$tpl);';
}
}
/**
* Open tag {if ...}
*
* @static
* @param Tokenizer $tokens
* @param Scope $scope
* @return string
*/
public static function ifOpen(Tokenizer $tokens, Scope $scope) {
$scope["else"] = false;
return 'if('.$scope->tpl->parseExp($tokens, true).') {';
}
/**
* Tag {elseif ...}
*
* @static
* @param Tokenizer $tokens
* @param Tokenizer $tokens
* @param Scope $scope
* @throws \Exception
* @internal param \Exception $
* @return string
*/
public static function tagElseIf(Tokenizer $tokens, Scope $scope) {
if($scope["else"]) {
throw new \Exception('Incorrect use of the tag {else if}');
}
return '} elseif('.$scope->tpl->parseExp($tokens, true).') {';
}
/**
* Tag {else}
*
* @param Tokenizer $tokens
* @param Scope $scope
* @internal param $
* @param Scope $scope
* @return string
*/
public static function tagElse(Tokenizer $tokens, Scope $scope) {
$scope["else"] = true;
return '} else {';
}
/**
* Open tag {foreach ...}
*
* @static
* @param Tokenizer $tokens
* @param Tokenizer $tokens
* @param Scope $scope
* @throws \Exception
* @internal param \Exception $
* @return string
*/
public static function foreachOpen(Tokenizer $tokens, Scope $scope) {
$p = array("index" => false, "first" => false, "last" => false);
$key = null;
$before = $body = array();
if($tokens->is(T_VARIABLE)) {
$from = $scope->tpl->parseVar($tokens, Template::DENY_MODS);
$prepend = "";
} elseif($tokens->is('[')) {
$from = $scope->tpl->parseArray($tokens);
$uid = '$v'.$scope->tpl->i++;
$prepend = $uid.' = '.$from.';';
$from = $uid;
} else {
if($tokens->valid()) {
throw new \Exception("Unexpected token '".$tokens->current()."' in 'foreach'");
} else {
throw new \Exception("Unexpected end of 'foreach'");
}
}
$tokens->get(T_AS);
$tokens->next();
$value = $scope->tpl->parseVar($tokens, Template::DENY_MODS | Template::DENY_ARRAY);
if($tokens->is(T_DOUBLE_ARROW)) {
$tokens->next();
$key = $value;
$value = $scope->tpl->parseVar($tokens, Template::DENY_MODS | Template::DENY_ARRAY);
}
$scope["after"] = array();
$scope["else"] = false;
while($token = $tokens->key()) {
$param = $tokens->get(T_STRING);
if(!isset($p[ $param ])) {
throw new \Exception("Unknown parameter '$param'");
}
$tokens->getNext("=");
$tokens->next();
$p[ $param ] = $scope->tpl->parseVar($tokens, Template::DENY_MODS | Template::DENY_ARRAY);
}
if($p["index"]) {
$before[] = $p["index"].' = 0';
$scope["after"][] = $p["index"].'++';
}
if($p["first"]) {
$before[] = $p["first"].' = true';
$scope["after"][] = $p["first"] .' && ('. $p["first"].' = false )';
}
if($p["last"]) {
$before[] = $p["last"].' = false';
$scope["uid"] = "v".$scope->tpl->i++;
$before[] = '$'.$scope["uid"]." = count($from)";
$body[] = 'if(!--$'.$scope["uid"].') '.$p["last"].' = true';
}
$before = $before ? implode("; ", $before).";" : "";
$body = $body ? implode("; ", $body).";" : "";
$scope["after"] = $scope["after"] ? implode("; ", $scope["after"]).";" : "";
if($key) {
return "$prepend if($from) { $before foreach($from as $key => $value) { $body";
} else {
return "$prepend if($from) { $before foreach($from as $value) { $body";
}
}
/**
* Tag {foreachelse}
*
* @param Tokenizer $tokens
* @param Scope $scope
* @internal param $
* @param Scope $scope
* @return string
*/
public static function foreachElse(Tokenizer $tokens, Scope $scope) {
$scope["no-break"] = $scope["no-continue"] = $scope["else"] = true;
return " {$scope['after']} } } else {";
}
/**
* Close tag {/foreach}
*
* @static
* @param Tokenizer $tokens
* @param Scope $scope
* @return string
*/
public static function foreachClose(Tokenizer $tokens, Scope $scope) {
if($scope["else"]) {
return '}';
} else {
return " {$scope['after']} } }";
}
}
/**
* @static
* @param Tokenizer $tokens
* @param Scope $scope
* @return string
* @throws \Exception
*/
public static function forOpen(Tokenizer $tokens, Scope $scope) {
$p = array("index" => false, "first" => false, "last" => false, "step" => 1, "to" => false, "max" => false, "min" => false);
$scope["after"] = $before = $body = array();
$i = array('', '');
$c = "";
$var = $scope->tpl->parseVar($tokens, Template::DENY_MODS);
$tokens->get("=");
$tokens->next();
$val = $scope->tpl->parseExp($tokens, true);
$p = $scope->tpl->parseParams($tokens, $p);
if(is_numeric($p["step"])) {
if($p["step"] > 0) {
$condition = "$var <= {$p['to']}";
if($p["last"]) $c = "($var + {$p['step']}) > {$p['to']}";
} elseif($p["step"] < 0) {
$condition = "$var >= {$p['to']}";
if($p["last"]) $c = "($var + {$p['step']}) < {$p['to']}";
} else {
throw new \Exception("Invalid step value");
}
} else {
$condition = "({$p['step']} > 0 && $var <= {$p['to']} || {$p['step']} < 0 && $var >= {$p['to']})";
if($p["last"]) $c = "({$p['step']} > 0 && ($var + {$p['step']}) <= {$p['to']} || {$p['step']} < 0 && ($var + {$p['step']}) >= {$p['to']})";
}
if($p["first"]) {
$before[] = $p["first"].' = true';
$scope["after"][] = $p["first"] .' && ('. $p["first"].' = false )';
}
if($p["last"]) {
$before[] = $p["last"].' = false';
$body[] = "if($c) {$p['last']} = true";
}
if($p["index"]) {
$i[0] .= $p["index"].' = 0,';
$i[1] .= $p["index"].'++,';
}
$scope["else"] = false;
$scope["else_cond"] = "$var==$val";
$before = $before ? implode("; ", $before).";" : "";
$body = $body ? implode("; ", $body).";" : "";
$scope["after"] = $scope["after"] ? implode("; ", $scope["after"]).";" : "";
return "$before for({$i[0]} $var=$val; $condition;{$i[1]} $var+={$p['step']}) { $body";
}
/**
* @static
* @param Tokenizer $tokens
* @param Scope $scope
* @return string
*/
public static function forElse(Tokenizer $tokens, Scope $scope) {
$scope["no-break"] = $scope["no-continue"] = true;
$scope["else"] = true;
return " } if({$scope['else_cond']}) {";
}
/**
* @static
* @param Tokenizer $tokens
* @param Scope $scope
* @return string
*/
public static function forClose(Tokenizer $tokens, Scope $scope) {
if($scope["else"]) {
return '}';
} else {
return " {$scope['after']} }";
}
}
/**
* @static
* @param Tokenizer $tokens
* @param Scope $scope
* @return string
*/
public static function whileOpen(Tokenizer $tokens, Scope $scope) {
return 'while('.$scope->tpl->parseExp($tokens, true).') {';
}
/**
* Open tag {switch}
*
* @static
* @param Tokenizer $tokens
* @param Scope $scope
* @return string
*/
public static function switchOpen(Tokenizer $tokens, Scope $scope) {
$scope["no-break"] = $scope["no-continue"] = true;
$scope["switch"] = 'switch('.$scope->tpl->parseExp($tokens, true).') {';
// lazy switch init
return '';
}
/**
* Tag {case ...}
*
* @static
* @param Tokenizer $tokens
* @param Scope $scope
* @return string
*/
public static function tagCase(Tokenizer $tokens, Scope $scope) {
$code = 'case '.$scope->tpl->parseExp($tokens, true).': ';
if($scope["switch"]) {
unset($scope["no-break"], $scope["no-continue"]);
$code = $scope["switch"]."\n".$code;
$scope["switch"] = "";
}
return $code;
}
/**
* Tag {continue}
*
* @static
* @param Tokenizer $tokens
* @param Scope $scope
* @throws \Exception
* @return string
*/
public static function tagContinue(Tokenizer $tokens, Scope $scope) {
if(empty($scope["no-continue"])) {
return 'continue;';
} else {
throw new \Exception("Incorrect use of the tag {continue}");
}
}
/**
* Tag {default}
*
* @static
* @return string
*/
public static function tagDefault(Tokenizer $tokens, Scope $scope) {
$code = 'default: ';
if($scope["switch"]) {
unset($scope["no-break"], $scope["no-continue"]);
$code = $scope["switch"]."\n".$code;
$scope["switch"] = "";
}
return $code;
}
/**
* Tag {break}
*
* @static
* @param Tokenizer $tokens
* @param Scope $scope
* @throws \Exception
* @return string
*/
public static function tagBreak(Tokenizer $tokens, Scope $scope) {
if(empty($scope["no-break"])) {
return 'break;';
} else {
throw new \Exception("Incorrect use of the tag {break}");
}
}
public static function tagExtends(Tokenizer $tokens, Template $tpl) {
if(!empty($tpl->_extends)) {
throw new \Exception("Only one {extends} allowed");
}
$p = $tpl->parseParams($tokens);
if(isset($p[0])) {
$tpl_name = $p[0];
} elseif (isset($p["file"])) {
$tpl_name = $p["file"];
} else {
throw new \Exception("{extends} require 'file' parameter");
}
$tpl->addPostCompile(__CLASS__."::extendBody");
$tpl->_extends = $tpl_name;
return '$parent = $tpl->getStorage()->getTemplate('.$tpl_name.');';
}
public static function extendBody(&$body, Template $tpl) {
$body = '<?php if(!isset($tpl->blocks)) {$tpl->blocks = array();} ob_start(); ?>'.$body.'<?php ob_end_clean(); $parent->blocks = &$tpl->blocks; $parent->display((array)$tpl); unset($tpl->blocks, $parent->blocks); ?>';
}
public static function tagBlockOpen(Tokenizer $tokens, Scope $scope) {
$p = $scope->tpl->parseParams($tokens);
if(isset($p["name"])) {
$scope["name"] = $p["name"];
} elseif (isset($p[0])) {
$scope["name"] = $p[0];
} else {
throw new \Exception("{block} require name parameter");
}
if($scope->closed) {
return 'isset($tpl->blocks['.$scope["name"].']) ? $tpl->blocks[] : "" ;';
} else {
return 'ob_start();';
}
}
public static function tagBlockClose(Tokenizer $tokens, Scope $scope) {
if(isset($scope->tpl->_extends)) {
$var = '$i'.$scope->tpl->i++;
return $var.' = ob_get_clean(); if('.$var.') $tpl->blocks['.$scope["name"].'] = '.$var.';';
} else {
return 'if(empty($tpl->blocks['.$scope["name"].'])) { ob_end_flush(); } else { print($tpl->blocks['.$scope["name"].']); ob_end_clean(); }';
}
}
/**
* Standard close tag {/...}
*
* @static
* @return string
*/
public static function stdClose() {
return '}';
}
/**
* Standard function tag parser
*
* @static
* @param $function
* @param Tokenizer $tokens
* @param Template $tpl
* @return string
*/
public static function stdFuncParser($function, Tokenizer $tokens, Template $tpl) {
return "echo $function(".self::_toArray($tpl->parseParams($tokens)).', $tpl);';
}
/**
* Standard function open tag parser
*
* @static
* @param Tokenizer $tokens
* @param Scope $scope
* @return string
*/
public static function stdFuncOpen(Tokenizer $tokens, Scope $scope) {
$scope["params"] = self::_toArray($scope->tpl->parseParams($tokens));
return 'ob_start();';
}
/**
* Standard function close tag parser
*
* @static
* @param Tokenizer $tokens
* @param Scope $scope
* @return string
*/
public static function stdFuncClose(Tokenizer $tokens, Scope $scope) {
return "echo ".$scope["function"].'('.$scope["params"].', ob_get_clean(), $tpl);';
}
private static function _toArray($params) {
$_code = array();
foreach($params as $k => $v) {
$_code[] = '"'.$k.'" => '.$v;
}
return 'array('.implode(",", $_code).')';
}
/**
* Tag {var ...}
*
* @static
* @param Tokenizer $tokens
* @param Template $tpl
* @return string
*/
public static function assign(Tokenizer $tokens, Template $tpl) {
return self::setVar($tokens, $tpl).';';
}
public static function setVar(Tokenizer $tokens, Template $tpl, $allow_array = true) {
$var = $tpl->parseVar($tokens, $tpl::DENY_MODS);
$tokens->get('=');
$tokens->next();
if($tokens->is("[") && $allow_array) {
return $var.'='.$tpl->parseArray($tokens);
} else {
return $var.'='.$tpl->parseExp($tokens, true);
}
}
}

17
src/Aspect/Func.php Normal file
View File

@ -0,0 +1,17 @@
<?php
namespace Aspect;
class Func {
public static function mailto($params) {
if(empty($params["address"])) {
trigger_error(E_USER_WARNING, "Modifier mailto: paramenter 'address' required");
return "";
}
if(empty($params["text"])) {
$params["text"] = $params["address"];
}
return '<a href="mailto:'.$params["address"].'">'.$params["text"].'</a>';
}
}

59
src/Aspect/Misc.php Normal file
View File

@ -0,0 +1,59 @@
<?php
namespace Aspect;
class Misc {
/**
* Create bit-mask from associative array use fully associative array possible keys with bit values
* @static
* @param array $values custom assoc array, ["a" => true, "b" => false]
* @param array $options possible values, ["a" => 0b001, "b" => 0b010, "c" => 0b100]
* @param int $mask the initial value of the mask
* @return int result, ( $mask | a ) & ~b
* @throws \RuntimeException if key from custom assoc doesn't exists into possible values
*/
public static function makeMask(array $values, array $options, $mask = 0) {
foreach($values as $value) {
if(isset($options[$value])) {
if($options[$value]) {
$mask |= $options[$value];
} else {
$mask &= ~$options[$value];
}
} else {
throw new \RuntimeException("Undefined parameter $value");
}
}
return $mask;
}
public static function clean($path) {
if(is_file($path)) {
unlink($path);
} elseif(is_dir($path)) {
$iterator = iterator_to_array(new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($path,
\FilesystemIterator::KEY_AS_PATHNAME | \FilesystemIterator::CURRENT_AS_FILEINFO | \FilesystemIterator::SKIP_DOTS),
\RecursiveIteratorIterator::CHILD_FIRST));
foreach($iterator as $file) {
/* @var \splFileInfo $file*/
if($file->isFile()) {
unlink($file->getRealPath());
} elseif($file->isDir()) {
rmdir($file->getRealPath());
}
}
}
}
public static function rm($path) {
self::clean($path);
if(is_dir($path)) {
rmdir($path);
}
}
public static function put($path, $content) {
file_put_contents($path, $content);
}
}

76
src/Aspect/Modifier.php Normal file
View File

@ -0,0 +1,76 @@
<?php
namespace Aspect;
class Modifier {
public static function dateFormat($date, $format = "%b %e, %Y") {
if(is_string($date) && !is_numeric($date)) {
$date = strtotime($date);
if(!$date) $date = time();
}
//dump($format, $date);
return strftime($format, $date);
}
public static function date($date, $format = "Y m d") {
if(is_string($date) && !is_numeric($date)) {
$date = strtotime($date);
if(!$date) $date = time();
}
return date($format, $date);
}
public static function escape($text, $type = 'html') {
switch($type) {
case "url":
return urlencode($text);
case "html";
return htmlspecialchars($text, ENT_COMPAT, 'UTF-8');
default:
return $text;
}
}
public static function unescape($text, $type = 'html') {
switch($type) {
case "url":
return urldecode($text);
case "html";
return htmlspecialchars_decode($text);
default:
return $text;
}
}
public static function defaultValue(&$value, $default = null) {
return ($value === null) ? $default : $value;
}
public static function truncate($string, $length = 80, $etc = '...', $break_words = false, $middle = false) {
$length -= min($length, strlen($etc));
if (!$break_words && !$middle) {
$string = preg_replace('/\s+?(\S+)?$/', '', substr($string, 0, $length + 1));
}
if (!$middle) {
return substr($string, 0, $length) . $etc;
}
return substr($string, 0, $length / 2) . $etc . substr($string, - $length / 2);
}
/**
* Strip spaces symbols on edge of string end multiple spaces into string
* @static
* @param string $str
* @param bool $to_line strip line ends
* @return string
*/
public static function strip($str, $to_line = false) {
$str = trim($str);
if($to_line) {
return preg_replace('#[\s]+#ms', ' ', $str);
} else {
return preg_replace('#[ \t]{2,}#', ' ', $str);
}
}
}

122
src/Aspect/Render.php Normal file
View File

@ -0,0 +1,122 @@
<?php
namespace Aspect;
use Aspect;
/**
* Primitive template
* @author Ivan Shalganov <bzick@megagroup.ru>
* @copyright MegaGroup.ru
*/
class Render extends \ArrayObject {
/**
* @var \Closure
*/
protected $_code;
/**
* Template name
* @var string
*/
protected $_name = 'runtime template';
/**
* @var Aspect
*/
protected $_aspect;
/**
* Signature of the template
* @var mixed
*/
protected $_fingerprint;
/**
* @param string $name template name
* @param callable $code template body
* @param mixed $fingerprint signature
*/
public function __construct($name, \Closure $code, $fingerprint = null) {
$this->_name = $name;
$this->_code = $code;
$this->_fingerprint = $fingerprint;
}
/**
* Set template storage
* @param Aspect $aspect
*/
public function setStorage(Aspect $aspect) {
$this->_aspect = $aspect;
}
/**
* Get template storage
* @return Aspect
*/
public function getStorage() {
return $this->_aspect;
}
/**
* @return string
*/
public function __toString() {
return "Template({$this->_name})";
}
/**
* Get template name
* @return string
*/
public function getName() {
return $this->_name;
}
/**
* Validate template version
* @param mixed $fingerprint of the template
* @return bool
*/
public function isValid($fingerprint) {
if($this->_fingerprint) {
return $fingerprint === $this->_fingerprint;
} else {
return true;
}
}
/**
* Execute template and write into output
* @param array $values for template
* @return Render
*/
public function display(array $values) {
$this->exchangeArray($values);
$this->_code->__invoke($this);
return $this;
}
/**
* Execute template and return result as string
* @param array $values for template
* @return string
* @throws \Exception
*/
public function fetch(array $values) {
ob_start();
try {
$this->display($values);
return ob_get_clean();
} catch (\Exception $e) {
ob_end_clean();
throw $e;
}
}
/**
* Stub
* @param $method
* @param $args
* @throws \BadMethodCallException
*/
public function __call($method, $args) {
throw new \BadMethodCallException("Unknown method ".$method);
}
}

69
src/Aspect/Scope.php Normal file
View File

@ -0,0 +1,69 @@
<?php
namespace Aspect;
/**
* Scope for blocks tags
*/
class Scope extends \ArrayObject {
public $line = 0;
public $name;
/**
* @var Template
*/
public $tpl;
public $closed = false;
public $is_next_close = false;
public $is_compiler = true;
private $_action;
/**
* @param string $name
* @param Template $tpl
* @param int $line
* @param array $action
*/
public function __construct($name, $tpl, $line, $action) {
$this->line = $line;
$this->name = $name;
$this->tpl = $tpl;
$this->_action = $action;
}
public function setFuncName($function) {
$this["function"] = $function;
$this->is_compiler = false;
}
public function open($tokenizer) {
return call_user_func($this->_action["open"], $tokenizer, $this);
}
public function hasTag($tag, $level) {
if(isset($this->_action["tags"][$tag])) {
if($level) {
return isset($this->_action["float_tags"][$tag]);
} else {
return true;
}
}
return false;
}
public function tag($tag, $tokenizer) {
return call_user_func($this->_action["tags"][$tag], $tokenizer, $this);
}
public function close($tokenizer) {
return call_user_func($this->_action["close"], $tokenizer, $this);
}
/**
* Count chars to close tag
* @todo
* @return int
*/
public function getDistanceToClose() {
return 1;
}
}

827
src/Aspect/Template.php Normal file
View File

@ -0,0 +1,827 @@
<?php
namespace Aspect;
use Aspect;
/**
* Aspect template compiler
*
* @author Ivan Shalganov <bzick@megagroup.ru>
* @copyright MegaGroup.ru
*/
class Template extends Render {
const DENY_ARRAY = 1;
const DENY_MODS = 2;
/**
* @var int shared counter
*/
public $i = 1;
/**
* Template PHP code
* @var string
*/
private $_body;
/**
* Call stack
* @var Scope[]
*/
private $_stack = array();
/**
* Template source
* @var string
*/
private $_src;
/**
* @var int
*/
private $_pos = 0;
private $_line = 1;
private $_trim = false;
private $_post = array();
/**
* @var bool
*/
private $_literal = false;
/**
* Options
* @var int
*/
private $_options = 0;
/** System variables {$smarty.<...>} or {$aspect.<...>}
* @var array
*/
public static $sysvar = array('$aspect' => 1, '$smarty' => 1);
/**
* @param Aspect $aspect Template storage
* @param string $code template source
* @param string $name template name
* @throws CompileException
*/
public function __construct(Aspect $aspect, $code, $name = "runtime template") {
$this->_src = $code;
$this->_name = $name;
$this->_aspect = $aspect;
$this->_options = $aspect->getOptions();
$pos = 0;
while(($start = strpos($code, '{', $pos)) !== false) { // search open-char of tags
switch($code[$start + 1]) { // check next char
case "\n": case "\r": case "\t": case " ": case "}": // ignore the tag
$pos = $start + 1; // trying finding tags after the current char
continue 2;
case "*": // if comment block
$end = strpos($code, '*}', $start); // finding end of the comment block
$frag = substr($code, $this->_pos, $start - $end); // read the comment block for precessing
$this->_line += substr_count($frag, "\n"); // count skipped lines
$pos = $end + 1; // trying finding tags after the comment block
continue 2;
}
$end = strpos($code, '}', $start); // search close-char of the tag
if(!$end) { // if unexpected end of template
throw new CompileException("Unclosed tag in line $this->_line", 0, 1, $this->_name, $this->_line);
}
$frag = substr($code, $this->_pos, $start - $this->_pos); // variable $frag contains chars after last '}' and new '{'
$tag = substr($code, $start, $end - $start + 1); // variable $tag contains aspect tag '{...}'
$this->_line += substr_count($code, "\n", $this->_pos, $end - $start + 1); // count lines in $frag and $tag (using original text $code)
$pos = $this->_pos = $end + 1; // move search pointer to end of the tag
if($this->_trim) { // if previous tag has trim flag
$frag = ltrim($frag);
}
$tag = $this->_tag($tag, $this->_trim);
if($this->_trim) { // if current tag has trim flag
$frag = rtrim($frag);
}
$this->_body .= $frag.$tag;
}
$this->_body .= substr($code, $this->_pos);
if($this->_stack) {
$_names = array();
$_line = 0;
foreach($this->_stack as $scope) {
if(!$_line) {
$_line = $scope->line;
}
$_names[] = $scope->name.' (line '.$scope->line.')';
}
throw new CompileException("Unclosed tags: ".implode(", ", $_names), 0, 1, $this->_name, $_line);
}
unset($this->_src);
if($this->_post) {
foreach($this->_post as $cb) {
call_user_func_array($cb, array(&$this->_body, $this));
}
}
}
public function addPostCompile($cb) {
$this->_post[] = $cb;
}
/**
* Return PHP code of template
* @return string
*/
public function getBody() {
return $this->_body;
}
/**
* Return PHP code of PHP file of template
* @return string
*/
public function getTemplateCode() {
return "<?php \n".
"/** Aspect template '".$this->_name."' compiled at ".date('Y-m-d H:i:s')." */\n".
"return new Aspect\\Render('{$this->_name}', ".$this->_getClosureCode().", ".$this->_options.");\n";
}
/**
* Return closure code
* @return string
*/
private function _getClosureCode() {
return "function (\$tpl) {\n?>{$this->_body}<?php\n}";
}
/**
* Runtime execute template.
*
* @param array $values input values
* @throws CompileException
* @return Render
*/
public function display(array $values) {
if(!$this->_code) {
// evaluate template's code
eval("\$this->_code = ".$this->_getClosureCode().";");
if(!$this->_code) {
throw new CompileException("Fatal error while creating the template");
}
}
return parent::display($values);
}
/**
* Execute template and return result as string
* @param array $values for template
* @throws CompileException
* @return string
*/
public function fetch(array $values) {
if(!$this->_code) {
eval("\$this->_code = ".$this->_getClosureCode().";");
if(!$this->_code) {
throw new CompileException("Fatal error while creating the template");
}
}
return parent::fetch($values);
}
/**
* Internal tags router
* @param string $src
* @param bool $trim
* @throws UnexpectedException
* @throws CompileException
* @throws SecurityException
* @return string
*/
private function _tag($src, &$trim = false) {
if($src[strlen($src) - 2] === "-") {
$token = substr($src, 1, -2);
$trim = true;
} else {
$token = substr($src, 1, -1);
$trim = false;
}
$token = trim($token);
if($this->_literal) {
if($token === '/literal') {
$this->_literal = false;
return '';
} else {
return $src;
}
}
$tokens = new Tokenizer($token);
try {
switch($token[0]) {
case '"':
case '\'':
case '$':
$code = "echo ".$this->parseExp($tokens).";";
break;
case '/':
$code = $this->_end($tokens);
break;
default:
$code = $this->_parseAct($tokens);
if($code === null) {
}
break;
}
if($tokens->key()) { // if tokenizer still have tokens
throw new UnexpectedException($tokens);
}
if($this->_options & Aspect::INCLUDE_SOURCES) {
return "<?php\n/* {$this->_name}:{$this->_line}: {$src} */\n {$code} ?>";
} else {
return "<?php {$code} ?>";
}
} catch (\LogicException $e) {
throw new SecurityException($e->getMessage()." in {$this} line {$this->_line}, near '{".$tokens->getSnippetAsString(0,0)."' <- there", 0, 1, $this->_name, $this->_line, $e);
} catch (\Exception $e) {
throw new CompileException($e->getMessage()." in {$this} line {$this->_line}, near '{".$tokens->getSnippetAsString(0,0)."' <- there", 0, 1, $this->_name, $this->_line, $e);
}
}
/**
* Close tag handler
* @param Tokenizer $tokens
* @return mixed
* @throws TokenizeException
*/
private function _end(Tokenizer $tokens) {
$name = $tokens->getNext(Tokenizer::MACRO_STRING);
$tokens->next();
if(!$this->_stack) {
throw new TokenizeException("Unexpected closing of the tag '$name', the tag hasn't been opened");
}
/** @var Scope $scope */
$scope = array_pop($this->_stack);
if($scope->name !== $name) {
throw new TokenizeException("Unexpected closing of the tag '$name' (expecting closing of the tag {$scope->name}, opened on line {$scope->line})");
}
return $scope->close($tokens);
}
/**
* Parse action {action ...} or {action(...) ...}
*
* @static
* @param Tokenizer $tokens
* @throws TokenizeException
* @return string
*/
private function _parseAct(Tokenizer $tokens) {
if($tokens->is(Tokenizer::MACRO_STRING)) {
$action = $tokens->current();
} else {
return 'echo '.$this->parseExp($tokens).';';
}
if($action === "literal") {
$this->_literal = true;
$tokens->next();
return '';
}
if($tokens->isNext("(")) {
return "echo ".$this->parseExp($tokens).";";
}
if($act = $this->_aspect->getFunction($action)) {
$tokens->next();
switch($act["type"]) {
case Aspect::BLOCK_COMPILER:
$scope = new Scope($action, $this, $this->_line, $act);
array_push($this->_stack, $scope);
return $scope->open($tokens);
case Aspect::INLINE_COMPILER:
return call_user_func($act["parser"], $tokens, $this);
case Aspect::INLINE_FUNCTION:
return call_user_func($act["parser"], $act["function"], $tokens, $this);
case Aspect::BLOCK_FUNCTION:
$scope = new Scope($action, $this, $this->_line, $act);
$scope->setFuncName($act["function"]);
array_push($this->_stack, $scope);
return $scope->open($tokens);
}
}
for($j = $i = count($this->_stack)-1; $i>=0; $i--) {
if($this->_stack[$i]->hasTag($action, $j - $i)) {
$tokens->next();
return $this->_stack[$i]->tag($action, $tokens);
}
}
if($tags = $this->_aspect->getTagOwners($action)) {
throw new TokenizeException("Unexpected tag '$action' (this tag can be used with '".implode("', '", $tags)."')");
} else {
throw new TokenizeException("Unexpected tag $action");
}
}
/**
* Parse expressions. The mix of math operations, boolean operations, scalars, arrays and variables.
*
* @static
* @param Tokenizer $tokens
* @param bool $required
* @throws \LogicException
* @throws UnexpectedException
* @throws TokenizeException
* @return string
*/
public function parseExp(Tokenizer $tokens, $required = false) {
$_exp = "";
$brackets = 0;
$term = false;
$cond = false;
while($tokens->valid()) {
if(!$term && $tokens->is(Tokenizer::MACRO_SCALAR, '"', '`', T_ENCAPSED_AND_WHITESPACE)) {
$_exp .= $this->parseScalar($tokens, true);
$term = 1;
} elseif(!$term && $tokens->is(T_VARIABLE)) {
$pp = $tokens->isPrev(Tokenizer::MACRO_INCDEC);
$_exp .= $this->parseVar($tokens, 0, $only_var);
if($only_var && !$pp) {
$term = 2;
} else {
$term = 1;
}
} elseif(!$term && $tokens->is("(")) {
$_exp .= $tokens->getAndNext();
$brackets++;
$term = false;
} elseif($term && $tokens->is(")")) {
if(!$brackets) {
break;
}
$brackets--;
$_exp .= $tokens->getAndNext();
$term = 1;
} elseif(!$term && $tokens->is(T_STRING)) {
if($tokens->isSpecialVal()) {
$_exp .= $tokens->getAndNext();
} elseif($tokens->isNext("(")) {
$func = $this->_aspect->getModifier($tokens->current());
$tokens->next();
$_exp .= $func.$this->parseArgs($tokens);
} else {
break;
}
$term = 1;
} elseif(!$term && $tokens->is(T_ISSET, T_EMPTY)) {
$_exp .= $tokens->getAndNext();
if($tokens->is("(") && $tokens->isNext(T_VARIABLE)) {
$_exp .= $this->parseArgs($tokens);
} else {
throw new TokenizeException("Unexpected token ".$tokens->getNext().", isset() and empty() accept only variables");
}
$term = 1;
} elseif(!$term && $tokens->is(Tokenizer::MACRO_UNARY)) {
if(!$tokens->isNext(T_VARIABLE, T_DNUMBER, T_LNUMBER, T_STRING, T_ISSET, T_EMPTY)) {
break;
}
$_exp .= $tokens->getAndNext();
$term = 0;
} elseif($tokens->is(Tokenizer::MACRO_BINARY)) {
if(!$term) {
throw new UnexpectedException($tokens);
}
if($tokens->isLast()) {
break;
}
if($tokens->is(Tokenizer::MACRO_COND)) {
if($cond) {
break;
}
$cond = true;
} elseif ($tokens->is(Tokenizer::MACRO_BOOLEAN)) {
$cond = false;
}
$_exp .= " ".$tokens->getAndNext()." ";
$term = 0;
} elseif($tokens->is(Tokenizer::MACRO_INCDEC)) {
if($term === 2) {
$term = 1;
} elseif(!$tokens->isNext(T_VARIABLE)) {
break;
}
$_exp .= $tokens->getAndNext();
} elseif($term && !$cond && !$tokens->isLast()) {
if($tokens->is(Tokenizer::MACRO_EQUALS) && $term === 2) {
if($this->_options & Aspect::DENY_SET_VARS) {
throw new \LogicException("Forbidden to set a variable");
}
$_exp .= ' '.$tokens->getAndNext().' ';
$term = 0;
} else {
break;
}
} else {
break;
}
}
if($term === 0) {
throw new UnexpectedException($tokens);
}
if($brackets) {
throw new TokenizeException("Brackets don't match");
}
if($required && $_exp === "") {
throw new UnexpectedException($tokens);
}
return $_exp;
}
/**
* Parse variable
* $var.foo[bar]["a"][1+3/$var]|mod:3:"w":$var3|mod3
*
* @see parseModifier
* @static
* @param Tokenizer $tokens
* @param int $deny
* @param bool $pure_var
* @throws \LogicException
* @return string
*/
public function parseVar(Tokenizer $tokens, $deny = 0, &$pure_var = true) {
$var = $tokens->get(T_VARIABLE);
$pure_var = true;
if(isset(self::$sysvar[ $var ])) {
$_var = $this->_parseSystemVar($tokens);
} else {
$_var = '$tpl["'.ltrim($var,'$').'"]';
}
$tokens->next();
while($t = $tokens->key()) {
if($t === "." && !($deny & self::DENY_ARRAY)) {
$key = $tokens->getNext();
if($tokens->is(T_VARIABLE)) {
$key = "[ ".$this->parseVar($tokens, self::DENY_ARRAY)." ]";
} elseif($tokens->is(Tokenizer::MACRO_STRING)) {
if($tokens->isNext("(")) {
$key = "[".$this->parseExp($tokens)."]";
} else {
$key = '["'.$key.'"]';
$tokens->next();
}
} elseif($tokens->is(Tokenizer::MACRO_SCALAR, '"')) {
$key = "[".$this->parseScalar($tokens, false)."]";
} else {
break;
}
$_var .= $key;
} elseif($t === "[" && !($deny & self::DENY_ARRAY)) {
$tokens->next();
if($tokens->is(Tokenizer::MACRO_STRING)) {
if($tokens->isNext("(")) {
$key = "[".$this->parseExp($tokens)."]";
} else {
$key = '["'.$tokens->current().'"]';
$tokens->next();
}
} else {
$key = "[".$this->parseExp($tokens, true)."]";
}
$tokens->get("]");
$tokens->next();
$_var .= $key;
} elseif($t === "|" && !($deny & self::DENY_MODS)) {
$pure_var = false;
return $this->parseModifier($tokens, $_var);
} elseif($t === T_OBJECT_OPERATOR) {
$prop = $tokens->getNext(T_STRING);
if($tokens->isNext("(")) {
if($this->_options & Aspect::DENY_METHODS) {
throw new \LogicException("Forbidden to call methods");
}
$pure_var = false;
$tokens->next();
$_var .= '->'.$prop.$this->parseArgs($tokens);
} else {
$tokens->next();
$_var .= '->'.$prop;
}
} elseif($t === T_DNUMBER) {
$_var .= '['.substr($tokens->getAndNext(), 1).']';
} elseif($t === "?") {
$pure_var = false;
$tokens->next();
if($tokens->is(":")) {
$tokens->next();
return '(empty('.$_var.') ? ('.$this->parseExp($tokens, true).') : '.$_var.')';
} else {
return '!empty('.$_var.')';
}
} elseif($t === "!") {
$pure_var = false;
$tokens->next();
return 'isset('.$_var.')';
} else {
break;
}
}
return $_var;
}
/**
* Parse scalar values
*
* @param Tokenizer $tokens
* @param bool $allow_mods
* @return string
* @throws TokenizeException
*/
public function parseScalar(Tokenizer $tokens, $allow_mods = true) {
$_scalar = "";
if($token = $tokens->key()) {
switch($token) {
case T_CONSTANT_ENCAPSED_STRING:
case T_LNUMBER:
case T_DNUMBER:
$_scalar .= $tokens->getAndNext();
break;
case T_ENCAPSED_AND_WHITESPACE:
case '"':
$_scalar .= $this->parseSubstr($tokens);
break;
default:
throw new TokenizeException("Unexpected scalar token '".$tokens->current()."'");
}
if($allow_mods && $tokens->is("|")) {
return $this->parseModifier($tokens, $_scalar);
}
}
return $_scalar;
}
/**
* Parse string with or without variable
*
* @param Tokenizer $tokens
* @throws UnexpectedException
* @return string
*/
public function parseSubstr(Tokenizer $tokens) {
ref: {
if($tokens->is('"',"`")) {
$p = $tokens->p;
$stop = $tokens->current();
$_str = '"';
$tokens->next();
while($t = $tokens->key()) {
if($t === T_ENCAPSED_AND_WHITESPACE) {
$_str .= $tokens->current();
$tokens->next();
} elseif($t === T_VARIABLE) {
$_str .= '".$tpl["'.substr($tokens->current(), 1).'"]."';
$tokens->next();
} elseif($t === T_CURLY_OPEN) {
$tokens->getNext(T_VARIABLE);
$_str .= '".('.$this->parseExp($tokens).')."';
} elseif($t === "}") {
$tokens->next();
} elseif($t === $stop) {
$tokens->next();
return $_str.'"';
} else {
break;
}
}
if($more = $this->_getMoreSubstr($stop)) {
$tokens->append("}".$more, $p);
goto ref;
}
throw new UnexpectedException($tokens);
} elseif($tokens->is(T_CONSTANT_ENCAPSED_STRING)) {
return $tokens->getAndNext();
} elseif($tokens->is(T_ENCAPSED_AND_WHITESPACE)) {
$p = $tokens->p;
if($more = $this->_getMoreSubstr($tokens->curr[1][0])) {
$tokens->append("}".$more, $p);
goto ref;
}
throw new UnexpectedException($tokens);
} else {
return "";
}
}
}
private function _getMoreSubstr($after) {
$end = strpos($this->_src, $after, $this->_pos);
$end = strpos($this->_src, "}", $end);
if(!$end) {
return false;
}
$fragment = substr($this->_src, $this->_pos, $end - $this->_pos);
$this->_pos = $end + 1;
return $fragment;
}
/**
* Parse modifiers
* |modifier:1:2.3:'string':false:$var:(4+5*$var3)|modifier2:"str {$var+3} ing":$arr.item
*
* @param Tokenizer $tokens
* @param $value
* @throws \LogicException
* @throws \Exception
* @return string
*/
public function parseModifier(Tokenizer $tokens, $value) {
while($tokens->is("|")) {
$mods = $this->_aspect->getModifier( $tokens->getNext(Tokenizer::MACRO_STRING) );
$tokens->next();
$args = array();
while($tokens->is(":")) {
$token = $tokens->getNext(Tokenizer::MACRO_SCALAR, T_VARIABLE, '"', Tokenizer::MACRO_STRING, "(", "[");
if($tokens->is(Tokenizer::MACRO_SCALAR) || $tokens->isSpecialVal()) {
$args[] = $token;
$tokens->next();
} elseif($tokens->is(T_VARIABLE)) {
$args[] = $this->parseVar($tokens, self::DENY_MODS);
} elseif($tokens->is('"', '`', T_ENCAPSED_AND_WHITESPACE)) {
$args[] = $this->parseSubstr($tokens);
} elseif($tokens->is('(')) {
$args[] = $this->parseExp($tokens);
} elseif($tokens->is('[')) {
$args[] = $this->parseArray($tokens);
} elseif($tokens->is(T_STRING) && $tokens->isNext('(')) {
$args[] = $tokens->getAndNext().$this->parseArgs($tokens);
} else {
break;
}
}
if($args) {
$value = $mods.'('.$value.', '.implode(", ", $args).')';
} else {
$value = $mods.'('.$value.')';
}
}
return $value;
}
/**
* Parse array
* [1, 2.3, 5+7/$var, 'string', "str {$var+3} ing", $var2, []]
*
* @param Tokenizer $tokens
* @throws UnexpectedException
* @return string
*/
public function parseArray(Tokenizer $tokens) {
if($tokens->is("[")) {
$_arr = "array(";
$key = $val = false;
$tokens->next();
while($tokens->valid()) {
if($tokens->is(',') && $val) {
$key = true;
$val = false;
$_arr .= $tokens->getAndNext().' ';
} elseif($tokens->is(Tokenizer::MACRO_SCALAR, T_VARIABLE, T_STRING, T_EMPTY, T_ISSET, "(") && !$val) {
$_arr .= $this->parseExp($tokens, true);
$key = false;
$val = true;
} elseif($tokens->is('"') && !$val) {
$_arr .= $this->parseSubstr($tokens);
$key = false;
$val = true;
} elseif($tokens->is(T_DOUBLE_ARROW) && $val) {
$_arr .= ' '.$tokens->getAndNext().' ';
$key = true;
$val = false;
} elseif(!$val && $tokens->is('[')) {
$_arr .= $this->parseArray($tokens);
$key = false;
$val = true;
} elseif($tokens->is(']') && !$key) {
$tokens->next();
return $_arr.')';
} else {
break;
}
}
}
throw new UnexpectedException($tokens);
}
/**
* Parse system variable, like $aspect, $smarty
*
* @param Tokenizer $tokens
* @throws \LogicException
* @return mixed|string
*/
private function _parseSystemVar(Tokenizer $tokens) {
$tokens->getNext(".");
$key = $tokens->getNext(T_STRING, T_CONST);
switch($key) {
case 'get': return '$_GET';
case 'post': return '$_POST';
case 'cookies': return '$_COOKIES';
case 'session': return '$_SESSION';
case 'request': return '$_REQUEST';
case 'now': return 'time()';
case 'line': return $this->_line;
case 'tpl_name': return '$tpl->getName()';
case 'const':
$tokens->getNext(".");
return $tokens->getNext(T_STRING);
default:
throw new \LogicException("Unexpected key '".$tokens->current()."' in system variable");
}
}
/**
* Parse argument list
* (1 + 2.3, 'string', $var, [2,4])
*
* @static
* @param Tokenizer $tokens
* @throws TokenizeException
* @return string
*/
public function parseArgs(Tokenizer $tokens) {
$_args = "(";
$tokens->next();
$arg = $colon = false;
while($tokens->valid()) {
if(!$arg && $tokens->is(T_VARIABLE, T_STRING, "(", Tokenizer::MACRO_SCALAR, '"', Tokenizer::MACRO_UNARY, Tokenizer::MACRO_INCDEC)) {
$_args .= $this->parseExp($tokens, true);
$arg = true;
$colon = false;
} elseif(!$arg && $tokens->is('[')) {
$_args .= $this->parseArray($tokens);
$arg = true;
$colon = false;
} elseif($arg && $tokens->is(',')) {
$_args .= $tokens->getAndNext().' ';
$arg = false;
$colon = true;
} elseif(!$colon && $tokens->is(')')) {
$tokens->next();
return $_args.')';
} else {
break;
}
}
throw new TokenizeException("Unexpected token '".$tokens->current()."' in argument list");
}
/**
* Parse parameters as $key=$value
* param1=$var param2=3 ...
*
* @static
* @param Tokenizer $tokens
* @param array $defaults
* @throws \Exception
* @return array
*/
public function parseParams(Tokenizer $tokens, array $defaults = null) {
$params = array();
while($tokens->valid()) {
if($tokens->is(Tokenizer::MACRO_STRING)) {
$key = $tokens->getAndNext();
if($defaults && !isset($defaults[$key])) {
throw new \Exception("Unknown parameter '$key'");
}
if($tokens->is("=")) {
$tokens->next();
$params[ $key ] = $this->parseExp($tokens);
} else {
$params[ $key ] = true;
$params[] = "'".$key."'";
}
} elseif($tokens->is(Tokenizer::MACRO_SCALAR, '"', '`', T_VARIABLE, "[", '(')) {
$params[] = $this->parseExp($tokens);
} else {
break;
}
}
if($defaults) {
$params += $defaults;
}
return $params;
}
}
class CompileException extends \ErrorException {}
class SecurityException extends CompileException {}

731
src/Aspect/Tokenizer.php Normal file
View File

@ -0,0 +1,731 @@
<?php
namespace Aspect;
defined('T_INSTEADOF') || define('T_INSTEADOF', 341);
defined('T_TRAIT') || define('T_TRAIT', 355);
defined('T_TRAIT_C') || define('T_TRAIT_C', 365);
/**
* This iterator cannot be rewinded.
* Each token have structure
* - Token (constant T_* or text)
* - Token name (textual representation of the token)
* - Whitespace (whitespace symbols after token)
* - Line number of the token
*
* @see http://php.net/tokenizer
* @property array $prev the previous token
* @property array $curr the current token
* @property array $next the next token
*/
class Tokenizer {
const TOKEN = 0;
const TEXT = 1;
const WHITESPACE = 2;
const LINE = 3;
/**
* Strip whitespace tokens (default)
*/
const DECODE_TEXT = 0;
/**
* Strip whitespace tokens, exclude newlines
*/
const DECODE_NEW_LINES = 1;
/**
* Allow all whitespace tokens
*/
const DECODE_WHITESPACES = 2;
/**
* Decode mask
*/
const DECODE = 3;
/**
* Strip duplicate whitespaces. For example \n\n => \n
*/
const FILTER_DUP_WHITESPACES = 128;
/**
* Filter mask
*/
const FILTERS = 4080;
/**
* Some text value: foo, bar, new, class ...
*/
const MACRO_STRING = 1000;
/**
* Unary operation: ~, !, ^
*/
const MACRO_UNARY = 1001;
/**
* Binary operation (operation between two values): +, -, *, /, &&, or , ||, >=, !=, ...
*/
const MACRO_BINARY = 1002;
/**
* Equal operation
*/
const MACRO_EQUALS = 1003;
/**
* Scalar values (such as int, float, escaped strings): 2, 0.5, "foo", 'bar\'s'
*/
const MACRO_SCALAR = 1004;
/**
* Increment or decrement: ++ --
*/
const MACRO_INCDEC = 1005;
/**
* Boolean operations: &&, ||, or, xor
*/
const MACRO_BOOLEAN = 1006;
/**
* Math operation
*/
const MACRO_MATH = 1007;
/**
* Condition operation
*/
const MACRO_COND = 1008;
public $tokens;
public $p = 0;
private $_max = 0;
private $_last_no = 0;
/**
* @see http://docs.php.net/manual/en/tokens.php
* @var array groups of tokens
*/
private static $_macros = array(
self::MACRO_STRING => array(
\T_ABSTRACT => 1, \T_ARRAY => 1, \T_AS => 1, \T_BREAK => 1, \T_BREAK => 1, \T_CASE => 1,
\T_CATCH => 1, \T_CLASS => 1, \T_CLASS_C => 1, \T_CLONE => 1, \T_CONST => 1, \T_CONTINUE => 1,
\T_DECLARE => 1, \T_DEFAULT => 1, \T_DIR => 1, \T_DO => 1, \T_ECHO => 1, \T_ELSE => 1,
\T_ELSEIF => 1, \T_EMPTY => 1, \T_ENDDECLARE => 1, \T_ENDFOR => 1, \T_ENDFOREACH => 1, \T_ENDIF => 1,
\T_ENDSWITCH => 1, \T_ENDWHILE => 1, \T_EVAL => 1, \T_EXIT => 1, \T_EXTENDS => 1, \T_FILE => 1,
\T_FINAL => 1, \T_FOR => 1, \T_FOREACH => 1, \T_FUNCTION => 1, \T_FUNC_C => 1, \T_GLOBAL => 1,
\T_GOTO => 1, \T_HALT_COMPILER => 1, \T_IF => 1, \T_IMPLEMENTS => 1, \T_INCLUDE => 1, \T_INCLUDE_ONCE => 1,
\T_INSTANCEOF => 1, \T_INSTEADOF => 1, \T_INTERFACE => 1, \T_ISSET => 1, \T_LINE => 1, \T_LIST => 1,
\T_LOGICAL_AND => 1, \T_LOGICAL_OR => 1, \T_LOGICAL_XOR => 1, \T_METHOD_C => 1, \T_NAMESPACE => 1, \T_NS_C => 1,
\T_NEW => 1, \T_PRINT => 1, \T_PRIVATE => 1, \T_PUBLIC => 1, \T_PROTECTED => 1, \T_REQUIRE => 1,
\T_REQUIRE_ONCE => 1,\T_RETURN => 1, \T_RETURN => 1, \T_STRING => 1, \T_SWITCH => 1, \T_THROW => 1,
\T_TRAIT => 1, \T_TRAIT_C => 1, \T_TRY => 1, \T_UNSET => 1, \T_UNSET => 1, \T_VAR => 1,
\T_WHILE => 1
),
self::MACRO_INCDEC => array(
\T_INC => 1, \T_DEC => 1
),
self::MACRO_UNARY => array(
"!" => 1, "~" => 1, "-" => 1
),
self::MACRO_BINARY => array(
\T_BOOLEAN_AND => 1, \T_BOOLEAN_OR => 1, \T_IS_GREATER_OR_EQUAL => 1, \T_IS_EQUAL => 1, \T_IS_IDENTICAL => 1,
\T_IS_NOT_EQUAL => 1,\T_IS_NOT_IDENTICAL => 1, \T_IS_SMALLER_OR_EQUAL => 1, \T_LOGICAL_AND => 1,
\T_LOGICAL_OR => 1, \T_LOGICAL_XOR => 1, \T_SL => 1, \T_SR => 1,
"+" => 1, "-" => 1, "*" => 1, "/" => 1, ">" => 1, "<" => 1, "^" => 1, "%" => 1, "&" => 1
),
self::MACRO_BOOLEAN => array(
\T_LOGICAL_OR => 1, \T_LOGICAL_XOR => 1, \T_BOOLEAN_AND => 1, \T_BOOLEAN_OR => 1
),
self::MACRO_MATH => array(
"+" => 1, "-" => 1, "*" => 1, "/" => 1, "^" => 1, "%" => 1, "&" => 1, "|" => 1
),
self::MACRO_COND => array(
\T_IS_EQUAL => 1, \T_IS_IDENTICAL => 1, ">" => 1, "<" => 1, \T_SL => 1, \T_SR => 1,
\T_IS_NOT_EQUAL => 1,\T_IS_NOT_IDENTICAL => 1, \T_IS_SMALLER_OR_EQUAL => 1,
),
self::MACRO_EQUALS => array(
\T_AND_EQUAL => 1, \T_CONCAT_EQUAL => 1,\T_DIV_EQUAL => 1, \T_MINUS_EQUAL => 1, \T_MOD_EQUAL => 1,
\T_MUL_EQUAL => 1, \T_OR_EQUAL => 1, \T_PLUS_EQUAL => 1, \T_SL_EQUAL => 1, \T_SR_EQUAL => 1,
\T_XOR_EQUAL => 1, '=' => 1
),
self::MACRO_SCALAR => array(
\T_LNUMBER => 1, \T_DNUMBER => 1, \T_CONSTANT_ENCAPSED_STRING => 1
)
);
/**
* Special tokens
* @var array
*/
private static $spec = array(
'true' => 1, 'false' => 1, 'null' => 1, 'TRUE' => 1, 'FALSE' => 1, 'NULL' => 1
);
/**
* Translate expression to tokens list.
*
* @static
* @param string $query
* @param int $options one of DECODE_*, FILTER_* constants
* @return array
*/
public static function decode($query, $options = 0) {
$tokens = array(-1 => array(\T_WHITESPACE, '', '', 1));
$_tokens = token_get_all("<?php ".$query);
$line = 1;
$decode = $options & self::DECODE;
array_shift($_tokens);
$i = 0;
foreach($_tokens as &$token) {
if(is_string($token)) {
$tokens[] = array(
$token,
$token,
"",
$line,
);
$i++;
} elseif ($token[0] === \T_WHITESPACE) {
if(!$decode) {
$tokens[$i-1][2] = $token[1];
} elseif($decode == 1) {
if(strpos($token[1], "\n") !== false) {
$frags = explode("\n", $token[1]);
$ws = array_shift($frags);
if($ws) {
$tokens[$i-1][2] .= $ws;
}
foreach($frags as $frag) {
$tokens[] = array(
\T_WHITESPACE,
"\n",
$frag,
$line = $token[2],
);
$i++;
}
} else {
$tokens[$i-1][2] .= $token[1];
}
} else {
$tokens[] = array(
$token[0],
$token[1],
"",
$line = $token[2],
);
$i++;
}
} else {
$tokens[] = array(
$token[0],
$token[1],
"",
$line = $token[2],
);
$i++;
}
}
if($options & self::FILTER_DUP_WHITESPACES) {
$prev = null;
foreach($tokens as &$token) {
if($token[0] === T_WHITESPACE && $prev && $prev[0] === T_WHITESPACE) {
$prev = false;
}
$prev = &$token;
}
$tokens = array_values(array_filter($tokens));
}
return $tokens;
}
public function __construct($query, $decode = 0) {
$this->tokens = self::decode($query, $decode);
unset($this->tokens[-1]);
$this->_max = count($this->tokens) - 1;
$this->_last_no = $this->tokens[$this->_max][3];
}
/**
* Set the filter callback. Token may be changed by reference or skipped if callback return false.
*
* @param $callback
*/
public function filter(\Closure $callback) {
$tokens = array();
foreach($this->tokens as $token) {
if($callback($token) !== false) {
$tokens[] = $token;
}
}
$this->tokens = $tokens;
$this->_max = count($this->tokens) - 1;
}
/**
* Return the current element
*
* @link http://php.net/manual/en/iterator.current.php
* @return mixed Can return any type.
*/
public function current() {
return $this->curr[1];
}
/**
* Move forward to next element
*
* @link http://php.net/manual/en/iterator.next.php
* @return Tokenizer
*/
public function next() {
if($this->p > $this->_max) {
return $this;
}
$this->p++;
unset($this->prev, $this->curr, $this->next);
return $this;
}
/**
* Check token type. If token type is one of expected types return true. Otherwise return false
*
* @param array $expects
* @param string|int $token
* @return bool
*/
private function _valid($expects, $token) {
foreach($expects as $expect) {
if(is_string($expect) || $expect < 1000) {
if($expect === $token) {
return true;
}
} else {
if(isset(self::$_macros[ $expect ][ $token ])) {
return true;
}
}
}
return false;
}
/**
* If the next token is a valid one, move the position of cursor one step forward. Otherwise throws an exception.
* @param array $tokens
* @throws TokenizeException
* @return mixed
*/
public function _next($tokens) {
$this->next();
if(!$this->curr) {
throw new TokenizeException("Unexpected end of expression");
}
if($tokens) {
if($this->_valid($tokens, $this->key())) {
return;
}
} else {
return;
}
if(count($tokens) == 1 && is_string($tokens[0])) {
$expect = ", expect '".$tokens[0]."'";
} else {
$expect = "";
}
throw new TokenizeException("Unexpected token '".$this->current()."'$expect");
}
/**
* Fetch next specified token or throw an exception
* @return mixed
*/
public function getNext(/*int|string $token1, int|string $token2, ... */) {
$this->_next(func_get_args());
return $this->current();
}
/**
* Concatenate tokens from the current one to one of the specified and returns the string.
* @param string|int $token
* @param ...
* @return string
*/
public function getStringUntil($token/*, $token2 */) {
$str = '';
while($this->valid() && !$this->_valid(func_get_args(), $this->curr[0])) {
$str .= $this->curr[1].$this->curr[2];
$this->next();
}
return $str;
}
/**
* Return substring. This method doesn't move pointer.
* @param int $offset
* @param int $limit
* @return string
*/
public function getSubstr($offset, $limit = 0) {
$str = '';
if(!$limit) {
$limit = $this->_max;
} else {
$limit += $offset;
}
for($i = $offset; $i <= $limit; $i++){
$str .= $this->tokens[$i][1].$this->tokens[$i][2];
}
return $str;
}
/**
* Return token and move pointer
* @return mixed
* @throws UnexpectedException
*/
public function getAndNext() {
if($this->curr) {
$cur = $this->curr[1];
$this->next();
} else {
throw new UnexpectedException($this, func_get_args());
}
return $cur;
}
/**
* Check if the next token is one of the specified.
* @param $token1
* @return bool
*/
public function isNext($token1/*, ...*/) {
return $this->next && $this->_valid(func_get_args(), $this->next[0]);
}
/**
* Check if the current token is one of the specified.
* @param $token1
* @return bool
*/
public function is($token1/*, ...*/) {
return $this->curr && $this->_valid(func_get_args(), $this->curr[0]);
}
/**
* Check if the previous token is one of the specified.
* @param $token1
* @return bool
*/
public function isPrev($token1/*, ...*/) {
return $this->prev && $this->_valid(func_get_args(), $this->prev[0]);
}
/**
* Get specified token
*
* @param string|int $token1
* @throws UnexpectedException
* @return mixed
*/
public function get($token1 /*, $token2 ...*/) {
if($this->curr && $this->_valid(func_get_args(), $this->curr[0])) {
return $this->curr[1];
} else {
throw new UnexpectedException($this, func_get_args());
}
}
/**
* Step back
* @return Tokenizer
*/
public function back() {
if($this->p === 0) {
return $this;
}
$this->p--;
unset($this->prev, $this->curr, $this->next);
return $this;
}
/**
* Lazy load properties
*
* @param string $key
* @return mixed
*/
public function __get($key) {
switch($key) {
case 'curr':
return $this->curr = ($this->p <= $this->_max) ? $this->tokens[$this->p] : null;
case 'next':
return $this->next = ($this->p + 1 <= $this->_max) ? $this->tokens[$this->p + 1] : null;
case 'prev':
return $this->prev = $this->p ? $this->tokens[$this->p - 1] : null;
default:
return $this->$key = null;
}
}
/**
* Return the key of the current element
* @link http://php.net/manual/en/iterator.key.php
* @return mixed scalar on success, or null on failure.
*/
public function key() {
return $this->curr ? $this->curr[0] : null;
}
/**
* Checks if current position is valid
* @link http://php.net/manual/en/iterator.valid.php
* @return boolean The return value will be casted to boolean and then evaluated.
* Returns true on success or false on failure.
*/
public function valid() {
return (bool)$this->curr;
}
/**
* Rewind the Iterator to the first element. Disabled.
* @link http://php.net/manual/en/iterator.rewind.php
* @return void Any returned value is ignored.
*/
public function rewind() {}
/**
* Get token name
* @static
* @param int|string $token
* @return string
*/
public static function getName($token) {
if(is_string($token)) {
return $token;
} elseif(is_integer($token)) {
return token_name($token);
} elseif(is_array($token)) {
return token_name($token[0]);
} else {
return null;
}
}
/**
* Return whitespace of current token
* @return null
*/
public function getWhiteSpace() {
if($this->curr) {
return $this->curr[2];
} else {
return null;
}
}
/**
* Skip specific token or throw an exception
*
* @throws UnexpectedException
* @return Tokenizer
*/
public function skip(/*$token1, $token2, ...*/) {
if(func_num_args()) {
if($this->_valid(func_get_args(), $this->curr[0])) {
$this->next();
return $this;
} else {
throw new UnexpectedException($this, func_get_args());
}
} else {
$this->next();
return $this;
}
}
/**
* Skip specific token or do nothing
*
* @param int|string $token1
* @return Tokenizer
*/
public function skipIf($token1/*, $token2, ...*/) {
if($this->_valid(func_get_args(), $this->curr[0])) {
$this->next();
}
return $this;
}
/**
* Check current token's type
*
* @param int|string $token1
* @return Tokenizer
* @throws UnexpectedException
*/
public function need($token1/*, $token2, ...*/) {
if($this->_valid(func_get_args(), $this->curr[0])) {
return $this;
} else {
throw new UnexpectedException($this, func_get_args());
}
}
/**
* Count elements of an object
* @link http://php.net/manual/en/countable.count.php
* @return int The custom count as an integer.
* The return value is cast to an integer.
*/
public function count() {
return $this->_max;
}
/**
* Get tokens near current token
* @param int $before count tokens before current token
* @param int $after count tokens after current token
* @return array
*/
public function getSnippet($before = 0, $after = 0) {
$from = 0;
$to = $this->p;
if($before > 0) {
if($before > $this->p) {
$from = $this->p;
} else {
$from = $before;
}
} elseif($before < 0) {
$from = $this->p + $before;
if($from < 0) {
$from = 0;
}
}
if($after > 0) {
$to = $this->p + $after;
if($to > $this->_max) {
$to = $this->_max;
}
} elseif($after < 0) {
$to = $this->_max + $after;
if($to < $this->p) {
$to = $this->p;
}
} elseif($this->p > $this->_max) {
$to = $this->_max;
}
$code = array();
for($i=$from; $i<=$to; $i++) {
$code[] = $this->tokens[ $i ];
}
return $code;
}
/**
* Return snippet as string
* @param int $before
* @param int $after
* @return string
*/
public function getSnippetAsString($before = 0, $after = 0) {
$str = "";
foreach($this->getSnippet($before, $after) as $token) {
$str .= $token[1].$token[2];
}
return trim(str_replace("\n", '↵', $str));
}
/**
* Check if current is special value: true, TRUE, false, FALSE, null, NULL
* @return bool
*/
public function isSpecialVal() {
return isset(self::$spec[$this->current()]);
}
/**
* Check if the token is last
* @return bool
*/
public function isLast() {
return $this->p === $this->_max;
}
/**
* Move pointer to the end
*/
public function end() {
$this->p = $this->_max;
}
/**
* Return line number of the current token
* @return mixed
*/
public function getLine() {
return $this->curr ? $this->curr[3] : $this->_last_no;
}
/**
* Dump (append) token into variable
*
* @param mixed $var
* @param bool $whitespace include whitespace
*/
/*public function appendTo(&$var, $whitespace = false) {
$var .= $this->curr[1];
if($whitespace && $this->curr[2]) {
$var .= $this->curr[2];
}
}*/
/**
* Parse code and append tokens. This method move pointer to offset.
* @param string $code
* @param int $offset
* @return Tokenizer
*/
public function append($code, $offset = -1) {
if($offset != -1) {
$code = $this->getSubstr($offset).$code;
if($this->p > $offset) {
$this->p = $offset;
}
$this->tokens = array_slice($this->tokens, 0, $offset);
}
$tokens = self::decode($code);
unset($tokens[-1], $this->prev, $this->curr, $this->next);
$this->tokens = array_merge($this->tokens, $tokens);
$this->_max = count($this->tokens) - 1;
$this->_last_no = $this->tokens[$this->_max][3];
return $this;
}
}
/**
* Tokenize error
*/
class TokenizeException extends \RuntimeException {}
/**
* Unexpected token
*/
class UnexpectedException extends TokenizeException {
public function __construct(Tokenizer $tokens, $expect = null) {
if($expect && count($expect) == 1 && is_string($expect[0])) {
$expect = ", expect '".$expect[0]."'";
} else {
$expect = "";
}
if(!$tokens->curr) {
$this->message = "Unexpected end of expression$expect";
} elseif($tokens->curr[1] === "\n") {
$this->message = "Unexpected new line$expect";
} elseif($tokens->curr[0] === T_WHITESPACE) {
$this->message = "Unexpected whitespace$expect";
} else {
$this->message = "Unexpected token '".$tokens->current()."'$expect";
}
}
};