This commit is contained in:
bzick
2016-08-22 17:08:47 +03:00
parent 58f8c0facb
commit 3171d80d8b
4 changed files with 83 additions and 57 deletions

View File

@@ -5,9 +5,11 @@ require_once __DIR__.'/../tests/tools.php';
\Fenom::registerAutoload(); \Fenom::registerAutoload();
$fenom = Fenom::factory(__DIR__.'/templates', __DIR__.'/../tests/resources/compile'); $fenom = Fenom::factory(__DIR__.'/templates', __DIR__.'/compiled');
$fenom->setOptions(Fenom::AUTO_RELOAD); $fenom->setOptions(Fenom::AUTO_RELOAD | Fenom::FORCE_VERIFY);
var_dump($fenom->compileCode('{do $object->method()}')->getTemplateCode()); //var_dump($fenom->compile("nested.tpl", [])->getTemplateCode());
//exit;
var_dump($fenom->fetch('bug247/home.tpl', []));
//var_dump($fenom->compile("bug158/main.tpl", [])->getTemplateCode()); //var_dump($fenom->compile("bug158/main.tpl", [])->getTemplateCode());
//var_dump($fenom->display("bug158/main.tpl", [])); //var_dump($fenom->display("bug158/main.tpl", []));
// $fenom->getTemplate("problem.tpl"); // $fenom->getTemplate("problem.tpl");

View File

@@ -10,11 +10,11 @@
namespace Fenom; namespace Fenom;
use Fenom; use Fenom;
use Fenom\Error\UnexpectedTokenException;
use Fenom\Error\CompileException; use Fenom\Error\CompileException;
use Fenom\Error\InvalidUsageException; use Fenom\Error\InvalidUsageException;
use Fenom\Error\SecurityException; use Fenom\Error\SecurityException;
use Fenom\Error\TokenizeException; use Fenom\Error\TokenizeException;
use Fenom\Error\UnexpectedTokenException;
/** /**
* Template compiler * Template compiler
@@ -27,6 +27,12 @@ class Template extends Render
const VAR_NAME = '$var'; const VAR_NAME = '$var';
const TPL_NAME = '$tpl'; const TPL_NAME = '$tpl';
const COMPILE_STAGE_LOADED = 1;
const COMPILE_STAGE_PRE_FILTERED = 2;
const COMPILE_STAGE_PARSED = 3;
const COMPILE_STAGE_PROCESSED = 4;
const COMPILE_STAGE_POST_FILTERED = 5;
/** /**
* Disable array parser. * Disable array parser.
*/ */
@@ -80,6 +86,7 @@ class Template extends Render
* @var string * @var string
*/ */
private $_body; private $_body;
private $_compile_stage = 0;
/** /**
* Call stack * Call stack
@@ -166,6 +173,7 @@ class Template extends Render
} }
$this->_provider = $this->_fenom->getProvider($provider); $this->_provider = $this->_fenom->getProvider($provider);
$this->_src = $this->_provider->getSource($this->_base_name, $this->_time); $this->_src = $this->_provider->getSource($this->_base_name, $this->_time);
$this->_compile_stage = self::COMPILE_STAGE_LOADED;
if ($compile) { if ($compile) {
$this->compile(); $this->compile();
} }
@@ -196,10 +204,12 @@ class Template extends Render
*/ */
public function compile() public function compile()
{ {
$end = $pos = 0; $end = $pos = 0;
foreach ($this->_fenom->getPreFilters() as $filter) { foreach ($this->_fenom->getPreFilters() as $filter) {
$this->_src = call_user_func($filter, $this, $this->_src); $this->_src = call_user_func($filter, $this, $this->_src);
} }
$this->_compile_stage = self::COMPILE_STAGE_PRE_FILTERED;
while (($start = strpos($this->_src, '{', $pos)) !== false) { // search open-symbol of tags while (($start = strpos($this->_src, '{', $pos)) !== false) { // search open-symbol of tags
switch (substr($this->_src, $start + 1, 1)) { // check next character switch (substr($this->_src, $start + 1, 1)) { // check next character
case "\n": case "\n":
@@ -265,6 +275,7 @@ class Template extends Render
} }
$pos = $end + 1; // move search-pointer to end of the tag $pos = $end + 1; // move search-pointer to end of the tag
} }
$this->_compile_stage = self::COMPILE_STAGE_PARSED;
gc_collect_cycles(); gc_collect_cycles();
$this->_appendText(substr($this->_src, $end ? $end + 1 : 0)); // append tail of the template $this->_appendText(substr($this->_src, $end ? $end + 1 : 0)); // append tail of the template
@@ -283,10 +294,16 @@ class Template extends Render
call_user_func_array($cb, array($this, &$this->_body)); call_user_func_array($cb, array($this, &$this->_body));
} }
} }
$this->_compile_stage = self::COMPILE_STAGE_PROCESSED;
$this->addDepend($this); // for 'verify' performance $this->addDepend($this); // for 'verify' performance
foreach ($this->_fenom->getPostFilters() as $filter) { foreach ($this->_fenom->getPostFilters() as $filter) {
$this->_body = call_user_func($filter, $this, $this->_body); $this->_body = call_user_func($filter, $this, $this->_body);
} }
$this->_compile_stage = self::COMPILE_STAGE_POST_FILTERED;
}
public function isStageDone($stage_no) {
return $this->_compile_stage >= $stage_no;
} }
/** /**
@@ -350,7 +367,7 @@ class Template extends Render
} else { } else {
$text = str_replace("<?", '<?php echo "<?"; ?>' . ($strip ? '' : PHP_EOL), $text); $text = str_replace("<?", '<?php echo "<?"; ?>' . ($strip ? '' : PHP_EOL), $text);
} }
if($strip) { if ($strip) {
$text = preg_replace('/\s+/uS', ' ', str_replace(array("\r", "\n"), " ", $text)); $text = preg_replace('/\s+/uS', ' ', str_replace(array("\r", "\n"), " ", $text));
$text = str_replace("> <", "><", $text); $text = str_replace("> <", "><", $text);
} }
@@ -376,7 +393,8 @@ class Template extends Render
/** /**
* @param $tag_name * @param $tag_name
*/ */
public function ignore($tag_name) { public function ignore($tag_name)
{
$this->_ignore = $tag_name; $this->_ignore = $tag_name;
} }
@@ -490,7 +508,7 @@ class Template extends Render
$escape = $this->_options & Fenom::AUTO_ESCAPE; $escape = $this->_options & Fenom::AUTO_ESCAPE;
} }
if ($escape) { if ($escape) {
return "echo htmlspecialchars($data, ENT_COMPAT, ".var_export(Fenom::$charset, true).");"; return "echo htmlspecialchars($data, ENT_COMPAT, " . var_export(Fenom::$charset, true) . ");";
} else { } else {
return "echo $data;"; return "echo $data;";
} }
@@ -519,13 +537,13 @@ class Template extends Render
*/ */
public function extend($tpl) public function extend($tpl)
{ {
if (!$this->_body) { if (!$this->isStageDone(self::COMPILE_STAGE_PARSED)) {
$this->compile(); $this->compile();
} }
$parent = $this->_fenom->getRawTemplate()->load($tpl, false); $parent = $this->_fenom->getRawTemplate()->load($tpl, false);
$parent->blocks = & $this->blocks; $parent->blocks = &$this->blocks;
$parent->macros = & $this->macros; $parent->macros = &$this->macros;
$parent->_before = & $this->_before; $parent->_before = &$this->_before;
$parent->extended = $this->getName(); $parent->extended = $this->getName();
if (!$this->ext_stack) { if (!$this->ext_stack) {
$this->ext_stack[] = $this->getName(); $this->ext_stack[] = $this->getName();
@@ -638,10 +656,12 @@ class Template extends Render
} }
} }
if ($tags = $this->_fenom->getTagOwners($action)) { // unknown template tag if ($tags = $this->_fenom->getTagOwners($action)) { // unknown template tag
throw new TokenizeException("Unexpected tag '$action' (this tag can be used with '" . implode( throw new TokenizeException(
"Unexpected tag '$action' (this tag can be used with '" . implode(
"', '", "', '",
$tags $tags
) . "')"); ) . "')"
);
} else { } else {
throw new TokenizeException("Unexpected tag '$action'"); throw new TokenizeException("Unexpected tag '$action'");
} }
@@ -675,9 +695,9 @@ class Template extends Render
$term = $this->parseTerm($tokens, $var, -1); // term of the expression $term = $this->parseTerm($tokens, $var, -1); // term of the expression
if ($term !== false) { if ($term !== false) {
if ($tokens->is('?', '!')) { if ($tokens->is('?', '!')) {
if($cond) { if ($cond) {
$term = array_pop($exp) . ' ' . $term; $term = array_pop($exp) . ' ' . $term;
$term = '('. array_pop($exp) . ' ' . $term . ')'; $term = '(' . array_pop($exp) . ' ' . $term . ')';
$var = false; $var = false;
} }
$term = $this->parseTernary($tokens, $term, $var); $term = $this->parseTernary($tokens, $term, $var);
@@ -707,7 +727,7 @@ class Template extends Render
break; break;
} }
$op = $tokens->getAndNext(); $op = $tokens->getAndNext();
if($op == '[') { if ($op == '[') {
$tokens->need(']')->next()->need('=')->next(); $tokens->need(']')->next()->need('=')->next();
$op = '[]='; $op = '[]=';
} }
@@ -742,7 +762,7 @@ class Template extends Render
$tokens->next(); $tokens->next();
$concat[] = "' '"; $concat[] = "' '";
} }
if (!$term2 = "strval(".$this->parseTerm($tokens).")") { if (!$term2 = "strval(" . $this->parseTerm($tokens) . ")") {
throw new UnexpectedTokenException($tokens); throw new UnexpectedTokenException($tokens);
} }
$concat[] = $term2; $concat[] = $term2;
@@ -762,7 +782,7 @@ class Template extends Render
throw new UnexpectedTokenException($tokens); throw new UnexpectedTokenException($tokens);
} }
if(count($exp) == 1 && $var) { if (count($exp) == 1 && $var) {
$is_var = true; $is_var = true;
} }
return implode(' ', $exp); return implode(' ', $exp);
@@ -785,7 +805,7 @@ class Template extends Render
} else { } else {
$unary = ""; $unary = "";
} }
switch($tokens->key()) { switch ($tokens->key()) {
case T_LNUMBER: case T_LNUMBER:
case T_DNUMBER: case T_DNUMBER:
$code = $unary . $this->parseScalar($tokens); $code = $unary . $this->parseScalar($tokens);
@@ -801,13 +821,13 @@ class Template extends Render
/** @noinspection PhpMissingBreakStatementInspection */ /** @noinspection PhpMissingBreakStatementInspection */
case '$': case '$':
$code = $this->parseAccessor($tokens, $is_var); $code = $this->parseAccessor($tokens, $is_var);
if(!$is_var) { if (!$is_var) {
$code = $unary . $code; $code = $unary . $code;
break; break;
} }
/* no break */ /* no break */
case T_VARIABLE: case T_VARIABLE:
if(!isset($code)) { if (!isset($code)) {
$code = $this->parseVariable($tokens); $code = $this->parseVariable($tokens);
} }
if ($tokens->is("(") && $tokens->hasBackList(T_STRING, T_OBJECT_OPERATOR)) { if ($tokens->is("(") && $tokens->hasBackList(T_STRING, T_OBJECT_OPERATOR)) {
@@ -816,25 +836,25 @@ class Template extends Render
} }
$code = $unary . $this->parseChain($tokens, $code); $code = $unary . $this->parseChain($tokens, $code);
} elseif ($tokens->is(Tokenizer::MACRO_INCDEC)) { } elseif ($tokens->is(Tokenizer::MACRO_INCDEC)) {
if($this->_options & Fenom::FORCE_VERIFY) { if ($this->_options & Fenom::FORCE_VERIFY) {
$code = $unary . '(isset(' . $code . ') ? ' . $code . $tokens->getAndNext() . ' : null)'; $code = $unary . '(isset(' . $code . ') ? ' . $code . $tokens->getAndNext() . ' : null)';
} else { } else {
$code = $unary . $code . $tokens->getAndNext(); $code = $unary . $code . $tokens->getAndNext();
} }
} else { } else {
if($this->_options & Fenom::FORCE_VERIFY) { if ($this->_options & Fenom::FORCE_VERIFY) {
$code = $unary . '(isset(' . $code . ') ? ' . $code . ' : null)'; $code = $unary . '(isset(' . $code . ') ? ' . $code . ' : null)';
} else { } else {
$is_var = true; $is_var = true;
$code = $unary . $code; $code = $unary . $code;
} }
} }
break; break;
case T_DEC: case T_DEC:
case T_INC: case T_INC:
if($this->_options & Fenom::FORCE_VERIFY) { if ($this->_options & Fenom::FORCE_VERIFY) {
$var = $this->parseVariable($tokens); $var = $this->parseVariable($tokens);
$code = $unary . '(isset(' . $var . ') ? ' . $tokens->getAndNext() . $this->parseVariable($tokens).' : null)'; $code = $unary . '(isset(' . $var . ') ? ' . $tokens->getAndNext() . $this->parseVariable($tokens) . ' : null)';
} else { } else {
$code = $unary . $tokens->getAndNext() . $this->parseVariable($tokens); $code = $unary . $tokens->getAndNext() . $this->parseVariable($tokens);
} }
@@ -853,7 +873,7 @@ class Template extends Render
throw new \Exception("Function " . $tokens->getAndNext() . " not found"); throw new \Exception("Function " . $tokens->getAndNext() . " not found");
} }
if (!is_string($func)) { // dynamic modifier if (!is_string($func)) { // dynamic modifier
$call = 'call_user_func_array($tpl->getStorage()->getModifier("' . $modifier . '"), array'.$this->parseArgs($tokens->next()).')'; // @todo optimize $call = 'call_user_func_array($tpl->getStorage()->getModifier("' . $modifier . '"), array' . $this->parseArgs($tokens->next()) . ')'; // @todo optimize
} else { } else {
$call = $func . $this->parseArgs($tokens->next()); $call = $func . $this->parseArgs($tokens->next());
} }
@@ -890,13 +910,13 @@ class Template extends Render
} }
} }
if (($allows & self::TERM_MODS) && $tokens->is('|')) { if (($allows & self::TERM_MODS) && $tokens->is('|')) {
$code = $this->parseModifier($tokens, $code); $code = $this->parseModifier($tokens, $code);
$is_var = false; $is_var = false;
} }
if(($allows & self::TERM_RANGE) && $tokens->is('.') && $tokens->isNext('.')) { if (($allows & self::TERM_RANGE) && $tokens->is('.') && $tokens->isNext('.')) {
$tokens->next()->next(); $tokens->next()->next();
$code = '(new \Fenom\RangeIterator('.$code.', '.$this->parseTerm($tokens, $var, self::TERM_MODS).'))'; $code = '(new \Fenom\RangeIterator(' . $code . ', ' . $this->parseTerm($tokens, $var, self::TERM_MODS) . '))';
$is_var = false; $is_var = false;
} }
return $code; return $code;
} }
@@ -907,7 +927,8 @@ class Template extends Render
* @param string $code start point (it is $var) * @param string $code start point (it is $var)
* @return string * @return string
*/ */
public function parseChain(Tokenizer $tokens, $code) { public function parseChain(Tokenizer $tokens, $code)
{
do { do {
if ($tokens->is('(')) { if ($tokens->is('(')) {
$code .= $this->parseArgs($tokens); $code .= $this->parseArgs($tokens);
@@ -930,10 +951,10 @@ class Template extends Render
public function parseVariable(Tokenizer $tokens, $var = null) public function parseVariable(Tokenizer $tokens, $var = null)
{ {
if (!$var) { if (!$var) {
if($tokens->isNext('@')) { if ($tokens->isNext('@')) {
// $v = $tokens->get(T_VARIABLE); // $v = $tokens->get(T_VARIABLE);
$prop = $tokens->next()->next()->get(T_STRING); $prop = $tokens->next()->next()->get(T_STRING);
if($tag = $this->getParentScope("foreach")) { if ($tag = $this->getParentScope("foreach")) {
$tokens->next(); $tokens->next();
return Compiler::foreachProp($tag, $prop); return Compiler::foreachProp($tag, $prop);
} else { } else {
@@ -955,7 +976,7 @@ class Template extends Render
$key = "[" . $tokens->getAndNext() . "]"; $key = "[" . $tokens->getAndNext() . "]";
} elseif ($tokens->is('"')) { } elseif ($tokens->is('"')) {
$key = "[" . $this->parseQuote($tokens) . "]"; $key = "[" . $this->parseQuote($tokens) . "]";
} elseif($tokens->is('.')) { } elseif ($tokens->is('.')) {
$tokens->back(); $tokens->back();
break; break;
} else { } else {
@@ -963,7 +984,7 @@ class Template extends Render
} }
$var .= $key; $var .= $key;
} elseif ($t === "[") { } elseif ($t === "[") {
if($tokens->isNext(']')) { if ($tokens->isNext(']')) {
break; break;
} }
$tokens->next(); $tokens->next();
@@ -1001,16 +1022,23 @@ class Template extends Render
public function parseAccessor(Tokenizer $tokens, &$is_var = false) public function parseAccessor(Tokenizer $tokens, &$is_var = false)
{ {
$accessor = $tokens->need('$')->next()->need('.')->next()->current(); $accessor = $tokens->need('$')->next()->need('.')->next()->current();
$parser = $this->getStorage()->getAccessor($accessor); $parser = $this->getStorage()->getAccessor($accessor);
$is_var = false; $is_var = false;
if($parser) { if ($parser) {
if(is_array($parser)) { if (is_array($parser)) {
if(isset($parser['callback'])) { if (isset($parser['callback'])) {
$tokens->next(); $tokens->next();
return 'call_user_func($tpl->getStorage()->getAccessor('.var_export($accessor, true). return 'call_user_func($tpl->getStorage()->getAccessor(' . var_export($accessor, true) .
', "callback"), '.var_export($accessor, true).', $tpl, $var)'; ', "callback"), ' . var_export($accessor, true) . ', $tpl, $var)';
} else { } else {
return call_user_func_array($parser['parser'], array($parser['accessor'], $tokens->next(), $this, &$is_var)); return call_user_func_array(
$parser['parser'], array(
$parser['accessor'],
$tokens->next(),
$this,
&$is_var
)
);
} }
} else { } else {
return call_user_func_array($parser, array($tokens->next(), $this, &$is_var)); return call_user_func_array($parser, array($tokens->next(), $this, &$is_var));
@@ -1365,15 +1393,15 @@ class Template extends Render
$count++; $count++;
} else { } else {
$expr = $this->parseExpr($tokens); $expr = $this->parseExpr($tokens);
if($tokens->is(T_DOUBLE_ARROW)) { if ($tokens->is(T_DOUBLE_ARROW)) {
$tokens->next(); $tokens->next();
$arr[] = $expr.' => '.$this->parseExpr($tokens); $arr[] = $expr . ' => ' . $this->parseExpr($tokens);
} else { } else {
$arr[] = $expr; $arr[] = $expr;
} }
$count++; $count++;
} }
if($tokens->is(',')) { if ($tokens->is(',')) {
$tokens->next(); $tokens->next();
} }
} }

View File

@@ -9,8 +9,4 @@ require_once FENOM_RESOURCES . "/actions.php";
require_once __DIR__ . "/TestCase.php"; require_once __DIR__ . "/TestCase.php";
require_once __DIR__ . "/tools.php"; require_once __DIR__ . "/tools.php";
ini_set('date.timezone', 'Europe/Moscow'); ini_set('date.timezone', 'Europe/Moscow');
if(PHP_VERSION_ID > 50400) {
function php_gte_54() {}
}

View File

@@ -321,7 +321,7 @@ class FenomTest extends \Fenom\TestCase
/** /**
* @requires function php_gte_54 * @requires PHP 5.4
* @group pipe * @group pipe
*/ */
public function testPipe() public function testPipe()