To PSR-x format

This commit is contained in:
bzick
2013-07-29 14:58:14 +04:00
parent 4edd0e1708
commit 3674de41cb
27 changed files with 2071 additions and 1674 deletions

View File

@@ -15,7 +15,8 @@ use Fenom\Template,
* *
* @author Ivan Shalganov <a.cobest@gmail.com> * @author Ivan Shalganov <a.cobest@gmail.com>
*/ */
class Fenom { class Fenom
{
const VERSION = '1.2'; const VERSION = '1.2';
/* Actions */ /* Actions */
@@ -250,7 +251,8 @@ class Fenom {
* @throws InvalidArgumentException * @throws InvalidArgumentException
* @return Fenom * @return Fenom
*/ */
public static function factory($source, $compile_dir = '/tmp', $options = 0) { public static function factory($source, $compile_dir = '/tmp', $options = 0)
{
if (is_string($source)) { if (is_string($source)) {
$provider = new Fenom\Provider($source); $provider = new Fenom\Provider($source);
} elseif ($source instanceof ProviderInterface) { } elseif ($source instanceof ProviderInterface) {
@@ -270,7 +272,8 @@ class Fenom {
/** /**
* @param Fenom\ProviderInterface $provider * @param Fenom\ProviderInterface $provider
*/ */
public function __construct(Fenom\ProviderInterface $provider) { public function __construct(Fenom\ProviderInterface $provider)
{
$this->_provider = $provider; $this->_provider = $provider;
} }
@@ -280,7 +283,8 @@ class Fenom {
* @param string $dir directory to store compiled templates in * @param string $dir directory to store compiled templates in
* @return Fenom * @return Fenom
*/ */
public function setCompileDir($dir) { public function setCompileDir($dir)
{
$this->_compile_dir = $dir; $this->_compile_dir = $dir;
return $this; return $this;
} }
@@ -289,7 +293,8 @@ class Fenom {
* *
* @param callable $cb * @param callable $cb
*/ */
public function addPreCompileFilter($cb) { public function addPreCompileFilter($cb)
{
$this->_on_pre_cmp[] = $cb; $this->_on_pre_cmp[] = $cb;
} }
@@ -297,14 +302,16 @@ class Fenom {
* *
* @param callable $cb * @param callable $cb
*/ */
public function addPostCompileFilter($cb) { public function addPostCompileFilter($cb)
{
$this->_on_post_cmp[] = $cb; $this->_on_post_cmp[] = $cb;
} }
/** /**
* @param callable $cb * @param callable $cb
*/ */
public function addCompileFilter($cb) { public function addCompileFilter($cb)
{
$this->_on_cmp[] = $cb; $this->_on_cmp[] = $cb;
} }
@@ -315,7 +322,8 @@ class Fenom {
* @param string $callback the modifier callback * @param string $callback the modifier callback
* @return Fenom * @return Fenom
*/ */
public function addModifier($modifier, $callback) { public function addModifier($modifier, $callback)
{
$this->_modifiers[$modifier] = $callback; $this->_modifiers[$modifier] = $callback;
return $this; return $this;
} }
@@ -327,7 +335,8 @@ class Fenom {
* @param callable $parser * @param callable $parser
* @return Fenom * @return Fenom
*/ */
public function addCompiler($compiler, $parser) { public function addCompiler($compiler, $parser)
{
$this->_actions[$compiler] = array( $this->_actions[$compiler] = array(
'type' => self::INLINE_COMPILER, 'type' => self::INLINE_COMPILER,
'parser' => $parser 'parser' => $parser
@@ -340,7 +349,8 @@ class Fenom {
* @param string|object $storage * @param string|object $storage
* @return $this * @return $this
*/ */
public function addCompilerSmart($compiler, $storage) { public function addCompilerSmart($compiler, $storage)
{
if (method_exists($storage, "tag" . $compiler)) { if (method_exists($storage, "tag" . $compiler)) {
$this->_actions[$compiler] = array( $this->_actions[$compiler] = array(
'type' => self::INLINE_COMPILER, 'type' => self::INLINE_COMPILER,
@@ -359,7 +369,8 @@ class Fenom {
* @param array $tags * @param array $tags
* @return Fenom * @return Fenom
*/ */
public function addBlockCompiler($compiler, $open_parser, $close_parser = self::DEFAULT_CLOSE_COMPILER, array $tags = array()) { public function addBlockCompiler($compiler, $open_parser, $close_parser = self::DEFAULT_CLOSE_COMPILER, array $tags = array())
{
$this->_actions[$compiler] = array( $this->_actions[$compiler] = array(
'type' => self::BLOCK_COMPILER, 'type' => self::BLOCK_COMPILER,
'open' => $open_parser, 'open' => $open_parser,
@@ -377,7 +388,8 @@ class Fenom {
* @throws LogicException * @throws LogicException
* @return Fenom * @return Fenom
*/ */
public function addBlockCompilerSmart($compiler, $storage, array $tags, array $floats = array()) { public function addBlockCompilerSmart($compiler, $storage, array $tags, array $floats = array())
{
$c = array( $c = array(
'type' => self::BLOCK_COMPILER, 'type' => self::BLOCK_COMPILER,
"tags" => array(), "tags" => array(),
@@ -413,7 +425,8 @@ class Fenom {
* @param callable|string $parser * @param callable|string $parser
* @return Fenom * @return Fenom
*/ */
public function addFunction($function, $callback, $parser = self::DEFAULT_FUNC_PARSER) { public function addFunction($function, $callback, $parser = self::DEFAULT_FUNC_PARSER)
{
$this->_actions[$function] = array( $this->_actions[$function] = array(
'type' => self::INLINE_FUNCTION, 'type' => self::INLINE_FUNCTION,
'parser' => $parser, 'parser' => $parser,
@@ -427,7 +440,8 @@ class Fenom {
* @param callable $callback * @param callable $callback
* @return Fenom * @return Fenom
*/ */
public function addFunctionSmart($function, $callback) { public function addFunctionSmart($function, $callback)
{
$this->_actions[$function] = array( $this->_actions[$function] = array(
'type' => self::INLINE_FUNCTION, 'type' => self::INLINE_FUNCTION,
'parser' => self::SMART_FUNC_PARSER, 'parser' => self::SMART_FUNC_PARSER,
@@ -443,7 +457,8 @@ class Fenom {
* @param callable|string $parser_close * @param callable|string $parser_close
* @return Fenom * @return Fenom
*/ */
public function addBlockFunction($function, $callback, $parser_open = self::DEFAULT_FUNC_OPEN, $parser_close = self::DEFAULT_FUNC_CLOSE) { public function addBlockFunction($function, $callback, $parser_open = self::DEFAULT_FUNC_OPEN, $parser_close = self::DEFAULT_FUNC_CLOSE)
{
$this->_actions[$function] = array( $this->_actions[$function] = array(
'type' => self::BLOCK_FUNCTION, 'type' => self::BLOCK_FUNCTION,
'open' => $parser_open, 'open' => $parser_open,
@@ -457,7 +472,8 @@ class Fenom {
* @param array $funcs * @param array $funcs
* @return Fenom * @return Fenom
*/ */
public function addAllowedFunctions(array $funcs) { public function addAllowedFunctions(array $funcs)
{
$this->_allowed_funcs = $this->_allowed_funcs + array_flip($funcs); $this->_allowed_funcs = $this->_allowed_funcs + array_flip($funcs);
return $this; return $this;
} }
@@ -469,7 +485,8 @@ class Fenom {
* @param Fenom\Template $template * @param Fenom\Template $template
* @return mixed * @return mixed
*/ */
public function getModifier($modifier, Template $template = null) { public function getModifier($modifier, Template $template = null)
{
if (isset($this->_modifiers[$modifier])) { if (isset($this->_modifiers[$modifier])) {
return $this->_modifiers[$modifier]; return $this->_modifiers[$modifier];
} elseif ($this->isAllowedFunction($modifier)) { } elseif ($this->isAllowedFunction($modifier)) {
@@ -484,7 +501,8 @@ class Fenom {
* @param Fenom\Template $template * @param Fenom\Template $template
* @return bool * @return bool
*/ */
protected function _loadModifier($modifier, $template) { protected function _loadModifier($modifier, $template)
{
return false; return false;
} }
@@ -494,7 +512,8 @@ class Fenom {
* @return bool|string * @return bool|string
* @deprecated * @deprecated
*/ */
public function getFunction($function, Template $template = null) { public function getFunction($function, Template $template = null)
{
return $this->getTag($function, $template); return $this->getTag($function, $template);
} }
@@ -505,7 +524,8 @@ class Fenom {
* @param Fenom\Template $template * @param Fenom\Template $template
* @return string|bool * @return string|bool
*/ */
public function getTag($tag, Template $template = null) { public function getTag($tag, Template $template = null)
{
if (isset($this->_actions[$tag])) { if (isset($this->_actions[$tag])) {
return $this->_actions[$tag]; return $this->_actions[$tag];
} else { } else {
@@ -518,7 +538,8 @@ class Fenom {
* @param Fenom\Template $template * @param Fenom\Template $template
* @return bool * @return bool
*/ */
protected function _loadTag($tag, $template) { protected function _loadTag($tag, $template)
{
return false; return false;
} }
@@ -526,7 +547,8 @@ class Fenom {
* @param string $function * @param string $function
* @return bool * @return bool
*/ */
public function isAllowedFunction($function) { public function isAllowedFunction($function)
{
if ($this->_options & self::DENY_NATIVE_FUNCS) { if ($this->_options & self::DENY_NATIVE_FUNCS) {
return isset($this->_allowed_funcs[$function]); return isset($this->_allowed_funcs[$function]);
} else { } else {
@@ -538,7 +560,8 @@ class Fenom {
* @param string $tag * @param string $tag
* @return array * @return array
*/ */
public function getTagOwners($tag) { public function getTagOwners($tag)
{
$tags = array(); $tags = array();
foreach ($this->_actions as $owner => $params) { foreach ($this->_actions as $owner => $params) {
if (isset($params["tags"][$tag])) { if (isset($params["tags"][$tag])) {
@@ -554,7 +577,8 @@ class Fenom {
* @param string $scm scheme name * @param string $scm scheme name
* @param Fenom\ProviderInterface $provider provider object * @param Fenom\ProviderInterface $provider provider object
*/ */
public function addProvider($scm, \Fenom\ProviderInterface $provider) { public function addProvider($scm, \Fenom\ProviderInterface $provider)
{
$this->_providers[$scm] = $provider; $this->_providers[$scm] = $provider;
} }
@@ -562,7 +586,8 @@ class Fenom {
* Set options * Set options
* @param int|array $options * @param int|array $options
*/ */
public function setOptions($options) { public function setOptions($options)
{
if (is_array($options)) { if (is_array($options)) {
$options = self::_makeMask($options, self::$_options_list, $this->_options); $options = self::_makeMask($options, self::$_options_list, $this->_options);
} }
@@ -574,7 +599,8 @@ class Fenom {
* Get options as bits * Get options as bits
* @return int * @return int
*/ */
public function getOptions() { public function getOptions()
{
return $this->_options; return $this->_options;
} }
@@ -583,7 +609,8 @@ class Fenom {
* @return Fenom\ProviderInterface * @return Fenom\ProviderInterface
* @throws InvalidArgumentException * @throws InvalidArgumentException
*/ */
public function getProvider($scm = false) { public function getProvider($scm = false)
{
if ($scm) { if ($scm) {
if (isset($this->_providers[$scm])) { if (isset($this->_providers[$scm])) {
return $this->_providers[$scm]; return $this->_providers[$scm];
@@ -600,7 +627,8 @@ class Fenom {
* *
* @return Fenom\Template * @return Fenom\Template
*/ */
public function getRawTemplate() { public function getRawTemplate()
{
return new Template($this, $this->_options); return new Template($this, $this->_options);
} }
@@ -611,7 +639,8 @@ class Fenom {
* @param array $vars array of data for template * @param array $vars array of data for template
* @return Fenom\Render * @return Fenom\Render
*/ */
public function display($template, array $vars = array()) { public function display($template, array $vars = array())
{
return $this->getTemplate($template)->display($vars); return $this->getTemplate($template)->display($vars);
} }
@@ -621,7 +650,8 @@ class Fenom {
* @param array $vars array of data for template * @param array $vars array of data for template
* @return mixed * @return mixed
*/ */
public function fetch($template, array $vars = array()) { public function fetch($template, array $vars = array())
{
return $this->getTemplate($template)->fetch($vars); return $this->getTemplate($template)->fetch($vars);
} }
@@ -634,7 +664,8 @@ class Fenom {
* @param float $chunk * @param float $chunk
* @return array * @return array
*/ */
public function pipe($template, $callback, array $vars = array(), $chunk = 1e6) { public function pipe($template, $callback, array $vars = array(), $chunk = 1e6)
{
ob_start($callback, $chunk, true); ob_start($callback, $chunk, true);
$data = $this->getTemplate($template)->display($vars); $data = $this->getTemplate($template)->display($vars);
ob_end_flush(); ob_end_flush();
@@ -648,7 +679,8 @@ class Fenom {
* @param int $options additional options and flags * @param int $options additional options and flags
* @return Fenom\Template * @return Fenom\Template
*/ */
public function getTemplate($template, $options = 0) { public function getTemplate($template, $options = 0)
{
$options |= $this->_options; $options |= $this->_options;
$key = dechex($options) . "@" . $template; $key = dechex($options) . "@" . $template;
if (isset($this->_storage[$key])) { if (isset($this->_storage[$key])) {
@@ -671,7 +703,8 @@ class Fenom {
* @param string $template * @param string $template
* @return bool * @return bool
*/ */
public function templateExists($template) { public function templateExists($template)
{
if ($provider = strstr($template, ":", true)) { if ($provider = strstr($template, ":", true)) {
if (isset($this->_providers[$provider])) { if (isset($this->_providers[$provider])) {
return $this->_providers[$provider]->templateExists(substr($template, strlen($provider) + 1)); return $this->_providers[$provider]->templateExists(substr($template, strlen($provider) + 1));
@@ -689,7 +722,8 @@ class Fenom {
* @param int $opts * @param int $opts
* @return Fenom\Render * @return Fenom\Render
*/ */
protected function _load($tpl, $opts) { protected function _load($tpl, $opts)
{
$file_name = $this->_getCacheName($tpl, $opts); $file_name = $this->_getCacheName($tpl, $opts);
if (!is_file($this->_compile_dir . "/" . $file_name)) { if (!is_file($this->_compile_dir . "/" . $file_name)) {
return $this->compile($tpl, true, $opts); return $this->compile($tpl, true, $opts);
@@ -706,7 +740,8 @@ class Fenom {
* @param int $options * @param int $options
* @return string * @return string
*/ */
private function _getCacheName($tpl, $options) { private function _getCacheName($tpl, $options)
{
$hash = $tpl . ":" . $options; $hash = $tpl . ":" . $options;
return sprintf("%s.%x.%x.php", str_replace(":", "_", basename($tpl)), crc32($hash), strlen($hash)); return sprintf("%s.%x.%x.php", str_replace(":", "_", basename($tpl)), crc32($hash), strlen($hash));
} }
@@ -720,7 +755,8 @@ class Fenom {
* @throws RuntimeException * @throws RuntimeException
* @return \Fenom\Template * @return \Fenom\Template
*/ */
public function compile($tpl, $store = true, $options = 0) { public function compile($tpl, $store = true, $options = 0)
{
$options = $this->_options | $options; $options = $this->_options | $options;
$template = $this->getRawTemplate()->load($tpl); $template = $this->getRawTemplate()->load($tpl);
if ($store) { if ($store) {
@@ -743,14 +779,16 @@ class Fenom {
/** /**
* Flush internal memory template cache * Flush internal memory template cache
*/ */
public function flush() { public function flush()
{
$this->_storage = array(); $this->_storage = array();
} }
/** /**
* Remove all compiled templates * Remove all compiled templates
*/ */
public function clearAllCompiles() { public function clearAllCompiles()
{
\Fenom\Provider::clean($this->_compile_dir); \Fenom\Provider::clean($this->_compile_dir);
} }
@@ -761,7 +799,8 @@ class Fenom {
* @param string $name * @param string $name
* @return Fenom\Template * @return Fenom\Template
*/ */
public function compileCode($code, $name = 'Runtime compile') { public function compileCode($code, $name = 'Runtime compile')
{
return $this->getRawTemplate()->source($name, $code); return $this->getRawTemplate()->source($name, $code);
} }
@@ -775,7 +814,8 @@ class Fenom {
* @return int result, ( $mask | a ) & ~b * @return int result, ( $mask | a ) & ~b
* @throws \RuntimeException if key from custom assoc doesn't exists into possible values * @throws \RuntimeException if key from custom assoc doesn't exists into possible values
*/ */
private static function _makeMask(array $values, array $options, $mask = 0) { private static function _makeMask(array $values, array $options, $mask = 0)
{
foreach ($values as $key => $value) { foreach ($values as $key => $value) {
if (isset($options[$key])) { if (isset($options[$key])) {
if ($options[$key]) { if ($options[$key]) {

View File

@@ -17,7 +17,8 @@ use Fenom\Scope;
* @package Fenom * @package Fenom
* @author Ivan Shalganov <a.cobest@gmail.com> * @author Ivan Shalganov <a.cobest@gmail.com>
*/ */
class Compiler { class Compiler
{
/** /**
* Tag {include ...} * Tag {include ...}
* *
@@ -27,7 +28,8 @@ class Compiler {
* @throws InvalidUsageException * @throws InvalidUsageException
* @return string * @return string
*/ */
public static function tagInclude(Tokenizer $tokens, Template $tpl) { public static function tagInclude(Tokenizer $tokens, Template $tpl)
{
$cname = $tpl->parsePlainArg($tokens, $name); $cname = $tpl->parsePlainArg($tokens, $name);
$p = $tpl->parseParams($tokens); $p = $tpl->parseParams($tokens);
if ($p) { // if we have additionally variables if ($p) { // if we have additionally variables
@@ -58,7 +60,8 @@ class Compiler {
* @param Scope $scope * @param Scope $scope
* @return string * @return string
*/ */
public static function ifOpen(Tokenizer $tokens, Scope $scope) { public static function ifOpen(Tokenizer $tokens, Scope $scope)
{
$scope["else"] = false; $scope["else"] = false;
return 'if(' . $scope->tpl->parseExp($tokens, true) . ') {'; return 'if(' . $scope->tpl->parseExp($tokens, true) . ') {';
} }
@@ -72,7 +75,8 @@ class Compiler {
* @throws InvalidUsageException * @throws InvalidUsageException
* @return string * @return string
*/ */
public static function tagElseIf(Tokenizer $tokens, Scope $scope) { public static function tagElseIf(Tokenizer $tokens, Scope $scope)
{
if ($scope["else"]) { if ($scope["else"]) {
throw new InvalidUsageException('Incorrect use of the tag {elseif}'); throw new InvalidUsageException('Incorrect use of the tag {elseif}');
} }
@@ -88,7 +92,8 @@ class Compiler {
* @param Scope $scope * @param Scope $scope
* @return string * @return string
*/ */
public static function tagElse(Tokenizer $tokens, Scope $scope) { public static function tagElse(Tokenizer $tokens, Scope $scope)
{
$scope["else"] = true; $scope["else"] = true;
return '} else {'; return '} else {';
} }
@@ -103,7 +108,8 @@ class Compiler {
* @throws InvalidUsageException * @throws InvalidUsageException
* @return string * @return string
*/ */
public static function foreachOpen(Tokenizer $tokens, Scope $scope) { public static function foreachOpen(Tokenizer $tokens, Scope $scope)
{
$p = array("index" => false, "first" => false, "last" => false); $p = array("index" => false, "first" => false, "last" => false);
$key = null; $key = null;
$before = $body = array(); $before = $body = array();
@@ -172,7 +178,8 @@ class Compiler {
* @param Scope $scope * @param Scope $scope
* @return string * @return string
*/ */
public static function foreachElse($tokens, Scope $scope) { public static function foreachElse($tokens, Scope $scope)
{
$scope["no-break"] = $scope["no-continue"] = $scope["else"] = true; $scope["no-break"] = $scope["no-continue"] = $scope["else"] = true;
return " {$scope['after']} } } else {"; return " {$scope['after']} } } else {";
} }
@@ -185,7 +192,8 @@ class Compiler {
* @param Scope $scope * @param Scope $scope
* @return string * @return string
*/ */
public static function foreachClose($tokens, Scope $scope) { public static function foreachClose($tokens, Scope $scope)
{
if ($scope["else"]) { if ($scope["else"]) {
return '}'; return '}';
} else { } else {
@@ -200,7 +208,8 @@ class Compiler {
* @return string * @return string
* @throws InvalidUsageException * @throws InvalidUsageException
*/ */
public static function forOpen(Tokenizer $tokens, Scope $scope) { public static function forOpen(Tokenizer $tokens, Scope $scope)
{
$p = array("index" => false, "first" => false, "last" => false, "step" => 1, "to" => false, "max" => false, "min" => false); $p = array("index" => false, "first" => false, "last" => false, "step" => 1, "to" => false, "max" => false, "min" => false);
$scope["after"] = $before = $body = array(); $scope["after"] = $before = $body = array();
$i = array('', ''); $i = array('', '');
@@ -255,7 +264,8 @@ class Compiler {
* @param Scope $scope * @param Scope $scope
* @return string * @return string
*/ */
public static function forElse(Tokenizer $tokens, Scope $scope) { public static function forElse(Tokenizer $tokens, Scope $scope)
{
$scope["no-break"] = $scope["no-continue"] = true; $scope["no-break"] = $scope["no-continue"] = true;
$scope["else"] = true; $scope["else"] = true;
return " } if({$scope['else_cond']}) {"; return " } if({$scope['else_cond']}) {";
@@ -267,7 +277,8 @@ class Compiler {
* @param Scope $scope * @param Scope $scope
* @return string * @return string
*/ */
public static function forClose($tokens, Scope $scope) { public static function forClose($tokens, Scope $scope)
{
if ($scope["else"]) { if ($scope["else"]) {
return '}'; return '}';
} else { } else {
@@ -281,7 +292,8 @@ class Compiler {
* @param Scope $scope * @param Scope $scope
* @return string * @return string
*/ */
public static function whileOpen(Tokenizer $tokens, Scope $scope) { public static function whileOpen(Tokenizer $tokens, Scope $scope)
{
return 'while(' . $scope->tpl->parseExp($tokens, true) . ') {'; return 'while(' . $scope->tpl->parseExp($tokens, true) . ') {';
} }
@@ -293,7 +305,8 @@ class Compiler {
* @param Scope $scope * @param Scope $scope
* @return string * @return string
*/ */
public static function switchOpen(Tokenizer $tokens, Scope $scope) { public static function switchOpen(Tokenizer $tokens, Scope $scope)
{
$scope["no-break"] = $scope["no-continue"] = true; $scope["no-break"] = $scope["no-continue"] = true;
$scope["switch"] = 'switch(' . $scope->tpl->parseExp($tokens, true) . ') {'; $scope["switch"] = 'switch(' . $scope->tpl->parseExp($tokens, true) . ') {';
// lazy init // lazy init
@@ -308,7 +321,8 @@ class Compiler {
* @param Scope $scope * @param Scope $scope
* @return string * @return string
*/ */
public static function tagCase(Tokenizer $tokens, Scope $scope) { public static function tagCase(Tokenizer $tokens, Scope $scope)
{
$code = 'case ' . $scope->tpl->parseExp($tokens, true) . ': '; $code = 'case ' . $scope->tpl->parseExp($tokens, true) . ': ';
if ($scope["switch"]) { if ($scope["switch"]) {
unset($scope["no-break"], $scope["no-continue"]); unset($scope["no-break"], $scope["no-continue"]);
@@ -327,7 +341,8 @@ class Compiler {
* @throws InvalidUsageException * @throws InvalidUsageException
* @return string * @return string
*/ */
public static function tagContinue($tokens, Scope $scope) { public static function tagContinue($tokens, Scope $scope)
{
if (empty($scope["no-continue"])) { if (empty($scope["no-continue"])) {
return 'continue;'; return 'continue;';
} else { } else {
@@ -343,7 +358,8 @@ class Compiler {
* @param Scope $scope * @param Scope $scope
* @return string * @return string
*/ */
public static function tagDefault($tokens, Scope $scope) { public static function tagDefault($tokens, Scope $scope)
{
$code = 'default: '; $code = 'default: ';
if ($scope["switch"]) { if ($scope["switch"]) {
unset($scope["no-break"], $scope["no-continue"]); unset($scope["no-break"], $scope["no-continue"]);
@@ -362,7 +378,8 @@ class Compiler {
* @throws InvalidUsageException * @throws InvalidUsageException
* @return string * @return string
*/ */
public static function tagBreak($tokens, Scope $scope) { public static function tagBreak($tokens, Scope $scope)
{
if (empty($scope["no-break"])) { if (empty($scope["no-break"])) {
return 'break;'; return 'break;';
} else { } else {
@@ -377,7 +394,8 @@ class Compiler {
* @throws InvalidUsageException * @throws InvalidUsageException
* @return string * @return string
*/ */
public static function tagExtends(Tokenizer $tokens, Template $tpl) { public static function tagExtends(Tokenizer $tokens, Template $tpl)
{
if (!empty($tpl->_extends)) { if (!empty($tpl->_extends)) {
throw new InvalidUsageException("Only one {extends} allowed"); throw new InvalidUsageException("Only one {extends} allowed");
} elseif ($tpl->getStackSize()) { } elseif ($tpl->getStackSize()) {
@@ -411,7 +429,8 @@ class Compiler {
* @param string $body * @param string $body
* @param Template $tpl * @param Template $tpl
*/ */
public static function extendBody(&$body, $tpl) { public static function extendBody(&$body, $tpl)
{
$t = $tpl; $t = $tpl;
if ($tpl->uses) { if ($tpl->uses) {
$tpl->blocks += $tpl->uses; $tpl->blocks += $tpl->uses;
@@ -452,7 +471,8 @@ class Compiler {
* @throws InvalidUsageException * @throws InvalidUsageException
* @return string * @return string
*/ */
public static function tagUse(Tokenizer $tokens, Template $tpl) { public static function tagUse(Tokenizer $tokens, Template $tpl)
{
if ($tpl->getStackSize()) { if ($tpl->getStackSize()) {
throw new InvalidUsageException("Tags {use} can not be nested"); throw new InvalidUsageException("Tags {use} can not be nested");
} }
@@ -491,7 +511,8 @@ class Compiler {
* @return string * @return string
* @throws InvalidUsageException * @throws InvalidUsageException
*/ */
public static function tagBlockOpen(Tokenizer $tokens, Scope $scope) { public static function tagBlockOpen(Tokenizer $tokens, Scope $scope)
{
if ($scope->level > 0) { if ($scope->level > 0) {
$scope->tpl->_compatible = true; $scope->tpl->_compatible = true;
} }
@@ -505,7 +526,8 @@ class Compiler {
* @param Scope $scope * @param Scope $scope
* @return string * @return string
*/ */
public static function tagBlockClose($tokens, Scope $scope) { public static function tagBlockClose($tokens, Scope $scope)
{
$tpl = $scope->tpl; $tpl = $scope->tpl;
if (isset($tpl->_extends)) { // is child if (isset($tpl->_extends)) { // is child
@@ -561,7 +583,8 @@ class Compiler {
} }
public static function tagParent($tokens, Scope $scope) { public static function tagParent($tokens, Scope $scope)
{
if (empty($scope->tpl->_extends)) { if (empty($scope->tpl->_extends)) {
throw new InvalidUsageException("Tag {parent} may be declared in children"); throw new InvalidUsageException("Tag {parent} may be declared in children");
} }
@@ -573,7 +596,8 @@ class Compiler {
* @static * @static
* @return string * @return string
*/ */
public static function stdClose() { public static function stdClose()
{
return '}'; return '}';
} }
@@ -586,7 +610,8 @@ class Compiler {
* @param Template $tpl * @param Template $tpl
* @return string * @return string
*/ */
public static function stdFuncParser($function, Tokenizer $tokens, Template $tpl) { public static function stdFuncParser($function, Tokenizer $tokens, Template $tpl)
{
return "$function(" . self::toArray($tpl->parseParams($tokens)) . ', $tpl)'; return "$function(" . self::toArray($tpl->parseParams($tokens)) . ', $tpl)';
} }
@@ -599,7 +624,8 @@ class Compiler {
* @param Template $tpl * @param Template $tpl
* @return string * @return string
*/ */
public static function smartFuncParser($function, Tokenizer $tokens, Template $tpl) { public static function smartFuncParser($function, Tokenizer $tokens, Template $tpl)
{
if (strpos($function, "::")) { if (strpos($function, "::")) {
list($class, $method) = explode("::", $function, 2); list($class, $method) = explode("::", $function, 2);
$ref = new \ReflectionMethod($class, $method); $ref = new \ReflectionMethod($class, $method);
@@ -628,7 +654,8 @@ class Compiler {
* @param Scope $scope * @param Scope $scope
* @return string * @return string
*/ */
public static function stdFuncOpen(Tokenizer $tokens, Scope $scope) { public static function stdFuncOpen(Tokenizer $tokens, Scope $scope)
{
$scope["params"] = self::toArray($scope->tpl->parseParams($tokens)); $scope["params"] = self::toArray($scope->tpl->parseParams($tokens));
return 'ob_start();'; return 'ob_start();';
} }
@@ -641,7 +668,8 @@ class Compiler {
* @param Scope $scope * @param Scope $scope
* @return string * @return string
*/ */
public static function stdFuncClose($tokens, Scope $scope) { public static function stdFuncClose($tokens, Scope $scope)
{
return $scope["function"] . '(' . $scope["params"] . ', ob_get_clean(), $tpl)'; return $scope["function"] . '(' . $scope["params"] . ', ob_get_clean(), $tpl)';
} }
@@ -650,7 +678,8 @@ class Compiler {
* @param $params * @param $params
* @return string * @return string
*/ */
public static function toArray($params) { public static function toArray($params)
{
$_code = array(); $_code = array();
foreach ($params as $k => $v) { foreach ($params as $k => $v) {
$_code[] = '"' . $k . '" => ' . $v; $_code[] = '"' . $k . '" => ' . $v;
@@ -664,7 +693,8 @@ class Compiler {
* @param Scope $scope * @param Scope $scope
* @return string * @return string
*/ */
public static function varOpen(Tokenizer $tokens, Scope $scope) { public static function varOpen(Tokenizer $tokens, Scope $scope)
{
$var = $scope->tpl->parseVariable($tokens, Template::DENY_MODS); $var = $scope->tpl->parseVariable($tokens, Template::DENY_MODS);
if ($tokens->is('=')) { // inline tag {var ...} if ($tokens->is('=')) { // inline tag {var ...}
$scope->is_closed = true; $scope->is_closed = true;
@@ -690,7 +720,8 @@ class Compiler {
* @param Scope $scope * @param Scope $scope
* @return string * @return string
*/ */
public static function varClose(Tokenizer $tokens, Scope $scope) { public static function varClose(Tokenizer $tokens, Scope $scope)
{
return $scope["name"] . '=' . $scope["value"] . ';'; return $scope["name"] . '=' . $scope["value"] . ';';
} }
@@ -700,7 +731,8 @@ class Compiler {
* @param Scope $scope * @param Scope $scope
* @return string * @return string
*/ */
public static function filterOpen(Tokenizer $tokens, Scope $scope) { public static function filterOpen(Tokenizer $tokens, Scope $scope)
{
$scope["filter"] = $scope->tpl->parseModifier($tokens, "ob_get_clean()"); $scope["filter"] = $scope->tpl->parseModifier($tokens, "ob_get_clean()");
return "ob_start();"; return "ob_start();";
} }
@@ -710,7 +742,8 @@ class Compiler {
* @param Scope $scope * @param Scope $scope
* @return string * @return string
*/ */
public static function filterClose($tokens, Scope $scope) { public static function filterClose($tokens, Scope $scope)
{
return "echo " . $scope["filter"] . ";"; return "echo " . $scope["filter"] . ";";
} }
@@ -722,7 +755,8 @@ class Compiler {
* @return string * @return string
* @throws InvalidUsageException * @throws InvalidUsageException
*/ */
public static function tagCycle(Tokenizer $tokens, Template $tpl) { public static function tagCycle(Tokenizer $tokens, Template $tpl)
{
if ($tokens->is("[")) { if ($tokens->is("[")) {
$exp = $tpl->parseArray($tokens); $exp = $tpl->parseArray($tokens);
} else { } else {
@@ -747,7 +781,8 @@ class Compiler {
* @param $index * @param $index
* @return mixed * @return mixed
*/ */
public static function cycle($vals, $index) { public static function cycle($vals, $index)
{
return $vals[$index % count($vals)]; return $vals[$index % count($vals)];
} }
@@ -760,7 +795,8 @@ class Compiler {
* @throws InvalidUsageException * @throws InvalidUsageException
* @return string * @return string
*/ */
public static function tagImport(Tokenizer $tokens, Template $tpl) { public static function tagImport(Tokenizer $tokens, Template $tpl)
{
$import = array(); $import = array();
if ($tokens->is('[')) { if ($tokens->is('[')) {
$tokens->next(); $tokens->next();
@@ -823,7 +859,8 @@ class Compiler {
* @param Scope $scope * @param Scope $scope
* @throws InvalidUsageException * @throws InvalidUsageException
*/ */
public static function macroOpen(Tokenizer $tokens, Scope $scope) { public static function macroOpen(Tokenizer $tokens, Scope $scope)
{
$scope["name"] = $tokens->get(Tokenizer::MACRO_STRING); $scope["name"] = $tokens->get(Tokenizer::MACRO_STRING);
$scope["recursive"] = array(); $scope["recursive"] = array();
$args = array(); $args = array();
@@ -861,7 +898,8 @@ class Compiler {
* @param Tokenizer $tokens * @param Tokenizer $tokens
* @param Scope $scope * @param Scope $scope
*/ */
public static function macroClose(Tokenizer $tokens, Scope $scope) { public static function macroClose(Tokenizer $tokens, Scope $scope)
{
if ($scope["recursive"]) { if ($scope["recursive"]) {
$switch = "switch(\$call['mark']) {\n"; $switch = "switch(\$call['mark']) {\n";
foreach ($scope["recursive"] as $mark) { foreach ($scope["recursive"] as $mark) {
@@ -889,7 +927,8 @@ class Compiler {
* @throws InvalidUsageException * @throws InvalidUsageException
* @return string * @return string
*/ */
public static function tagRaw(Tokenizer $tokens, Template $tpl) { public static function tagRaw(Tokenizer $tokens, Template $tpl)
{
$escape = (bool)$tpl->escape; $escape = (bool)$tpl->escape;
$tpl->escape = false; $tpl->escape = false;
if ($tokens->is(':')) { if ($tokens->is(':')) {
@@ -915,7 +954,8 @@ class Compiler {
* @param Tokenizer $tokens * @param Tokenizer $tokens
* @param Scope $scope * @param Scope $scope
*/ */
public static function autoescapeOpen(Tokenizer $tokens, Scope $scope) { public static function autoescapeOpen(Tokenizer $tokens, Scope $scope)
{
$boolean = ($tokens->get(T_STRING) == "true" ? true : false); $boolean = ($tokens->get(T_STRING) == "true" ? true : false);
$scope["escape"] = $scope->tpl->escape; $scope["escape"] = $scope->tpl->escape;
$scope->tpl->escape = $boolean; $scope->tpl->escape = $boolean;
@@ -926,7 +966,8 @@ class Compiler {
* @param Tokenizer $tokens * @param Tokenizer $tokens
* @param Scope $scope * @param Scope $scope
*/ */
public static function autoescapeClose(Tokenizer $tokens, Scope $scope) { public static function autoescapeClose(Tokenizer $tokens, Scope $scope)
{
$scope->tpl->escape = $scope["escape"]; $scope->tpl->escape = $scope["escape"];
} }
@@ -938,7 +979,8 @@ class Compiler {
* @return string * @return string
* @throws InvalidUsageException * @throws InvalidUsageException
*/ */
public static function tagUnset(Tokenizer $tokens, Template $tpl) { public static function tagUnset(Tokenizer $tokens, Template $tpl)
{
$vars = array(); $vars = array();
while ($tokens->valid()) { while ($tokens->valid()) {
$vars[] = $tpl->parseVar($tokens); $vars[] = $tpl->parseVar($tokens);

View File

@@ -13,7 +13,8 @@ namespace Fenom;
* Collection of modifiers * Collection of modifiers
* @author Ivan Shalganov <a.cobest@gmail.com> * @author Ivan Shalganov <a.cobest@gmail.com>
*/ */
class Modifier { class Modifier
{
/** /**
* Date format * Date format
@@ -22,7 +23,8 @@ class Modifier {
* @param string $format * @param string $format
* @return string * @return string
*/ */
public static function dateFormat($date, $format = "%b %e, %Y") { public static function dateFormat($date, $format = "%b %e, %Y")
{
if (is_string($date) && !is_numeric($date)) { if (is_string($date) && !is_numeric($date)) {
$date = strtotime($date); $date = strtotime($date);
if (!$date) $date = time(); if (!$date) $date = time();
@@ -35,7 +37,8 @@ class Modifier {
* @param string $format * @param string $format
* @return string * @return string
*/ */
public static function date($date, $format = "Y m d") { public static function date($date, $format = "Y m d")
{
if (is_string($date) && !is_numeric($date)) { if (is_string($date) && !is_numeric($date)) {
$date = strtotime($date); $date = strtotime($date);
if (!$date) $date = time(); if (!$date) $date = time();
@@ -50,7 +53,8 @@ class Modifier {
* @param string $type * @param string $type
* @return string * @return string
*/ */
public static function escape($text, $type = 'html') { public static function escape($text, $type = 'html')
{
switch (strtolower($type)) { switch (strtolower($type)) {
case "url": case "url":
return urlencode($text); return urlencode($text);
@@ -68,7 +72,8 @@ class Modifier {
* @param string $type * @param string $type
* @return string * @return string
*/ */
public static function unescape($text, $type = 'html') { public static function unescape($text, $type = 'html')
{
switch (strtolower($type)) { switch (strtolower($type)) {
case "url": case "url":
return urldecode($text); return urldecode($text);
@@ -89,7 +94,8 @@ class Modifier {
* @param bool $middle * @param bool $middle
* @return string * @return string
*/ */
public static function truncate($string, $length = 80, $etc = '...', $by_words = false, $middle = false) { public static function truncate($string, $length = 80, $etc = '...', $by_words = false, $middle = false)
{
if ($middle) { if ($middle) {
if (preg_match('#^(.{' . $length . '}).*?(.{' . $length . '})?$#usS', $string, $match)) { if (preg_match('#^(.{' . $length . '}).*?(.{' . $length . '})?$#usS', $string, $match)) {
if (count($match) == 3) { if (count($match) == 3) {
@@ -119,7 +125,8 @@ class Modifier {
* @param bool $to_line strip line ends * @param bool $to_line strip line ends
* @return string * @return string
*/ */
public static function strip($str, $to_line = false) { public static function strip($str, $to_line = false)
{
$str = trim($str); $str = trim($str);
if ($to_line) { if ($to_line) {
return preg_replace('#[\s]+#ms', ' ', $str); return preg_replace('#[\s]+#ms', ' ', $str);
@@ -133,7 +140,8 @@ class Modifier {
* @param mixed $item * @param mixed $item
* @return int * @return int
*/ */
public static function length($item) { public static function length($item)
{
if (is_string($item)) { if (is_string($item)) {
return strlen(preg_replace('#[\x00-\x7F]|[\x80-\xDF][\x00-\xBF]|[\xE0-\xEF][\x00-\xBF]{2}#s', ' ', $item)); return strlen(preg_replace('#[\x00-\x7F]|[\x80-\xDF][\x00-\xBF]|[\xE0-\xEF][\x00-\xBF]{2}#s', ' ', $item));
} elseif (is_array($item)) { } elseif (is_array($item)) {
@@ -151,7 +159,8 @@ class Modifier {
* @param mixed $haystack * @param mixed $haystack
* @return bool * @return bool
*/ */
public static function in($value, $haystack) { public static function in($value, $haystack)
{
if (is_array($haystack)) { if (is_array($haystack)) {
return in_array($value, $haystack) || array_key_exists($value, $haystack); return in_array($value, $haystack) || array_key_exists($value, $haystack);
} elseif (is_string($haystack)) { } elseif (is_string($haystack)) {
@@ -164,7 +173,8 @@ class Modifier {
* @param $value * @param $value
* @return bool * @return bool
*/ */
public static function isIterable($value) { public static function isIterable($value)
{
return is_array($value) || ($value instanceof \Iterator); return is_array($value) || ($value instanceof \Iterator);
} }
} }

View File

@@ -10,11 +10,13 @@
namespace Fenom; namespace Fenom;
use Fenom\ProviderInterface; use Fenom\ProviderInterface;
/** /**
* Base template provider * Base template provider
* @author Ivan Shalganov * @author Ivan Shalganov
*/ */
class Provider implements ProviderInterface { class Provider implements ProviderInterface
{
private $_path; private $_path;
/** /**
@@ -22,7 +24,8 @@ class Provider implements ProviderInterface {
* *
* @param string $path * @param string $path
*/ */
public static function clean($path) { public static function clean($path)
{
if (is_file($path)) { if (is_file($path)) {
unlink($path); unlink($path);
} elseif (is_dir($path)) { } elseif (is_dir($path)) {
@@ -51,7 +54,8 @@ class Provider implements ProviderInterface {
* *
* @param string $path * @param string $path
*/ */
public static function rm($path) { public static function rm($path)
{
self::clean($path); self::clean($path);
if (is_dir($path)) { if (is_dir($path)) {
rmdir($path); rmdir($path);
@@ -62,7 +66,8 @@ class Provider implements ProviderInterface {
* @param string $template_dir directory of templates * @param string $template_dir directory of templates
* @throws \LogicException if directory doesn't exists * @throws \LogicException if directory doesn't exists
*/ */
public function __construct($template_dir) { public function __construct($template_dir)
{
if ($_dir = realpath($template_dir)) { if ($_dir = realpath($template_dir)) {
$this->_path = $_dir; $this->_path = $_dir;
} else { } else {
@@ -76,7 +81,8 @@ class Provider implements ProviderInterface {
* @param int $time load last modified time * @param int $time load last modified time
* @return string * @return string
*/ */
public function getSource($tpl, &$time) { public function getSource($tpl, &$time)
{
$tpl = $this->_getTemplatePath($tpl); $tpl = $this->_getTemplatePath($tpl);
clearstatcache(null, $tpl); clearstatcache(null, $tpl);
$time = filemtime($tpl); $time = filemtime($tpl);
@@ -88,7 +94,8 @@ class Provider implements ProviderInterface {
* @param string $tpl * @param string $tpl
* @return int * @return int
*/ */
public function getLastModified($tpl) { public function getLastModified($tpl)
{
clearstatcache(null, $tpl = $this->_getTemplatePath($tpl)); clearstatcache(null, $tpl = $this->_getTemplatePath($tpl));
return filemtime($tpl); return filemtime($tpl);
} }
@@ -99,7 +106,8 @@ class Provider implements ProviderInterface {
* @param string $extension all templates must have this extension, default .tpl * @param string $extension all templates must have this extension, default .tpl
* @return array|\Iterator * @return array|\Iterator
*/ */
public function getList($extension = "tpl") { public function getList($extension = "tpl")
{
$list = array(); $list = array();
$iterator = new \RecursiveIteratorIterator( $iterator = new \RecursiveIteratorIterator(
new \RecursiveDirectoryIterator($this->_path, new \RecursiveDirectoryIterator($this->_path,
@@ -122,7 +130,8 @@ class Provider implements ProviderInterface {
* @return string * @return string
* @throws \RuntimeException * @throws \RuntimeException
*/ */
protected function _getTemplatePath($tpl) { protected function _getTemplatePath($tpl)
{
if (($path = realpath($this->_path . "/" . $tpl)) && strpos($path, $this->_path) === 0) { if (($path = realpath($this->_path . "/" . $tpl)) && strpos($path, $this->_path) === 0) {
return $path; return $path;
} else { } else {
@@ -134,7 +143,8 @@ class Provider implements ProviderInterface {
* @param string $tpl * @param string $tpl
* @return bool * @return bool
*/ */
public function templateExists($tpl) { public function templateExists($tpl)
{
return file_exists($this->_path . "/" . $tpl); return file_exists($this->_path . "/" . $tpl);
} }
@@ -144,7 +154,8 @@ class Provider implements ProviderInterface {
* @param array $templates [template_name => modified, ...] By conversation, you may trust the template's name * @param array $templates [template_name => modified, ...] By conversation, you may trust the template's name
* @return bool * @return bool
*/ */
public function verify(array $templates) { public function verify(array $templates)
{
foreach ($templates as $template => $mtime) { foreach ($templates as $template => $mtime) {
clearstatcache(null, $template = $this->_path . '/' . $template); clearstatcache(null, $template = $this->_path . '/' . $template);
if (@filemtime($template) !== $mtime) { if (@filemtime($template) !== $mtime) {

View File

@@ -14,7 +14,8 @@ namespace Fenom;
* @package Fenom * @package Fenom
* @author Ivan Shalganov <a.cobest@gmail.com> * @author Ivan Shalganov <a.cobest@gmail.com>
*/ */
interface ProviderInterface { interface ProviderInterface
{
/** /**
* @param string $tpl * @param string $tpl
* @return bool * @return bool

View File

@@ -14,7 +14,8 @@ use Fenom;
* Primitive template * Primitive template
* @author Ivan Shalganov <a.cobest@gmail.com> * @author Ivan Shalganov <a.cobest@gmail.com>
*/ */
class Render extends \ArrayObject { class Render extends \ArrayObject
{
private static $_props = array( private static $_props = array(
"name" => "runtime", "name" => "runtime",
"base_name" => "", "base_name" => "",
@@ -72,7 +73,8 @@ class Render extends \ArrayObject {
* @param callable $code template body * @param callable $code template body
* @param array $props * @param array $props
*/ */
public function __construct(Fenom $fenom, \Closure $code, array $props = array()) { public function __construct(Fenom $fenom, \Closure $code, array $props = array())
{
$this->_fenom = $fenom; $this->_fenom = $fenom;
$props += self::$_props; $props += self::$_props;
$this->_name = $props["name"]; $this->_name = $props["name"];
@@ -86,7 +88,8 @@ class Render extends \ArrayObject {
* Get template storage * Get template storage
* @return \Fenom * @return \Fenom
*/ */
public function getStorage() { public function getStorage()
{
return $this->_fenom; return $this->_fenom;
} }
@@ -94,7 +97,8 @@ class Render extends \ArrayObject {
* Get depends list * Get depends list
* @return array * @return array
*/ */
public function getDepends() { public function getDepends()
{
return $this->_depends; return $this->_depends;
} }
@@ -102,7 +106,8 @@ class Render extends \ArrayObject {
* Get schema name * Get schema name
* @return string * @return string
*/ */
public function getScm() { public function getScm()
{
return $this->_scm; return $this->_scm;
} }
@@ -110,7 +115,8 @@ class Render extends \ArrayObject {
* Get provider of template source * Get provider of template source
* @return ProviderInterface * @return ProviderInterface
*/ */
public function getProvider() { public function getProvider()
{
return $this->_fenom->getProvider($this->_scm); return $this->_fenom->getProvider($this->_scm);
} }
@@ -118,7 +124,8 @@ class Render extends \ArrayObject {
* Get name without schema * Get name without schema
* @return string * @return string
*/ */
public function getBaseName() { public function getBaseName()
{
return $this->_base_name; return $this->_base_name;
} }
@@ -126,14 +133,16 @@ class Render extends \ArrayObject {
* Get parse options * Get parse options
* @return int * @return int
*/ */
public function getOptions() { public function getOptions()
{
return $this->_options; return $this->_options;
} }
/** /**
* @return string * @return string
*/ */
public function __toString() { public function __toString()
{
return $this->_name; return $this->_name;
} }
@@ -141,11 +150,13 @@ class Render extends \ArrayObject {
* Get template name * Get template name
* @return string * @return string
*/ */
public function getName() { public function getName()
{
return $this->_name; return $this->_name;
} }
public function getTime() { public function getTime()
{
return $this->_time; return $this->_time;
} }
@@ -154,7 +165,8 @@ class Render extends \ArrayObject {
* Validate template * Validate template
* @return bool * @return bool
*/ */
public function isValid() { public function isValid()
{
if (count($this->_depends) === 1) { // if no external dependencies, only self if (count($this->_depends) === 1) { // if no external dependencies, only self
$provider = $this->_fenom->getProvider($this->_scm); $provider = $this->_fenom->getProvider($this->_scm);
if ($provider->getLastModified($this->_name) !== $this->_time) { if ($provider->getLastModified($this->_name) !== $this->_time) {
@@ -176,7 +188,8 @@ class Render extends \ArrayObject {
* @param array $values for template * @param array $values for template
* @return Render * @return Render
*/ */
public function display(array $values) { public function display(array $values)
{
$this->exchangeArray($values); $this->exchangeArray($values);
$this->_code->__invoke($this); $this->_code->__invoke($this);
return $this->exchangeArray(array()); return $this->exchangeArray(array());
@@ -188,7 +201,8 @@ class Render extends \ArrayObject {
* @return string * @return string
* @throws \Exception * @throws \Exception
*/ */
public function fetch(array $values) { public function fetch(array $values)
{
ob_start(); ob_start();
try { try {
$this->display($values); $this->display($values);
@@ -205,7 +219,8 @@ class Render extends \ArrayObject {
* @param $args * @param $args
* @throws \BadMethodCallException * @throws \BadMethodCallException
*/ */
public function __call($method, $args) { public function __call($method, $args)
{
throw new \BadMethodCallException("Unknown method " . $method); throw new \BadMethodCallException("Unknown method " . $method);
} }
} }

View File

@@ -14,7 +14,8 @@ namespace Fenom;
* *
* @author Ivan Shalganov <a.cobest@gmail.com> * @author Ivan Shalganov <a.cobest@gmail.com>
*/ */
class Scope extends \ArrayObject { class Scope extends \ArrayObject
{
public $line = 0; public $line = 0;
public $name; public $name;
@@ -40,7 +41,8 @@ class Scope extends \ArrayObject {
* @param int $level * @param int $level
* @param $body * @param $body
*/ */
public function __construct($name, $tpl, $line, $action, $level, &$body) { public function __construct($name, $tpl, $line, $action, $level, &$body)
{
$this->line = $line; $this->line = $line;
$this->name = $name; $this->name = $name;
$this->tpl = $tpl; $this->tpl = $tpl;
@@ -54,7 +56,8 @@ class Scope extends \ArrayObject {
* *
* @param string $function * @param string $function
*/ */
public function setFuncName($function) { public function setFuncName($function)
{
$this["function"] = $function; $this["function"] = $function;
$this->is_compiler = false; $this->is_compiler = false;
$this->escape = $this->tpl->escape; $this->escape = $this->tpl->escape;
@@ -66,7 +69,8 @@ class Scope extends \ArrayObject {
* @param Tokenizer $tokenizer * @param Tokenizer $tokenizer
* @return mixed * @return mixed
*/ */
public function open($tokenizer) { public function open($tokenizer)
{
return call_user_func($this->_action["open"], $tokenizer, $this); return call_user_func($this->_action["open"], $tokenizer, $this);
} }
@@ -77,7 +81,8 @@ class Scope extends \ArrayObject {
* @param int $level * @param int $level
* @return bool * @return bool
*/ */
public function hasTag($tag, $level) { public function hasTag($tag, $level)
{
if (isset($this->_action["tags"][$tag])) { if (isset($this->_action["tags"][$tag])) {
if ($level) { if ($level) {
return isset($this->_action["float_tags"][$tag]); return isset($this->_action["float_tags"][$tag]);
@@ -95,7 +100,8 @@ class Scope extends \ArrayObject {
* @param Tokenizer $tokenizer * @param Tokenizer $tokenizer
* @return string * @return string
*/ */
public function tag($tag, $tokenizer) { public function tag($tag, $tokenizer)
{
return call_user_func($this->_action["tags"][$tag], $tokenizer, $this); return call_user_func($this->_action["tags"][$tag], $tokenizer, $this);
} }
@@ -105,7 +111,8 @@ class Scope extends \ArrayObject {
* @param Tokenizer $tokenizer * @param Tokenizer $tokenizer
* @return string * @return string
*/ */
public function close($tokenizer) { public function close($tokenizer)
{
return call_user_func($this->_action["close"], $tokenizer, $this); return call_user_func($this->_action["close"], $tokenizer, $this);
} }
@@ -115,7 +122,8 @@ class Scope extends \ArrayObject {
* @throws \LogicException * @throws \LogicException
* @return string * @return string
*/ */
public function getContent() { public function getContent()
{
return substr($this->_body, $this->_offset); return substr($this->_body, $this->_offset);
} }
@@ -125,7 +133,8 @@ class Scope extends \ArrayObject {
* @return string * @return string
* @throws \LogicException * @throws \LogicException
*/ */
public function cutContent() { public function cutContent()
{
$content = substr($this->_body, $this->_offset + 1); $content = substr($this->_body, $this->_offset + 1);
$this->_body = substr($this->_body, 0, $this->_offset); $this->_body = substr($this->_body, 0, $this->_offset);
return $content; return $content;
@@ -136,12 +145,14 @@ class Scope extends \ArrayObject {
* *
* @param $new_content * @param $new_content
*/ */
public function replaceContent($new_content) { public function replaceContent($new_content)
{
$this->cutContent(); $this->cutContent();
$this->_body .= $new_content; $this->_body .= $new_content;
} }
public function unEscapeContent() { public function unEscapeContent()
{
} }
} }

View File

@@ -16,7 +16,8 @@ use Fenom;
* @package Fenom * @package Fenom
* @author Ivan Shalganov <a.cobest@gmail.com> * @author Ivan Shalganov <a.cobest@gmail.com>
*/ */
class Template extends Render { class Template extends Render
{
/** /**
* Disable array parser. * Disable array parser.
@@ -126,7 +127,8 @@ class Template extends Render {
* @param int $options * @param int $options
* @return \Fenom\Template * @return \Fenom\Template
*/ */
public function __construct(Fenom $fenom, $options) { public function __construct(Fenom $fenom, $options)
{
$this->_fenom = $fenom; $this->_fenom = $fenom;
$this->_options = $options; $this->_options = $options;
} }
@@ -135,7 +137,8 @@ class Template extends Render {
* Get tag stack size * Get tag stack size
* @return int * @return int
*/ */
public function getStackSize() { public function getStackSize()
{
return count($this->_stack); return count($this->_stack);
} }
@@ -145,7 +148,8 @@ class Template extends Render {
* @param bool $compile * @param bool $compile
* @return $this * @return $this
*/ */
public function load($name, $compile = true) { public function load($name, $compile = true)
{
$this->_name = $name; $this->_name = $name;
if ($provider = strstr($name, ":", true)) { if ($provider = strstr($name, ":", true)) {
$this->_scm = $provider; $this->_scm = $provider;
@@ -168,7 +172,8 @@ class Template extends Render {
* @param bool $compile * @param bool $compile
* @return \Fenom\Template * @return \Fenom\Template
*/ */
public function source($name, $src, $compile = true) { public function source($name, $src, $compile = true)
{
$this->_name = $name; $this->_name = $name;
$this->_src = $src; $this->_src = $src;
if ($compile) { if ($compile) {
@@ -182,13 +187,18 @@ class Template extends Render {
* *
* @throws CompileException * @throws CompileException
*/ */
public function compile() { public function compile()
{
$end = $pos = 0; $end = $pos = 0;
$this->escape = $this->_options & Fenom::AUTO_ESCAPE; $this->escape = $this->_options & Fenom::AUTO_ESCAPE;
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 ($this->_src[$start + 1]) { // check next character switch ($this->_src[$start + 1]) { // check next character
case "\n": case "\r": case "\t": case " ": case "}": // ignore the tag case "\n":
case "\r":
case "\t":
case " ":
case "}": // ignore the tag
$this->_appendText(substr($this->_src, $pos, $start - $pos + 2)); $this->_appendText(substr($this->_src, $pos, $start - $pos + 2));
$end = $start + 1; $end = $start + 1;
break; break;
@@ -266,7 +276,8 @@ class Template extends Render {
* Execute some code in loading cache * Execute some code in loading cache
* @param $code * @param $code
*/ */
public function before($code) { public function before($code)
{
$this->_before .= $code; $this->_before .= $code;
} }
@@ -274,7 +285,8 @@ class Template extends Render {
* Generate temporary internal template variable * Generate temporary internal template variable
* @return string * @return string
*/ */
public function tmpVar() { public function tmpVar()
{
return '$t' . ($this->i++); return '$t' . ($this->i++);
} }
@@ -283,7 +295,8 @@ class Template extends Render {
* *
* @param string $text * @param string $text
*/ */
private function _appendText($text) { private function _appendText($text)
{
$this->_line += substr_count($text, "\n"); $this->_line += substr_count($text, "\n");
if ($this->_filter) { if ($this->_filter) {
if (strpos($text, "<?") === false) { if (strpos($text, "<?") === false) {
@@ -309,7 +322,8 @@ class Template extends Render {
* @param int $code * @param int $code
* @return string * @return string
*/ */
private function _escapeCode($code) { private function _escapeCode($code)
{
$c = ""; $c = "";
foreach (token_get_all($code) as $token) { foreach (token_get_all($code) as $token) {
if (is_string($token)) { if (is_string($token)) {
@@ -329,7 +343,8 @@ class Template extends Render {
* @param string $code * @param string $code
* @param $source * @param $source
*/ */
private function _appendCode($code, $source) { private function _appendCode($code, $source)
{
if (!$code) { if (!$code) {
return; return;
} else { } else {
@@ -344,7 +359,8 @@ class Template extends Render {
/** /**
* @param callable[] $cb * @param callable[] $cb
*/ */
public function addPostCompile($cb) { public function addPostCompile($cb)
{
$this->_post[] = $cb; $this->_post[] = $cb;
} }
@@ -353,7 +369,8 @@ class Template extends Render {
* *
* @return string * @return string
*/ */
public function getBody() { public function getBody()
{
return $this->_body; return $this->_body;
} }
@@ -362,7 +379,8 @@ class Template extends Render {
* *
* @return string * @return string
*/ */
public function getTemplateCode() { public function getTemplateCode()
{
$before = $this->_before ? $this->_before . "\n" : ""; $before = $this->_before ? $this->_before . "\n" : "";
return "<?php \n" . return "<?php \n" .
"/** Fenom template '" . $this->_name . "' compiled at " . date('Y-m-d H:i:s') . " */\n" . "/** Fenom template '" . $this->_name . "' compiled at " . date('Y-m-d H:i:s') . " */\n" .
@@ -381,7 +399,8 @@ class Template extends Render {
* Return closure code * Return closure code
* @return string * @return string
*/ */
private function _getClosureSource() { private function _getClosureSource()
{
return "function (\$tpl) {\n?>{$this->_body}<?php\n}"; return "function (\$tpl) {\n?>{$this->_body}<?php\n}";
} }
@@ -392,7 +411,8 @@ class Template extends Render {
* @throws CompileException * @throws CompileException
* @return Render * @return Render
*/ */
public function display(array $values) { public function display(array $values)
{
if (!$this->_code) { if (!$this->_code) {
// evaluate template's code // evaluate template's code
eval("\$this->_code = " . $this->_getClosureSource() . ";"); eval("\$this->_code = " . $this->_getClosureSource() . ";");
@@ -408,7 +428,8 @@ class Template extends Render {
* Add depends from template * Add depends from template
* @param Render $tpl * @param Render $tpl
*/ */
public function addDepend(Render $tpl) { public function addDepend(Render $tpl)
{
$this->_depends[$tpl->getScm()][$tpl->getName()] = $tpl->getTime(); $this->_depends[$tpl->getScm()][$tpl->getName()] = $tpl->getTime();
} }
@@ -418,13 +439,15 @@ class Template extends Render {
* @param $data * @param $data
* @return string * @return string
*/ */
public function out($data) { public function out($data)
{
if ($this->escape) { if ($this->escape) {
return "echo htmlspecialchars($data, ENT_COMPAT, 'UTF-8');"; return "echo htmlspecialchars($data, ENT_COMPAT, 'UTF-8');";
} else { } else {
return "echo $data;"; return "echo $data;";
} }
} }
/** /**
* Tag router * Tag router
* @param Tokenizer $tokens * @param Tokenizer $tokens
@@ -433,7 +456,8 @@ class Template extends Render {
* @throws CompileException * @throws CompileException
* @return string executable PHP code * @return string executable PHP code
*/ */
public function parseTag(Tokenizer $tokens) { public function parseTag(Tokenizer $tokens)
{
try { try {
if ($tokens->is(Tokenizer::MACRO_STRING)) { if ($tokens->is(Tokenizer::MACRO_STRING)) {
if ($tokens->current() === "ignore") { if ($tokens->current() === "ignore") {
@@ -466,7 +490,8 @@ class Template extends Render {
* @return string * @return string
* @throws TokenizeException * @throws TokenizeException
*/ */
public function parseEndTag(Tokenizer $tokens) { public function parseEndTag(Tokenizer $tokens)
{
$name = $tokens->getNext(Tokenizer::MACRO_STRING); $name = $tokens->getNext(Tokenizer::MACRO_STRING);
$tokens->next(); $tokens->next();
if (!$this->_stack) { if (!$this->_stack) {
@@ -490,7 +515,8 @@ class Template extends Render {
* Get current scope * Get current scope
* @return Scope * @return Scope
*/ */
public function getLastScope() { public function getLastScope()
{
return end($this->_stack); return end($this->_stack);
} }
@@ -503,7 +529,8 @@ class Template extends Render {
* @throws TokenizeException * @throws TokenizeException
* @return string * @return string
*/ */
public function parseAct(Tokenizer $tokens) { public function parseAct(Tokenizer $tokens)
{
if ($tokens->is(Tokenizer::MACRO_STRING)) { if ($tokens->is(Tokenizer::MACRO_STRING)) {
$action = $tokens->getAndNext(); $action = $tokens->getAndNext();
} else { } else {
@@ -570,7 +597,8 @@ class Template extends Render {
* @throws \Exception * @throws \Exception
* @return string * @return string
*/ */
public function parseExp(Tokenizer $tokens, $required = false) { public function parseExp(Tokenizer $tokens, $required = false)
{
$_exp = array(); // expression as PHP code $_exp = array(); // expression as PHP code
$term = false; // last item was variable or value. $term = false; // last item was variable or value.
// 0 - was operator, but trem required // 0 - was operator, but trem required
@@ -697,7 +725,8 @@ class Template extends Render {
* @param int $options * @param int $options
* @return string * @return string
*/ */
public function parseVar(Tokenizer $tokens, $options = 0) { public function parseVar(Tokenizer $tokens, $options = 0)
{
$var = $tokens->get(T_VARIABLE); $var = $tokens->get(T_VARIABLE);
$_var = '$tpl["' . substr($var, 1) . '"]'; $_var = '$tpl["' . substr($var, 1) . '"]';
$tokens->next(); $tokens->next();
@@ -761,7 +790,8 @@ class Template extends Render {
* @throws InvalidUsageException * @throws InvalidUsageException
* @return string * @return string
*/ */
public function parseVariable(Tokenizer $tokens, $options = 0, $var = null) { public function parseVariable(Tokenizer $tokens, $options = 0, $var = null)
{
$stained = false; $stained = false;
if (!$var) { if (!$var) {
if ($tokens->is(Tokenizer::MACRO_INCDEC)) { if ($tokens->is(Tokenizer::MACRO_INCDEC)) {
@@ -810,7 +840,8 @@ class Template extends Render {
* @return string * @return string
* @throws UnexpectedTokenException * @throws UnexpectedTokenException
*/ */
public function parseTernary(Tokenizer $tokens, $var, $type) { public function parseTernary(Tokenizer $tokens, $var, $type)
{
$empty = ($type === "?"); $empty = ($type === "?");
$tokens->next(); $tokens->next();
if ($tokens->is(":")) { if ($tokens->is(":")) {
@@ -849,7 +880,8 @@ class Template extends Render {
* @throws InvalidUsageException * @throws InvalidUsageException
* @return string * @return string
*/ */
public function parseIs(Tokenizer $tokens, $value, $variable = false) { public function parseIs(Tokenizer $tokens, $value, $variable = false)
{
$tokens->next(); $tokens->next();
if ($tokens->current() == 'not') { if ($tokens->current() == 'not') {
$invert = '!'; $invert = '!';
@@ -894,7 +926,8 @@ class Template extends Render {
* @throws UnexpectedTokenException * @throws UnexpectedTokenException
* @return string * @return string
*/ */
public function parseIn(Tokenizer $tokens, $value) { public function parseIn(Tokenizer $tokens, $value)
{
$checkers = array( $checkers = array(
"string" => 'is_int(strpos(%2$s, %1$s))', "string" => 'is_int(strpos(%2$s, %1$s))',
"list" => "in_array(%s, %s)", "list" => "in_array(%s, %s)",
@@ -948,7 +981,8 @@ class Template extends Render {
* @param Tokenizer $tokens * @param Tokenizer $tokens
* @return string * @return string
*/ */
public function parseName(Tokenizer $tokens) { public function parseName(Tokenizer $tokens)
{
$tokens->skipIf(T_NS_SEPARATOR); $tokens->skipIf(T_NS_SEPARATOR);
$name = ""; $name = "";
if ($tokens->is(T_STRING)) { if ($tokens->is(T_STRING)) {
@@ -969,7 +1003,8 @@ class Template extends Render {
* @return string * @return string
* @throws TokenizeException * @throws TokenizeException
*/ */
public function parseScalar(Tokenizer $tokens, $allow_mods = true) { public function parseScalar(Tokenizer $tokens, $allow_mods = true)
{
$_scalar = ""; $_scalar = "";
if ($token = $tokens->key()) { if ($token = $tokens->key()) {
switch ($token) { switch ($token) {
@@ -999,7 +1034,8 @@ class Template extends Render {
* @throws UnexpectedTokenException * @throws UnexpectedTokenException
* @return string * @return string
*/ */
public function parseSubstr(Tokenizer $tokens) { public function parseSubstr(Tokenizer $tokens)
{
if ($tokens->is('"', "`")) { if ($tokens->is('"', "`")) {
$stop = $tokens->current(); $stop = $tokens->current();
$_str = '"'; $_str = '"';
@@ -1066,7 +1102,8 @@ class Template extends Render {
* @throws \Exception * @throws \Exception
* @return string * @return string
*/ */
public function parseModifier(Tokenizer $tokens, $value) { public function parseModifier(Tokenizer $tokens, $value)
{
while ($tokens->is("|")) { while ($tokens->is("|")) {
$mods = $this->_fenom->getModifier($tokens->getNext(Tokenizer::MACRO_STRING), $this); $mods = $this->_fenom->getModifier($tokens->getNext(Tokenizer::MACRO_STRING), $this);
if (!$mods) { if (!$mods) {
@@ -1118,7 +1155,8 @@ class Template extends Render {
* @throws UnexpectedTokenException * @throws UnexpectedTokenException
* @return string * @return string
*/ */
public function parseArray(Tokenizer $tokens) { public function parseArray(Tokenizer $tokens)
{
if ($tokens->is("[")) { if ($tokens->is("[")) {
$_arr = "array("; $_arr = "array(";
$key = $val = false; $key = $val = false;
@@ -1163,7 +1201,8 @@ class Template extends Render {
* @return string * @return string
* @throws InvalidUsageException * @throws InvalidUsageException
*/ */
public function parseConst(Tokenizer $tokens) { public function parseConst(Tokenizer $tokens)
{
$tokens->get('#'); $tokens->get('#');
$name = $tokens->getNext(T_STRING); $name = $tokens->getNext(T_STRING);
$tokens->next(); $tokens->next();
@@ -1190,7 +1229,8 @@ class Template extends Render {
* @return string * @return string
* @throws InvalidUsageException * @throws InvalidUsageException
*/ */
public function parseMacroCall(Tokenizer $tokens, $name) { public function parseMacroCall(Tokenizer $tokens, $name)
{
$recursive = false; $recursive = false;
$macro = false; $macro = false;
if (isset($this->macros[$name])) { if (isset($this->macros[$name])) {
@@ -1238,7 +1278,8 @@ class Template extends Render {
* @throws TokenizeException * @throws TokenizeException
* @return string * @return string
*/ */
public function parseArgs(Tokenizer $tokens) { public function parseArgs(Tokenizer $tokens)
{
$_args = "("; $_args = "(";
$tokens->next(); $tokens->next();
$arg = $colon = false; $arg = $colon = false;
@@ -1273,7 +1314,8 @@ class Template extends Render {
* @param string $static * @param string $static
* @return mixed|string * @return mixed|string
*/ */
public function parsePlainArg(Tokenizer $tokens, &$static) { public function parsePlainArg(Tokenizer $tokens, &$static)
{
if ($tokens->is(T_CONSTANT_ENCAPSED_STRING)) { if ($tokens->is(T_CONSTANT_ENCAPSED_STRING)) {
if ($tokens->isNext('|')) { if ($tokens->isNext('|')) {
return $this->parseExp($tokens, true); return $this->parseExp($tokens, true);
@@ -1301,7 +1343,8 @@ class Template extends Render {
* @throws \Exception * @throws \Exception
* @return array * @return array
*/ */
public function parseParams(Tokenizer $tokens, array $defaults = null) { public function parseParams(Tokenizer $tokens, array $defaults = null)
{
$params = array(); $params = array();
while ($tokens->valid()) { while ($tokens->valid()) {
if ($tokens->is(Tokenizer::MACRO_STRING)) { if ($tokens->is(Tokenizer::MACRO_STRING)) {
@@ -1329,7 +1372,18 @@ class Template extends Render {
} }
} }
class CompileException extends \ErrorException {} class CompileException extends \ErrorException
class SecurityException extends CompileException {} {
class InvalidUsageException extends \LogicException {} }
class TokenizeException extends \RuntimeException {}
class SecurityException extends CompileException
{
}
class InvalidUsageException extends \LogicException
{
}
class TokenizeException extends \RuntimeException
{
}

View File

@@ -35,7 +35,8 @@ defined('T_YIELD') || define('T_YIELD', 370);
* @package Fenom * @package Fenom
* @author Ivan Shalganov <a.cobest@gmail.com> * @author Ivan Shalganov <a.cobest@gmail.com>
*/ */
class Tokenizer { class Tokenizer
{
const TOKEN = 0; const TOKEN = 0;
const TEXT = 1; const TEXT = 1;
const WHITESPACE = 2; const WHITESPACE = 2;
@@ -159,7 +160,8 @@ class Tokenizer {
/** /**
* @param $query * @param $query
*/ */
public function __construct($query) { public function __construct($query)
{
$tokens = array(-1 => array(\T_WHITESPACE, '', '', 1)); $tokens = array(-1 => array(\T_WHITESPACE, '', '', 1));
$_tokens = token_get_all("<?php " . $query); $_tokens = token_get_all("<?php " . $query);
$line = 1; $line = 1;
@@ -202,7 +204,8 @@ class Tokenizer {
* *
* @return int * @return int
*/ */
public function isIncomplete() { public function isIncomplete()
{
return ($this->quotes % 2) || ($this->tokens[$this->_max][0] === T_ENCAPSED_AND_WHITESPACE); return ($this->quotes % 2) || ($this->tokens[$this->_max][0] === T_ENCAPSED_AND_WHITESPACE);
} }
@@ -212,7 +215,8 @@ class Tokenizer {
* @link http://php.net/manual/en/iterator.current.php * @link http://php.net/manual/en/iterator.current.php
* @return mixed Can return any type. * @return mixed Can return any type.
*/ */
public function current() { public function current()
{
return $this->curr[1]; return $this->curr[1];
} }
@@ -222,7 +226,8 @@ class Tokenizer {
* @link http://php.net/manual/en/iterator.next.php * @link http://php.net/manual/en/iterator.next.php
* @return Tokenizer * @return Tokenizer
*/ */
public function next() { public function next()
{
if ($this->p > $this->_max) { if ($this->p > $this->_max) {
return $this; return $this;
} }
@@ -238,7 +243,8 @@ class Tokenizer {
* @param string|int $token * @param string|int $token
* @return bool * @return bool
*/ */
private function _valid($expects, $token) { private function _valid($expects, $token)
{
foreach ($expects as $expect) { foreach ($expects as $expect) {
if (is_string($expect) || $expect < 1000) { if (is_string($expect) || $expect < 1000) {
if ($expect === $token) { if ($expect === $token) {
@@ -260,7 +266,8 @@ class Tokenizer {
* @throws UnexpectedTokenException * @throws UnexpectedTokenException
* @return mixed * @return mixed
*/ */
public function _next($tokens) { public function _next($tokens)
{
$this->next(); $this->next();
if (!$this->curr) { if (!$this->curr) {
throw new UnexpectedTokenException($this, $tokens); throw new UnexpectedTokenException($this, $tokens);
@@ -279,7 +286,8 @@ class Tokenizer {
* Fetch next specified token or throw an exception * Fetch next specified token or throw an exception
* @return mixed * @return mixed
*/ */
public function getNext(/*int|string $token1, int|string $token2, ... */) { public function getNext( /*int|string $token1, int|string $token2, ... */)
{
$this->_next(func_get_args()); $this->_next(func_get_args());
return $this->current(); return $this->current();
} }
@@ -288,7 +296,8 @@ class Tokenizer {
* @param $token * @param $token
* @return bool * @return bool
*/ */
public function isNextToken($token) { public function isNextToken($token)
{
return $this->next ? $this->next[1] == $token : false; return $this->next ? $this->next[1] == $token : false;
} }
@@ -298,7 +307,8 @@ class Tokenizer {
* @param int $limit * @param int $limit
* @return string * @return string
*/ */
public function getSubstr($offset, $limit = 0) { public function getSubstr($offset, $limit = 0)
{
$str = ''; $str = '';
if (!$limit) { if (!$limit) {
$limit = $this->_max; $limit = $this->_max;
@@ -316,7 +326,8 @@ class Tokenizer {
* @return mixed * @return mixed
* @throws UnexpectedTokenException * @throws UnexpectedTokenException
*/ */
public function getAndNext() { public function getAndNext()
{
if ($this->curr) { if ($this->curr) {
$cur = $this->curr[1]; $cur = $this->curr[1];
$this->next(); $this->next();
@@ -331,7 +342,8 @@ class Tokenizer {
* @param $token1 * @param $token1
* @return bool * @return bool
*/ */
public function isNext($token1/*, ...*/) { public function isNext($token1 /*, ...*/)
{
return $this->next && $this->_valid(func_get_args(), $this->next[0]); return $this->next && $this->_valid(func_get_args(), $this->next[0]);
} }
@@ -340,7 +352,8 @@ class Tokenizer {
* @param $token1 * @param $token1
* @return bool * @return bool
*/ */
public function is($token1/*, ...*/) { public function is($token1 /*, ...*/)
{
return $this->curr && $this->_valid(func_get_args(), $this->curr[0]); return $this->curr && $this->_valid(func_get_args(), $this->curr[0]);
} }
@@ -349,7 +362,8 @@ class Tokenizer {
* @param $token1 * @param $token1
* @return bool * @return bool
*/ */
public function isPrev($token1/*, ...*/) { public function isPrev($token1 /*, ...*/)
{
return $this->prev && $this->_valid(func_get_args(), $this->prev[0]); return $this->prev && $this->_valid(func_get_args(), $this->prev[0]);
} }
@@ -360,7 +374,8 @@ class Tokenizer {
* @throws UnexpectedTokenException * @throws UnexpectedTokenException
* @return mixed * @return mixed
*/ */
public function get($token1 /*, $token2 ...*/) { public function get($token1 /*, $token2 ...*/)
{
if ($this->curr && $this->_valid(func_get_args(), $this->curr[0])) { if ($this->curr && $this->_valid(func_get_args(), $this->curr[0])) {
return $this->curr[1]; return $this->curr[1];
} else { } else {
@@ -372,7 +387,8 @@ class Tokenizer {
* Step back * Step back
* @return Tokenizer * @return Tokenizer
*/ */
public function back() { public function back()
{
if ($this->p === 0) { if ($this->p === 0) {
return $this; return $this;
} }
@@ -385,7 +401,8 @@ class Tokenizer {
* @param $token1 * @param $token1
* @return bool * @return bool
*/ */
public function hasBackList($token1 /*, $token2 ...*/) { public function hasBackList($token1 /*, $token2 ...*/)
{
$tokens = func_get_args(); $tokens = func_get_args();
$c = $this->p; $c = $this->p;
foreach ($tokens as $token) { foreach ($tokens as $token) {
@@ -403,7 +420,8 @@ class Tokenizer {
* @param string $key * @param string $key
* @return mixed * @return mixed
*/ */
public function __get($key) { public function __get($key)
{
switch ($key) { switch ($key) {
case 'curr': case 'curr':
return $this->curr = ($this->p <= $this->_max) ? $this->tokens[$this->p] : null; return $this->curr = ($this->p <= $this->_max) ? $this->tokens[$this->p] : null;
@@ -416,7 +434,8 @@ class Tokenizer {
} }
} }
public function count() { public function count()
{
return $this->_max; return $this->_max;
} }
@@ -424,7 +443,8 @@ class Tokenizer {
* Return the key of the current element * Return the key of the current element
* @return mixed scalar on success, or null on failure. * @return mixed scalar on success, or null on failure.
*/ */
public function key() { public function key()
{
return $this->curr ? $this->curr[0] : null; return $this->curr ? $this->curr[0] : null;
} }
@@ -433,7 +453,8 @@ class Tokenizer {
* @return boolean The return value will be casted to boolean and then evaluated. * @return boolean The return value will be casted to boolean and then evaluated.
* Returns true on success or false on failure. * Returns true on success or false on failure.
*/ */
public function valid() { public function valid()
{
return (bool)$this->curr; return (bool)$this->curr;
} }
@@ -443,7 +464,8 @@ class Tokenizer {
* @param int|string $token * @param int|string $token
* @return string * @return string
*/ */
public static function getName($token) { public static function getName($token)
{
if (is_string($token)) { if (is_string($token)) {
return $token; return $token;
} elseif (is_integer($token)) { } elseif (is_integer($token)) {
@@ -461,7 +483,8 @@ class Tokenizer {
* @throws UnexpectedTokenException * @throws UnexpectedTokenException
* @return Tokenizer * @return Tokenizer
*/ */
public function skip(/*$token1, $token2, ...*/) { public function skip( /*$token1, $token2, ...*/)
{
if (func_num_args()) { if (func_num_args()) {
if ($this->_valid(func_get_args(), $this->curr[0])) { if ($this->_valid(func_get_args(), $this->curr[0])) {
$this->next(); $this->next();
@@ -481,7 +504,8 @@ class Tokenizer {
* @param int|string $token1 * @param int|string $token1
* @return Tokenizer * @return Tokenizer
*/ */
public function skipIf($token1/*, $token2, ...*/) { public function skipIf($token1 /*, $token2, ...*/)
{
if ($this->_valid(func_get_args(), $this->curr[0])) { if ($this->_valid(func_get_args(), $this->curr[0])) {
$this->next(); $this->next();
} }
@@ -495,7 +519,8 @@ class Tokenizer {
* @return Tokenizer * @return Tokenizer
* @throws UnexpectedTokenException * @throws UnexpectedTokenException
*/ */
public function need($token1/*, $token2, ...*/) { public function need($token1 /*, $token2, ...*/)
{
if ($this->_valid(func_get_args(), $this->curr[0])) { if ($this->_valid(func_get_args(), $this->curr[0])) {
return $this; return $this;
} else { } else {
@@ -509,7 +534,8 @@ class Tokenizer {
* @param int $after count tokens after current token * @param int $after count tokens after current token
* @return array * @return array
*/ */
public function getSnippet($before = 0, $after = 0) { public function getSnippet($before = 0, $after = 0)
{
$from = 0; $from = 0;
$to = $this->p; $to = $this->p;
if ($before > 0) { if ($before > 0) {
@@ -551,7 +577,8 @@ class Tokenizer {
* @param int $after * @param int $after
* @return string * @return string
*/ */
public function getSnippetAsString($before = 0, $after = 0) { public function getSnippetAsString($before = 0, $after = 0)
{
$str = ""; $str = "";
foreach ($this->getSnippet($before, $after) as $token) { foreach ($this->getSnippet($before, $after) as $token) {
$str .= $token[1] . $token[2]; $str .= $token[1] . $token[2];
@@ -563,7 +590,8 @@ class Tokenizer {
* Check if current is special value: true, TRUE, false, FALSE, null, NULL * Check if current is special value: true, TRUE, false, FALSE, null, NULL
* @return bool * @return bool
*/ */
public function isSpecialVal() { public function isSpecialVal()
{
return isset(self::$spec[$this->current()]); return isset(self::$spec[$this->current()]);
} }
@@ -571,14 +599,16 @@ class Tokenizer {
* Check if the token is last * Check if the token is last
* @return bool * @return bool
*/ */
public function isLast() { public function isLast()
{
return $this->p === $this->_max; return $this->p === $this->_max;
} }
/** /**
* Move pointer to the end * Move pointer to the end
*/ */
public function end() { public function end()
{
$this->p = $this->_max; $this->p = $this->_max;
} }
@@ -586,7 +616,8 @@ class Tokenizer {
* Return line number of the current token * Return line number of the current token
* @return mixed * @return mixed
*/ */
public function getLine() { public function getLine()
{
return $this->curr ? $this->curr[3] : $this->_last_no; return $this->curr ? $this->curr[3] : $this->_last_no;
} }
@@ -594,33 +625,13 @@ class Tokenizer {
* Is current token whitespaced, means previous token has whitespace characters * Is current token whitespaced, means previous token has whitespace characters
* @return bool * @return bool
*/ */
public function isWhiteSpaced() { public function isWhiteSpaced()
{
return $this->prev ? (bool)$this->prev[2] : false; return $this->prev ? (bool)$this->prev[2] : false;
} }
public function getWhitespace() { public function getWhitespace()
{
return $this->curr ? $this->curr[2] : false; return $this->curr ? $this->curr[2] : false;
} }
} }
/**
* Unexpected token
*/
class UnexpectedTokenException extends \RuntimeException {
public function __construct(Tokenizer $tokens, $expect = null, $where = null) {
if($expect && count($expect) == 1 && is_string($expect[0])) {
$expect = ", expect '".$expect[0]."'";
} else {
$expect = "";
}
if(!$tokens->curr) {
$this->message = "Unexpected end of ".($where?:"expression")."$expect";
} elseif($tokens->curr[0] === T_WHITESPACE) {
$this->message = "Unexpected whitespace$expect";
} elseif($tokens->curr[0] === T_BAD_CHARACTER) {
$this->message = "Unexpected bad characters (below ASCII 32 except \\t, \\n and \\r) in ".($where?:"expression")."$expect";
} else {
$this->message = "Unexpected token '".$tokens->current()."' in ".($where?:"expression")."$expect";
}
}
};

View File

@@ -0,0 +1,29 @@
<?php
namespace Fenom;
/**
* Unexpected token
*/
class UnexpectedTokenException extends \RuntimeException
{
public function __construct(Tokenizer $tokens, $expect = null, $where = null)
{
if ($expect && count($expect) == 1 && is_string($expect[0])) {
$expect = ", expect '" . $expect[0] . "'";
} else {
$expect = "";
}
if (!$tokens->curr) {
$this->message = "Unexpected end of " . ($where ? : "expression") . "$expect";
} elseif ($tokens->curr[0] === T_WHITESPACE) {
$this->message = "Unexpected whitespace$expect";
} elseif ($tokens->curr[0] === T_BAD_CHARACTER) {
$this->message = "Unexpected bad characters (below ASCII 32 except \\t, \\n and \\r) in " . ($where ? : "expression") . "$expect";
} else {
$this->message = "Unexpected token '" . $tokens->current() . "' in " . ($where ? : "expression") . "$expect";
}
}
}
;

View File

@@ -2,7 +2,8 @@
namespace Fenom; namespace Fenom;
use Fenom, Fenom\Provider as FS; use Fenom, Fenom\Provider as FS;
class TestCase extends \PHPUnit_Framework_TestCase { class TestCase extends \PHPUnit_Framework_TestCase
{
/** /**
* @var Fenom * @var Fenom
*/ */
@@ -21,7 +22,8 @@ class TestCase extends \PHPUnit_Framework_TestCase {
3 => "three value", 3 => "three value",
); );
public static function getVars() { public static function getVars()
{
return array( return array(
"zero" => 0, "zero" => 0,
"one" => 1, "one" => 1,
@@ -41,7 +43,8 @@ class TestCase extends \PHPUnit_Framework_TestCase {
); );
} }
public function setUp() { public function setUp()
{
if (!file_exists(FENOM_RESOURCES . '/compile')) { if (!file_exists(FENOM_RESOURCES . '/compile')) {
mkdir(FENOM_RESOURCES . '/compile', 0777, true); mkdir(FENOM_RESOURCES . '/compile', 0777, true);
} else { } else {
@@ -55,23 +58,28 @@ class TestCase extends \PHPUnit_Framework_TestCase {
$this->fenom->addBlockFunction('test_block_function', __CLASS__ . '::blockFunction'); $this->fenom->addBlockFunction('test_block_function', __CLASS__ . '::blockFunction');
} }
public static function dots($value) { public static function dots($value)
{
return $value . "..."; return $value . "...";
} }
public static function concat() { public static function concat()
{
return call_user_func_array('var_export', func_get_args()); return call_user_func_array('var_export', func_get_args());
} }
public static function inlineFunction($params) { public static function inlineFunction($params)
{
return isset($params["text"]) ? $params["text"] : ""; return isset($params["text"]) ? $params["text"] : "";
} }
public static function blockFunction($params, $text) { public static function blockFunction($params, $text)
{
return $text; return $text;
} }
public static function setUpBeforeClass() { public static function setUpBeforeClass()
{
if (!file_exists(FENOM_RESOURCES . '/template')) { if (!file_exists(FENOM_RESOURCES . '/template')) {
mkdir(FENOM_RESOURCES . '/template', 0777, true); mkdir(FENOM_RESOURCES . '/template', 0777, true);
} else { } else {
@@ -79,7 +87,8 @@ class TestCase extends \PHPUnit_Framework_TestCase {
} }
} }
public function tpl($name, $code) { public function tpl($name, $code)
{
$dir = dirname($name); $dir = dirname($name);
if ($dir != "." && !is_dir(FENOM_RESOURCES . '/template/' . $dir)) { if ($dir != "." && !is_dir(FENOM_RESOURCES . '/template/' . $dir)) {
mkdir(FENOM_RESOURCES . '/template/' . $dir, 0777, true); mkdir(FENOM_RESOURCES . '/template/' . $dir, 0777, true);
@@ -96,7 +105,8 @@ class TestCase extends \PHPUnit_Framework_TestCase {
* @param int $options * @param int $options
* @param bool $dump dump source and result code (for debug) * @param bool $dump dump source and result code (for debug)
*/ */
public function exec($code, $vars, $result, $options = 0, $dump = false) { public function exec($code, $vars, $result, $options = 0, $dump = false)
{
$this->fenom->setOptions($options); $this->fenom->setOptions($options);
$tpl = $this->fenom->compileCode($code, "runtime.tpl"); $tpl = $this->fenom->compileCode($code, "runtime.tpl");
if ($dump) { if ($dump) {
@@ -105,7 +115,8 @@ class TestCase extends \PHPUnit_Framework_TestCase {
$this->assertSame(Modifier::strip($result), Modifier::strip($tpl->fetch($vars), true), "Test $code"); $this->assertSame(Modifier::strip($result), Modifier::strip($tpl->fetch($vars), true), "Test $code");
} }
public function execTpl($name, $code, $vars, $result, $dump = false) { public function execTpl($name, $code, $vars, $result, $dump = false)
{
$this->tpl($name, $code); $this->tpl($name, $code);
$tpl = $this->fenom->getTemplate($name); $tpl = $this->fenom->getTemplate($name);
if ($dump) { if ($dump) {
@@ -121,7 +132,8 @@ class TestCase extends \PHPUnit_Framework_TestCase {
* @param string $message exception message * @param string $message exception message
* @param int $options Fenom's options * @param int $options Fenom's options
*/ */
public function execError($code, $exception, $message, $options = 0) { public function execError($code, $exception, $message, $options = 0)
{
$opt = $this->fenom->getOptions(); $opt = $this->fenom->getOptions();
$this->fenom->setOptions($options); $this->fenom->setOptions($options);
try { try {
@@ -136,7 +148,8 @@ class TestCase extends \PHPUnit_Framework_TestCase {
$this->fail("Code $code must be invalid"); $this->fail("Code $code must be invalid");
} }
public function assertRender($tpl, $result, $debug = false) { public function assertRender($tpl, $result, $debug = false)
{
$template = $this->fenom->compileCode($tpl); $template = $this->fenom->compileCode($tpl);
if ($debug) { if ($debug) {
print_r("$tpl:\n" . $template->getBody()); print_r("$tpl:\n" . $template->getBody());
@@ -145,7 +158,8 @@ class TestCase extends \PHPUnit_Framework_TestCase {
} }
public static function providerNumbers() { public static function providerNumbers()
{
return array( return array(
array('0', 0), array('0', 0),
array('77', 77), array('77', 77),
@@ -157,7 +171,8 @@ class TestCase extends \PHPUnit_Framework_TestCase {
); );
} }
public static function providerStrings() { public static function providerStrings()
{
return array( return array(
array('"str"', 'str'), array('"str"', 'str'),
array('"str\nand\nmany\nlines"', "str\nand\nmany\nlines"), array('"str\nand\nmany\nlines"', "str\nand\nmany\nlines"),
@@ -187,15 +202,18 @@ class TestCase extends \PHPUnit_Framework_TestCase {
); );
} }
public function providerVariables() { public function providerVariables()
{
return array(); return array();
} }
public static function providerObjects() { public static function providerObjects()
{
return array(); return array();
} }
public static function providerArrays() { public static function providerArrays()
{
$scalars = array(); $scalars = array();
$data = array( $data = array(
array('[]', array()), array('[]', array()),
@@ -221,14 +239,16 @@ class TestCase extends \PHPUnit_Framework_TestCase {
return $data; return $data;
} }
public static function providerScalars() { public static function providerScalars()
{
return array_merge( return array_merge(
self::providerNumbers(), self::providerNumbers(),
self::providerStrings() self::providerStrings()
); );
} }
public static function providerValues() { public static function providerValues()
{
return array_merge( return array_merge(
self::providerScalars(), self::providerScalars(),
self::providerArrays(), self::providerArrays(),
@@ -238,14 +258,17 @@ class TestCase extends \PHPUnit_Framework_TestCase {
} }
} }
class Fake implements \ArrayAccess { class Fake implements \ArrayAccess
{
public $vars; public $vars;
public function offsetExists($offset) { public function offsetExists($offset)
{
return true; return true;
} }
public function offsetGet($offset) { public function offsetGet($offset)
{
if ($offset == "object") { if ($offset == "object") {
return new self(); return new self();
} else { } else {
@@ -253,15 +276,18 @@ class Fake implements \ArrayAccess {
} }
} }
public function offsetSet($offset, $value) { public function offsetSet($offset, $value)
{
$this->vars[$offset] = $value; $this->vars[$offset] = $value;
} }
public function offsetUnset($offset) { public function offsetUnset($offset)
{
unset($this->vars[$offset]); unset($this->vars[$offset]);
} }
public function proxy() { public function proxy()
{
return implode(", ", func_get_args()); return implode(", ", func_get_args());
} }
} }

View File

@@ -3,7 +3,6 @@
require_once __DIR__ . "/../vendor/autoload.php"; require_once __DIR__ . "/../vendor/autoload.php";
define('FENOM_RESOURCES', __DIR__ . "/resources"); define('FENOM_RESOURCES', __DIR__ . "/resources");
require_once FENOM_RESOURCES . "/actions.php"; require_once FENOM_RESOURCES . "/actions.php";
@@ -11,14 +10,16 @@ require_once __DIR__."/TestCase.php";
ini_set('date.timezone', 'Europe/Moscow'); ini_set('date.timezone', 'Europe/Moscow');
function drop() { function drop()
{
call_user_func_array("var_dump", func_get_args()); call_user_func_array("var_dump", func_get_args());
$e = new Exception(); $e = new Exception();
echo "-------\nDump trace: \n" . $e->getTraceAsString() . "\n"; echo "-------\nDump trace: \n" . $e->getTraceAsString() . "\n";
exit(); exit();
} }
function dump() { function dump()
{
foreach (func_get_args() as $arg) { foreach (func_get_args() as $arg) {
fwrite(STDERR, "DUMP: " . call_user_func("print_r", $arg, true) . "\n"); fwrite(STDERR, "DUMP: " . call_user_func("print_r", $arg, true) . "\n");

View File

@@ -3,9 +3,11 @@
namespace Fenom; namespace Fenom;
class AutoEscapeTest extends TestCase { class AutoEscapeTest extends TestCase
{
public static function providerHTML() { public static function providerHTML()
{
$html = "<script>alert('injection');</script>"; $html = "<script>alert('injection');</script>";
$escaped = htmlspecialchars($html, ENT_COMPAT, 'UTF-8'); $escaped = htmlspecialchars($html, ENT_COMPAT, 'UTF-8');
$vars = array( $vars = array(
@@ -56,7 +58,8 @@ class AutoEscapeTest extends TestCase {
/** /**
* @dataProvider providerHTML * @dataProvider providerHTML
*/ */
public function testEscaping($tpl, $result, $vars, $options) { public function testEscaping($tpl, $result, $vars, $options)
{
$this->values = $vars; $this->values = $vars;
$this->fenom->setOptions($options); $this->fenom->setOptions($options);
$this->assertRender($tpl, $result); $this->assertRender($tpl, $result);

View File

@@ -3,25 +3,29 @@
namespace Fenom; namespace Fenom;
class CommentTest extends TestCase { class CommentTest extends TestCase
{
/** /**
* @dataProvider providerScalars * @dataProvider providerScalars
*/ */
public function testInline($tpl_val) { public function testInline($tpl_val)
{
$this->assertRender("before {* $tpl_val *} after", "before after"); $this->assertRender("before {* $tpl_val *} after", "before after");
$this->assertRender("before {* {{$tpl_val}} {{$tpl_val}} *} after", "before after"); $this->assertRender("before {* {{$tpl_val}} {{$tpl_val}} *} after", "before after");
$this->assertRender("before {*{{$tpl_val}}*} after", "before after"); $this->assertRender("before {*{{$tpl_val}}*} after", "before after");
} }
public function testError() { public function testError()
{
$this->execError('{* ', 'Fenom\CompileException', "Unclosed comment block in line"); $this->execError('{* ', 'Fenom\CompileException', "Unclosed comment block in line");
} }
/** /**
* @dataProvider providerScalars * @dataProvider providerScalars
*/ */
public function testMultiLine($tpl_val) { public function testMultiLine($tpl_val)
{
$this->assertRender( $this->assertRender(
"before-1\nbefore-2 {* before-3\nbefore-4 $tpl_val after-1\nafter-2 *} after-3\nafter-4{* dummy *}\nafter-5", "before-1\nbefore-2 {* before-3\nbefore-4 $tpl_val after-1\nafter-2 *} after-3\nafter-4{* dummy *}\nafter-5",
"before-1\nbefore-2 after-3\nafter-4\nafter-5" "before-1\nbefore-2 after-3\nafter-4\nafter-5"

View File

@@ -3,14 +3,17 @@
namespace Fenom; namespace Fenom;
class CustomProviderTest extends TestCase { class CustomProviderTest extends TestCase
{
public function setUp() { public function setUp()
{
parent::setUp(); parent::setUp();
$this->fenom->addProvider("my", new Provider(FENOM_RESOURCES . '/provider')); $this->fenom->addProvider("my", new Provider(FENOM_RESOURCES . '/provider'));
} }
public function testCustom() { public function testCustom()
{
$this->assertRender("start: {include 'my:include.tpl'}", 'start: include template'); $this->assertRender("start: {include 'my:include.tpl'}", 'start: include template');
//$this->assertRender("start: {import 'my:macros.tpl' as ops} {ops.add a=3 b=6}"); //$this->assertRender("start: {import 'my:macros.tpl' as ops} {ops.add a=3 b=6}");
} }

View File

@@ -2,9 +2,11 @@
namespace Fenom; namespace Fenom;
use Fenom, Fenom\TestCase; use Fenom, Fenom\TestCase;
class ExtendsTemplateTest extends TestCase { class ExtendsTemplateTest extends TestCase
{
public function _testSandbox() { public function _testSandbox()
{
$this->fenom = Fenom::factory(FENOM_RESOURCES . '/provider', FENOM_RESOURCES . '/compile'); $this->fenom = Fenom::factory(FENOM_RESOURCES . '/provider', FENOM_RESOURCES . '/compile');
try { try {
print_r($this->fenom->getTemplate('use/child.tpl')->getBody()); print_r($this->fenom->getTemplate('use/child.tpl')->getBody());
@@ -19,7 +21,8 @@ class ExtendsTemplateTest extends TestCase {
* @param array $vars * @param array $vars
* @return array * @return array
*/ */
public static function templates(array $vars) { public static function templates(array $vars)
{
return array( return array(
array( array(
"name" => "level.0.tpl", "name" => "level.0.tpl",
@@ -82,7 +85,8 @@ class ExtendsTemplateTest extends TestCase {
* @param array $skels * @param array $skels
* @return array * @return array
*/ */
public static function generate($block_mask, $extend_mask, $skels) { public static function generate($block_mask, $extend_mask, $skels)
{
$t = array(); $t = array();
foreach ($skels as $level => $tpl) { foreach ($skels as $level => $tpl) {
$src = 'level#' . $level . ' '; $src = 'level#' . $level . ' ';
@@ -102,7 +106,8 @@ class ExtendsTemplateTest extends TestCase {
return $t; return $t;
} }
public function _testTemplateExtends() { public function _testTemplateExtends()
{
$vars = array( $vars = array(
"b1" => "b1", "b1" => "b1",
"b2" => "b2", "b2" => "b2",
@@ -138,12 +143,14 @@ class ExtendsTemplateTest extends TestCase {
/** /**
* @group use * @group use
*/ */
public function testUse() { public function testUse()
{
$this->fenom = Fenom::factory(FENOM_RESOURCES . '/provider', FENOM_RESOURCES . '/compile'); $this->fenom = Fenom::factory(FENOM_RESOURCES . '/provider', FENOM_RESOURCES . '/compile');
$this->assertSame("<html>\n block 1 blocks \n block 2 child \n</html>", $this->fenom->fetch('use/child.tpl')); $this->assertSame("<html>\n block 1 blocks \n block 2 child \n</html>", $this->fenom->fetch('use/child.tpl'));
} }
public function _testParent() { public function _testParent()
{
} }
} }

View File

@@ -1,23 +1,28 @@
<?php <?php
namespace Fenom; namespace Fenom;
class FunctionsTest extends TestCase { class FunctionsTest extends TestCase
{
const FUNCTION_ARGUMENT_CONSTANT = 1; const FUNCTION_ARGUMENT_CONSTANT = 1;
public static function functionSum($of = array()) { public static function functionSum($of = array())
{
return array_sum($of); return array_sum($of);
} }
public static function functionPow($a, $n = 2) { public static function functionPow($a, $n = 2)
{
return pow($a, $n); return pow($a, $n);
} }
public static function functionInc($a, $i = self::FUNCTION_ARGUMENT_CONSTANT) { public static function functionInc($a, $i = self::FUNCTION_ARGUMENT_CONSTANT)
{
return $a + $i; return $a + $i;
} }
public function setUp() { public function setUp()
{
parent::setUp(); parent::setUp();
$this->fenom->addFunctionSmart('sum', __CLASS__ . '::functionSum'); $this->fenom->addFunctionSmart('sum', __CLASS__ . '::functionSum');
$this->fenom->addFunctionSmart('pow', __CLASS__ . '::functionPow'); $this->fenom->addFunctionSmart('pow', __CLASS__ . '::functionPow');
@@ -32,37 +37,44 @@ class FunctionsTest extends TestCase {
$this->tpl('function_array_param_pos.tpl', '{sum [1, 2, 3, 4, 5]}'); $this->tpl('function_array_param_pos.tpl', '{sum [1, 2, 3, 4, 5]}');
} }
public function testFunctionWithParams() { public function testFunctionWithParams()
{
$output = $this->fenom->fetch('function_params_scalar.tpl'); $output = $this->fenom->fetch('function_params_scalar.tpl');
$this->assertEquals('8', $output); $this->assertEquals('8', $output);
} }
public function testFunctionWithDynamicParams() { public function testFunctionWithDynamicParams()
{
$output = $this->fenom->fetch('function_params_dynamic.tpl', array('a' => 3, 'n' => 4)); $output = $this->fenom->fetch('function_params_dynamic.tpl', array('a' => 3, 'n' => 4));
$this->assertEquals('81', $output); $this->assertEquals('81', $output);
} }
public function testFunctionWithDefaultParamScalar() { public function testFunctionWithDefaultParamScalar()
{
$output = $this->fenom->fetch('function_default_param_scalar.tpl'); $output = $this->fenom->fetch('function_default_param_scalar.tpl');
$this->assertEquals('4', $output); $this->assertEquals('4', $output);
} }
public function testFunctionWithDefaultParamArray() { public function testFunctionWithDefaultParamArray()
{
$output = $this->fenom->fetch('function_default_param_empty_array.tpl'); $output = $this->fenom->fetch('function_default_param_empty_array.tpl');
$this->assertEquals('0', $output); $this->assertEquals('0', $output);
} }
public function testFunctionWithDefaultParamConst() { public function testFunctionWithDefaultParamConst()
{
$output = $this->fenom->fetch('function_default_param_const.tpl'); $output = $this->fenom->fetch('function_default_param_const.tpl');
$this->assertEquals('2', $output); $this->assertEquals('2', $output);
} }
public function testFunctionWithArrayNamedParam() { public function testFunctionWithArrayNamedParam()
{
$output = $this->fenom->fetch('function_array_param.tpl'); $output = $this->fenom->fetch('function_array_param.tpl');
$this->assertEquals('15', $output); $this->assertEquals('15', $output);
} }
public function testFunctionWithArrayPositionalParam() { public function testFunctionWithArrayPositionalParam()
{
$output = $this->fenom->fetch('function_array_param_pos.tpl'); $output = $this->fenom->fetch('function_array_param_pos.tpl');
$this->assertEquals('15', $output); $this->assertEquals('15', $output);
} }

View File

@@ -1,9 +1,11 @@
<?php <?php
namespace Fenom; namespace Fenom;
class MacrosTest extends TestCase { class MacrosTest extends TestCase
{
public function setUp() { public function setUp()
{
parent::setUp(); parent::setUp();
$this->tpl("math.tpl", ' $this->tpl("math.tpl", '
{macro plus(x, y)} {macro plus(x, y)}
@@ -52,7 +54,8 @@ class MacrosTest extends TestCase {
{macro.factorial num=10}'); {macro.factorial num=10}');
} }
public function _testSandbox() { public function _testSandbox()
{
try { try {
$this->fenom->compile("macro_recursive.tpl"); $this->fenom->compile("macro_recursive.tpl");
$this->fenom->flush(); $this->fenom->flush();
@@ -63,20 +66,23 @@ class MacrosTest extends TestCase {
exit; exit;
} }
public function testMacros() { public function testMacros()
{
$tpl = $this->fenom->compile('math.tpl'); $tpl = $this->fenom->compile('math.tpl');
$this->assertStringStartsWith('x + y = ', trim($tpl->macros["plus"]["body"])); $this->assertStringStartsWith('x + y = ', trim($tpl->macros["plus"]["body"]));
$this->assertSame('Math: x + y = 5 , x - y - z = 6', Modifier::strip($tpl->fetch(array()), true)); $this->assertSame('Math: x + y = 5 , x - y - z = 6', Modifier::strip($tpl->fetch(array()), true));
} }
public function testImport() { public function testImport()
{
$tpl = $this->fenom->compile('import.tpl'); $tpl = $this->fenom->compile('import.tpl');
$this->assertSame('Imp: x + y = 3 , x - y - z = 3', Modifier::strip($tpl->fetch(array()), true)); $this->assertSame('Imp: x + y = 3 , x - y - z = 3', Modifier::strip($tpl->fetch(array()), true));
} }
public function testImportCustom() { public function testImportCustom()
{
$tpl = $this->fenom->compile('import_custom.tpl'); $tpl = $this->fenom->compile('import_custom.tpl');
$this->assertSame('a: x + y = 3 , x - y - z = 3 , new minus macros .', Modifier::strip($tpl->fetch(array()), true)); $this->assertSame('a: x + y = 3 , x - y - z = 3 , new minus macros .', Modifier::strip($tpl->fetch(array()), true));
@@ -86,13 +92,15 @@ class MacrosTest extends TestCase {
* @expectedExceptionMessage Undefined macro 'plus' * @expectedExceptionMessage Undefined macro 'plus'
* @expectedException \Fenom\CompileException * @expectedException \Fenom\CompileException
*/ */
public function testImportMiss() { public function testImportMiss()
{
$tpl = $this->fenom->compile('import_miss.tpl'); $tpl = $this->fenom->compile('import_miss.tpl');
$this->assertSame('a: x + y = 3 , x - y - z = 3 , new minus macros .', Modifier::strip($tpl->fetch(array()), true)); $this->assertSame('a: x + y = 3 , x - y - z = 3 , new minus macros .', Modifier::strip($tpl->fetch(array()), true));
} }
public function testRecursive() { public function testRecursive()
{
$this->fenom->compile('macro_recursive.tpl'); $this->fenom->compile('macro_recursive.tpl');
$this->fenom->flush(); $this->fenom->flush();
$tpl = $this->fenom->getTemplate('macro_recursive.tpl'); $tpl = $this->fenom->getTemplate('macro_recursive.tpl');

View File

@@ -2,9 +2,11 @@
namespace Fenom; namespace Fenom;
class ModifiersTest extends TestCase { class ModifiersTest extends TestCase
{
public static function providerTruncate() { public static function providerTruncate()
{
$lorem = 'Lorem ipsum dolor sit amet'; // en $lorem = 'Lorem ipsum dolor sit amet'; // en
$uni = 'Лорем ипсум долор сит амет'; // ru $uni = 'Лорем ипсум долор сит амет'; // ru
return array( return array(
@@ -33,7 +35,8 @@ class ModifiersTest extends TestCase {
* @param bool $by_words * @param bool $by_words
* @param bool $middle * @param bool $middle
*/ */
public function testTruncate($in, $out, $count, $delim = '...', $by_words = false, $middle = false) { public function testTruncate($in, $out, $count, $delim = '...', $by_words = false, $middle = false)
{
$tpl = $this->fenom->compileCode('{$text|truncate:$count:$delim:$by_words:$middle}'); $tpl = $this->fenom->compileCode('{$text|truncate:$count:$delim:$by_words:$middle}');
$this->assertEquals($out, $tpl->fetch(array( $this->assertEquals($out, $tpl->fetch(array(
"text" => $in, "text" => $in,
@@ -44,7 +47,8 @@ class ModifiersTest extends TestCase {
))); )));
} }
public static function providerUpLow() { public static function providerUpLow()
{
return array( return array(
array("up", "lorem", "LOREM"), array("up", "lorem", "LOREM"),
array("up", "Lorem", "LOREM"), array("up", "Lorem", "LOREM"),
@@ -64,14 +68,16 @@ class ModifiersTest extends TestCase {
* @param $in * @param $in
* @param $out * @param $out
*/ */
public function testUpLow($modifier, $in, $out) { public function testUpLow($modifier, $in, $out)
{
$tpl = $this->fenom->compileCode('{$text|' . $modifier . '}'); $tpl = $this->fenom->compileCode('{$text|' . $modifier . '}');
$this->assertEquals($out, $tpl->fetch(array( $this->assertEquals($out, $tpl->fetch(array(
"text" => $in, "text" => $in,
))); )));
} }
public static function providerLength() { public static function providerLength()
{
return array( return array(
array("length", 6), array("length", 6),
array("длина", 5), array("длина", 5),
@@ -90,7 +96,8 @@ class ModifiersTest extends TestCase {
* @param $in * @param $in
* @param $out * @param $out
*/ */
public function testLength($in, $out) { public function testLength($in, $out)
{
$tpl = $this->fenom->compileCode('{$data|length}'); $tpl = $this->fenom->compileCode('{$data|length}');
$this->assertEquals($out, $tpl->fetch(array( $this->assertEquals($out, $tpl->fetch(array(
"data" => $in, "data" => $in,

View File

@@ -3,13 +3,15 @@ namespace Fenom;
use Fenom; use Fenom;
use Fenom\TestCase; use Fenom\TestCase;
class ProviderTest extends TestCase { class ProviderTest extends TestCase
{
/** /**
* @var Provider * @var Provider
*/ */
public $provider; public $provider;
public function setUp() { public function setUp()
{
parent::setUp(); parent::setUp();
$this->tpl("template1.tpl", 'Template 1 {$a}'); $this->tpl("template1.tpl", 'Template 1 {$a}');
$this->tpl("template2.tpl", 'Template 2 {$a}'); $this->tpl("template2.tpl", 'Template 2 {$a}');
@@ -18,13 +20,15 @@ class ProviderTest extends TestCase {
clearstatcache(); clearstatcache();
} }
public function testIsTemplateExists() { public function testIsTemplateExists()
{
clearstatcache(); clearstatcache();
$this->assertTrue($this->provider->templateExists("template1.tpl")); $this->assertTrue($this->provider->templateExists("template1.tpl"));
$this->assertFalse($this->provider->templateExists("unexists.tpl")); $this->assertFalse($this->provider->templateExists("unexists.tpl"));
} }
public function testGetSource() { public function testGetSource()
{
clearstatcache(); clearstatcache();
$src = $this->provider->getSource("template1.tpl", $time); $src = $this->provider->getSource("template1.tpl", $time);
clearstatcache(); clearstatcache();
@@ -35,11 +39,13 @@ class ProviderTest extends TestCase {
/** /**
* @expectedException \RuntimeException * @expectedException \RuntimeException
*/ */
public function testGetSourceInvalid() { public function testGetSourceInvalid()
{
$this->provider->getSource("unexists.tpl", $time); $this->provider->getSource("unexists.tpl", $time);
} }
public function testGetLastModified() { public function testGetLastModified()
{
$time = $this->provider->getLastModified("template1.tpl"); $time = $this->provider->getLastModified("template1.tpl");
clearstatcache(); clearstatcache();
$this->assertEquals(filemtime(FENOM_RESOURCES . '/template/template1.tpl'), $time); $this->assertEquals(filemtime(FENOM_RESOURCES . '/template/template1.tpl'), $time);
@@ -48,11 +54,13 @@ class ProviderTest extends TestCase {
/** /**
* @expectedException \RuntimeException * @expectedException \RuntimeException
*/ */
public function testGetLastModifiedInvalid() { public function testGetLastModifiedInvalid()
{
$this->provider->getLastModified("unexists.tpl"); $this->provider->getLastModified("unexists.tpl");
} }
public function testVerify() { public function testVerify()
{
$templates = array( $templates = array(
"template1.tpl" => filemtime(FENOM_RESOURCES . '/template/template1.tpl'), "template1.tpl" => filemtime(FENOM_RESOURCES . '/template/template1.tpl'),
"template2.tpl" => filemtime(FENOM_RESOURCES . '/template/template2.tpl') "template2.tpl" => filemtime(FENOM_RESOURCES . '/template/template2.tpl')
@@ -68,7 +76,8 @@ class ProviderTest extends TestCase {
$this->assertTrue($this->provider->verify($templates)); $this->assertTrue($this->provider->verify($templates));
} }
public function testVerifyInvalid() { public function testVerifyInvalid()
{
$templates = array( $templates = array(
"template1.tpl" => filemtime(FENOM_RESOURCES . '/template/template1.tpl'), "template1.tpl" => filemtime(FENOM_RESOURCES . '/template/template1.tpl'),
"template2.tpl" => filemtime(FENOM_RESOURCES . '/template/template2.tpl') + 1 "template2.tpl" => filemtime(FENOM_RESOURCES . '/template/template2.tpl') + 1
@@ -83,7 +92,8 @@ class ProviderTest extends TestCase {
$this->assertFalse($this->provider->verify($templates)); $this->assertFalse($this->provider->verify($templates));
} }
public function testGetAll() { public function testGetAll()
{
$list = $this->provider->getList(); $list = $this->provider->getList();
sort($list); sort($list);
$this->assertSame(array( $this->assertSame(array(

View File

@@ -3,14 +3,16 @@ namespace Fenom;
use Fenom, use Fenom,
Fenom\Render; Fenom\Render;
class RenderTest extends \PHPUnit_Framework_TestCase { class RenderTest extends \PHPUnit_Framework_TestCase
{
/** /**
* @var Render * @var Render
*/ */
public static $render; public static $render;
public static function setUpBeforeClass() { public static function setUpBeforeClass()
{
self::$render = new Render(Fenom::factory("."), function ($tpl) { self::$render = new Render(Fenom::factory("."), function ($tpl) {
echo "It is render's function " . $tpl["render"]; echo "It is render's function " . $tpl["render"];
}, array( }, array(
@@ -18,7 +20,8 @@ class RenderTest extends \PHPUnit_Framework_TestCase {
)); ));
} }
public function testCreate() { public function testCreate()
{
$r = new Render(Fenom::factory("."), function () { $r = new Render(Fenom::factory("."), function () {
echo "Test render"; echo "Test render";
}, array( }, array(
@@ -27,14 +30,16 @@ class RenderTest extends \PHPUnit_Framework_TestCase {
$this->assertSame("Test render", $r->fetch(array())); $this->assertSame("Test render", $r->fetch(array()));
} }
public function testDisplay() { public function testDisplay()
{
ob_start(); ob_start();
self::$render->display(array("render" => "display")); self::$render->display(array("render" => "display"));
$out = ob_get_clean(); $out = ob_get_clean();
$this->assertSame("It is render's function display", $out); $this->assertSame("It is render's function display", $out);
} }
public function testFetch() { public function testFetch()
{
$this->assertSame("It is render's function fetch", self::$render->fetch(array("render" => "fetch"))); $this->assertSame("It is render's function fetch", self::$render->fetch(array("render" => "fetch")));
} }
@@ -42,7 +47,8 @@ class RenderTest extends \PHPUnit_Framework_TestCase {
* @expectedException \RuntimeException * @expectedException \RuntimeException
* @expectedExceptionMessage template error * @expectedExceptionMessage template error
*/ */
public function testFetchException() { public function testFetchException()
{
$render = new Render(Fenom::factory("."), function () { $render = new Render(Fenom::factory("."), function () {
echo "error"; echo "error";
throw new \RuntimeException("template error"); throw new \RuntimeException("template error");

View File

@@ -1,22 +1,26 @@
<?php <?php
namespace Fenom; namespace Fenom;
class ScopeTest extends TestCase { class ScopeTest extends TestCase
public function openTag($tokenizer, $scope) { {
public function openTag($tokenizer, $scope)
{
$this->assertInstanceOf('Fenom\Tokenizer', $tokenizer); $this->assertInstanceOf('Fenom\Tokenizer', $tokenizer);
$this->assertInstanceOf('Fenom\Scope', $scope); $this->assertInstanceOf('Fenom\Scope', $scope);
$scope["value"] = true; $scope["value"] = true;
return "open-tag"; return "open-tag";
} }
public function closeTag($tokenizer, $scope) { public function closeTag($tokenizer, $scope)
{
$this->assertInstanceOf('Fenom\Tokenizer', $tokenizer); $this->assertInstanceOf('Fenom\Tokenizer', $tokenizer);
$this->assertInstanceOf('Fenom\Scope', $scope); $this->assertInstanceOf('Fenom\Scope', $scope);
$this->assertTrue($scope["value"]); $this->assertTrue($scope["value"]);
return "close-tag"; return "close-tag";
} }
public function testBlock() { public function testBlock()
{
/*$scope = new Scope($this->fenom, new Template($this->fenom), 1, array( /*$scope = new Scope($this->fenom, new Template($this->fenom), 1, array(
"open" => array($this, "openTag"), "open" => array($this, "openTag"),
"close" => array($this, "closeTag") "close" => array($this, "closeTag")

View File

@@ -3,9 +3,11 @@
namespace Fenom; namespace Fenom;
class TagsTest extends TestCase { class TagsTest extends TestCase
{
public function _testSandbox() { public function _testSandbox()
{
try { try {
var_dump($this->fenom->compileCode('{var $a=Fenom\TestCase::dots("asd")}')->getBody()); var_dump($this->fenom->compileCode('{var $a=Fenom\TestCase::dots("asd")}')->getBody());
} catch (\Exception $e) { } catch (\Exception $e) {
@@ -17,39 +19,45 @@ class TagsTest extends TestCase {
/** /**
* @dataProvider providerScalars * @dataProvider providerScalars
*/ */
public function testVar($tpl_val, $val) { public function testVar($tpl_val, $val)
{
$this->assertRender("{var \$a=$tpl_val}\nVar: {\$a}", "\nVar: " . $val); $this->assertRender("{var \$a=$tpl_val}\nVar: {\$a}", "\nVar: " . $val);
} }
/** /**
* @dataProvider providerScalars * @dataProvider providerScalars
*/ */
public function testVarBlock($tpl_val, $val) { public function testVarBlock($tpl_val, $val)
{
$this->assertRender("{var \$a}before {{$tpl_val}} after{/var}\nVar: {\$a}", "\nVar: before " . $val . " after"); $this->assertRender("{var \$a}before {{$tpl_val}} after{/var}\nVar: {\$a}", "\nVar: before " . $val . " after");
} }
/** /**
* @dataProvider providerScalars * @dataProvider providerScalars
*/ */
public function testVarBlockModified($tpl_val, $val) { public function testVarBlockModified($tpl_val, $val)
{
$this->assertRender("{var \$a|low|dots}before {{$tpl_val}} after{/var}\nVar: {\$a}", "\nVar: " . strtolower("before " . $val . " after") . "..."); $this->assertRender("{var \$a|low|dots}before {{$tpl_val}} after{/var}\nVar: {\$a}", "\nVar: " . strtolower("before " . $val . " after") . "...");
} }
public function testCycle() { public function testCycle()
{
$this->assertRender('{for $i=0 to=4}{cycle ["one", "two"]}, {/for}', "one, two, one, two, one, "); $this->assertRender('{for $i=0 to=4}{cycle ["one", "two"]}, {/for}', "one, two, one, two, one, ");
} }
/** /**
* *
*/ */
public function testCycleIndex() { public function testCycleIndex()
{
$this->assertRender('{var $a=["one", "two"]}{for $i=1 to=5}{cycle $a index=$i}, {/for}', "two, one, two, one, two, "); $this->assertRender('{var $a=["one", "two"]}{for $i=1 to=5}{cycle $a index=$i}, {/for}', "two, one, two, one, two, ");
} }
/** /**
* @dataProvider providerScalars * @dataProvider providerScalars
*/ */
public function testFilter($tpl_val, $val) { public function testFilter($tpl_val, $val)
{
$this->assertRender("{filter|up} before {{$tpl_val}} after {/filter}", strtoupper(" before {$val} after ")); $this->assertRender("{filter|up} before {{$tpl_val}} after {/filter}", strtoupper(" before {$val} after "));
} }

View File

@@ -9,14 +9,17 @@ use Fenom\Template,
* *
* @package Fenom * @package Fenom
*/ */
class TemplateTest extends TestCase { class TemplateTest extends TestCase
{
public function setUp() { public function setUp()
{
parent::setUp(); parent::setUp();
$this->tpl('welcome.tpl', '<b>Welcome, {$username} ({$email})</b>'); $this->tpl('welcome.tpl', '<b>Welcome, {$username} ({$email})</b>');
} }
public static function providerVars() { public static function providerVars()
{
$a = array("a" => "World"); $a = array("a" => "World");
$obj = new \stdClass; $obj = new \stdClass;
$obj->name = "Object"; $obj->name = "Object";
@@ -75,7 +78,8 @@ class TemplateTest extends TestCase {
} }
public static function providerVarsInvalid() { public static function providerVarsInvalid()
{
return array( return array(
array('hello, {$a.}!', 'Fenom\CompileException', "Unexpected end of expression"), array('hello, {$a.}!', 'Fenom\CompileException', "Unexpected end of expression"),
array('hello, {$b[c}!', 'Fenom\CompileException', "Unexpected end of expression"), array('hello, {$b[c}!', 'Fenom\CompileException', "Unexpected end of expression"),
@@ -88,7 +92,8 @@ class TemplateTest extends TestCase {
); );
} }
public static function providerModifiers() { public static function providerModifiers()
{
$b = array( $b = array(
"a" => "World", "a" => "World",
"b" => array( "b" => array(
@@ -127,7 +132,8 @@ class TemplateTest extends TestCase {
); );
} }
public static function providerModifiersInvalid() { public static function providerModifiersInvalid()
{
return array( return array(
array('Mod: {$lorem|}!', 'Fenom\CompileException', "Unexpected end of expression"), array('Mod: {$lorem|}!', 'Fenom\CompileException', "Unexpected end of expression"),
array('Mod: {$lorem|str_rot13}!', 'Fenom\CompileException', "Modifier str_rot13 not found", Fenom::DENY_INLINE_FUNCS), array('Mod: {$lorem|str_rot13}!', 'Fenom\CompileException', "Modifier str_rot13 not found", Fenom::DENY_INLINE_FUNCS),
@@ -138,7 +144,8 @@ class TemplateTest extends TestCase {
); );
} }
public static function providerExpressions() { public static function providerExpressions()
{
$b = array( $b = array(
"x" => $x = 9, "x" => $x = 9,
"y" => 27, "y" => 27,
@@ -175,7 +182,8 @@ class TemplateTest extends TestCase {
); );
} }
public static function providerExpressionsInvalid() { public static function providerExpressionsInvalid()
{
return array( return array(
array('If: {-"hi"} end', 'Fenom\CompileException', "Unexpected token '-'"), array('If: {-"hi"} end', 'Fenom\CompileException', "Unexpected token '-'"),
array('If: {($a++)++} end', 'Fenom\CompileException', "Unexpected token '++'"), array('If: {($a++)++} end', 'Fenom\CompileException', "Unexpected token '++'"),
@@ -193,7 +201,8 @@ class TemplateTest extends TestCase {
); );
} }
public static function providerInclude() { public static function providerInclude()
{
$a = array( $a = array(
"name" => "welcome", "name" => "welcome",
"tpl" => "welcome.tpl", "tpl" => "welcome.tpl",
@@ -224,14 +233,16 @@ class TemplateTest extends TestCase {
); );
} }
public static function providerIncludeInvalid() { public static function providerIncludeInvalid()
{
return array( return array(
array('Include {include} template', 'Fenom\CompileException', "Unexpected end of expression"), array('Include {include} template', 'Fenom\CompileException', "Unexpected end of expression"),
array('Include {include another="welcome.tpl"} template', 'Fenom\CompileException', "Unexpected token '='"), array('Include {include another="welcome.tpl"} template', 'Fenom\CompileException', "Unexpected token '='"),
); );
} }
public static function providerIf() { public static function providerIf()
{
$a = array( $a = array(
"val1" => 1, "val1" => 1,
"val0" => 0, "val0" => 0,
@@ -268,7 +279,8 @@ class TemplateTest extends TestCase {
); );
} }
public static function providerIfInvalid() { public static function providerIfInvalid()
{
return array( return array(
array('If: {if} block1 {/if} end', 'Fenom\CompileException', "Unexpected end of expression"), array('If: {if} block1 {/if} end', 'Fenom\CompileException', "Unexpected end of expression"),
array('If: {if 1} block1 {elseif} block2 {/if} end', 'Fenom\CompileException', "Unexpected end of expression"), array('If: {if 1} block1 {elseif} block2 {/if} end', 'Fenom\CompileException', "Unexpected end of expression"),
@@ -277,7 +289,8 @@ class TemplateTest extends TestCase {
); );
} }
public static function providerCreateVar() { public static function providerCreateVar()
{
$a = array( $a = array(
"x" => 9, "x" => 9,
"y" => 27, "y" => 27,
@@ -309,7 +322,8 @@ class TemplateTest extends TestCase {
); );
} }
public static function providerCreateVarInvalid() { public static function providerCreateVarInvalid()
{
return array( return array(
array('Create: {var $v} Result: {$v} end', 'Fenom\CompileException', "Unclosed tag: {var} opened"), array('Create: {var $v} Result: {$v} end', 'Fenom\CompileException', "Unclosed tag: {var} opened"),
array('Create: {var $v = } Result: {$v} end', 'Fenom\CompileException', "Unexpected end of expression"), array('Create: {var $v = } Result: {$v} end', 'Fenom\CompileException', "Unexpected end of expression"),
@@ -329,7 +343,8 @@ class TemplateTest extends TestCase {
); );
} }
public static function providerTernary() { public static function providerTernary()
{
$a = array( $a = array(
"a" => 1, "a" => 1,
"em" => "empty", "em" => "empty",
@@ -392,7 +407,8 @@ class TemplateTest extends TestCase {
); );
} }
public static function providerForeach() { public static function providerForeach()
{
$a = array( $a = array(
"list" => array(1 => "one", 2 => "two", 3 => "three"), "list" => array(1 => "one", 2 => "two", 3 => "three"),
"empty" => array() "empty" => array()
@@ -417,7 +433,8 @@ class TemplateTest extends TestCase {
); );
} }
public static function providerForeachInvalid() { public static function providerForeachInvalid()
{
return array( return array(
array('Foreach: {foreach} {$e}, {/foreach} end', 'Fenom\CompileException', "Unexpected end of tag {foreach}"), array('Foreach: {foreach} {$e}, {/foreach} end', 'Fenom\CompileException', "Unexpected end of tag {foreach}"),
array('Foreach: {foreach $list} {$e}, {/foreach} end', 'Fenom\CompileException', "Unexpected end of expression"), array('Foreach: {foreach $list} {$e}, {/foreach} end', 'Fenom\CompileException', "Unexpected end of expression"),
@@ -443,7 +460,8 @@ class TemplateTest extends TestCase {
); );
} }
public static function providerIgnores() { public static function providerIgnores()
{
$a = array("a" => "lit. A"); $a = array("a" => "lit. A");
return array( return array(
array('{if 0}none{/if} literal: {$a} end', $a, 'literal: lit. A end'), array('{if 0}none{/if} literal: {$a} end', $a, 'literal: lit. A end'),
@@ -456,7 +474,8 @@ class TemplateTest extends TestCase {
); );
} }
public static function providerSwitch() { public static function providerSwitch()
{
$code1 = 'Switch: {switch $a} $code1 = 'Switch: {switch $a}
{case 1} one {break} {case 1} one {break}
{case 2} two {break} {case 2} two {break}
@@ -483,7 +502,8 @@ class TemplateTest extends TestCase {
); );
} }
public static function providerSwitchInvalid() { public static function providerSwitchInvalid()
{
return array( return array(
array('Switch: {switch}{case 1} one {break}{/switch} end', 'Fenom\CompileException', "Unexpected end of expression"), array('Switch: {switch}{case 1} one {break}{/switch} end', 'Fenom\CompileException', "Unexpected end of expression"),
array('Switch: {switch 1}{case} one {break}{/switch} end', 'Fenom\CompileException', "Unexpected end of expression"), array('Switch: {switch 1}{case} one {break}{/switch} end', 'Fenom\CompileException', "Unexpected end of expression"),
@@ -491,7 +511,8 @@ class TemplateTest extends TestCase {
); );
} }
public static function providerWhile() { public static function providerWhile()
{
$a = array("a" => 3); $a = array("a" => 3);
return array( return array(
array('While: {while false} block {/while} end', $a, 'While: end'), array('While: {while false} block {/while} end', $a, 'While: end'),
@@ -501,13 +522,15 @@ class TemplateTest extends TestCase {
); );
} }
public static function providerWhileInvalid() { public static function providerWhileInvalid()
{
return array( return array(
array('While: {while} block {/while} end', 'Fenom\CompileException', "Unexpected end of expression"), array('While: {while} block {/while} end', 'Fenom\CompileException', "Unexpected end of expression"),
); );
} }
public static function providerFor() { public static function providerFor()
{
$a = array("c" => 1, "s" => 1, "m" => 3); $a = array("c" => 1, "s" => 1, "m" => 3);
return array( return array(
array('For: {for $a=4 to=6} $a: {$a}, {/for} end', $a, 'For: $a: 4, $a: 5, $a: 6, end'), array('For: {for $a=4 to=6} $a: {$a}, {/for} end', $a, 'For: $a: 4, $a: 5, $a: 6, end'),
@@ -529,7 +552,8 @@ class TemplateTest extends TestCase {
); );
} }
public static function providerForInvalid() { public static function providerForInvalid()
{
return array( return array(
array('For: {for} block1 {/for} end', 'Fenom\CompileException', "Unexpected end of expression"), array('For: {for} block1 {/for} end', 'Fenom\CompileException', "Unexpected end of expression"),
array('For: {for $a=} block1 {/for} end', 'Fenom\CompileException', "Unexpected end of expression"), array('For: {for $a=} block1 {/for} end', 'Fenom\CompileException', "Unexpected end of expression"),
@@ -545,7 +569,8 @@ class TemplateTest extends TestCase {
); );
} }
public static function providerLayersInvalid() { public static function providerLayersInvalid()
{
return array( return array(
array('Layers: {foreach $list as $e} block1 {if 1} {foreachelse} {/if} {/foreach} end', 'Fenom\CompileException', "Unexpected tag 'foreachelse' (this tag can be used with 'foreach')"), array('Layers: {foreach $list as $e} block1 {if 1} {foreachelse} {/if} {/foreach} end', 'Fenom\CompileException', "Unexpected tag 'foreachelse' (this tag can be used with 'foreach')"),
array('Layers: {foreach $list as $e} block1 {if 1} {/foreach} {/if} end', 'Fenom\CompileException', "Unexpected closing of the tag 'foreach'"), array('Layers: {foreach $list as $e} block1 {if 1} {/foreach} {/if} end', 'Fenom\CompileException', "Unexpected closing of the tag 'foreach'"),
@@ -557,7 +582,8 @@ class TemplateTest extends TestCase {
); );
} }
public static function providerExtends() { public static function providerExtends()
{
return array( return array(
array('{extends file="parent.tpl"}{block name="bk1"} block1 {/block}', "Template extended by block1"), array('{extends file="parent.tpl"}{block name="bk1"} block1 {/block}', "Template extended by block1"),
array('{extends "parent.tpl"}{block "bk1"} block1 {/block}', "Template extended by block1"), array('{extends "parent.tpl"}{block "bk1"} block1 {/block}', "Template extended by block1"),
@@ -568,7 +594,8 @@ class TemplateTest extends TestCase {
); );
} }
public static function providerIsOperator() { public static function providerIsOperator()
{
return array( return array(
// is {$type} // is {$type}
array('{if $one is int} block1 {else} block2 {/if}', 'block1'), array('{if $one is int} block1 {else} block2 {/if}', 'block1'),
@@ -624,7 +651,8 @@ class TemplateTest extends TestCase {
); );
} }
public static function providerInOperator() { public static function providerInOperator()
{
return array( return array(
array('{if $one in "qwertyuiop 1"} block1 {else} block2 {/if}', 'block1'), array('{if $one in "qwertyuiop 1"} block1 {else} block2 {/if}', 'block1'),
array('{if $one in string "qwertyuiop 1"} block1 {else} block2 {/if}', 'block1'), array('{if $one in string "qwertyuiop 1"} block1 {else} block2 {/if}', 'block1'),
@@ -641,7 +669,8 @@ class TemplateTest extends TestCase {
); );
} }
public function _testSandbox() { public function _testSandbox()
{
try { try {
var_dump($this->fenom->compileCode('{$one.two->three[e]()}')->getBody()); var_dump($this->fenom->compileCode('{$one.two->three[e]()}')->getBody());
} catch (\Exception $e) { } catch (\Exception $e) {
@@ -653,28 +682,32 @@ class TemplateTest extends TestCase {
/** /**
* @dataProvider providerVars * @dataProvider providerVars
*/ */
public function testVars($code, $vars, $result) { public function testVars($code, $vars, $result)
{
$this->exec($code, $vars, $result); $this->exec($code, $vars, $result);
} }
/** /**
* @dataProvider providerVarsInvalid * @dataProvider providerVarsInvalid
*/ */
public function testVarsInvalid($code, $exception, $message, $options = 0) { public function testVarsInvalid($code, $exception, $message, $options = 0)
{
$this->execError($code, $exception, $message, $options); $this->execError($code, $exception, $message, $options);
} }
/** /**
* @dataProvider providerModifiers * @dataProvider providerModifiers
*/ */
public function testModifiers($code, $vars, $result) { public function testModifiers($code, $vars, $result)
{
$this->exec($code, $vars, $result); $this->exec($code, $vars, $result);
} }
/** /**
* @dataProvider providerModifiersInvalid * @dataProvider providerModifiersInvalid
*/ */
public function testModifiersInvalid($code, $exception, $message, $options = 0) { public function testModifiersInvalid($code, $exception, $message, $options = 0)
{
$this->execError($code, $exception, $message, $options); $this->execError($code, $exception, $message, $options);
} }
@@ -682,14 +715,16 @@ class TemplateTest extends TestCase {
* @group expression * @group expression
* @dataProvider providerExpressions * @dataProvider providerExpressions
*/ */
public function testExpressions($code, $vars, $result) { public function testExpressions($code, $vars, $result)
{
$this->exec($code, $vars, $result); $this->exec($code, $vars, $result);
} }
/** /**
* @dataProvider providerExpressionsInvalid * @dataProvider providerExpressionsInvalid
*/ */
public function testExpressionsInvalid($code, $exception, $message, $options = 0) { public function testExpressionsInvalid($code, $exception, $message, $options = 0)
{
$this->execError($code, $exception, $message, $options); $this->execError($code, $exception, $message, $options);
} }
@@ -697,14 +732,16 @@ class TemplateTest extends TestCase {
* @group include * @group include
* @dataProvider providerInclude * @dataProvider providerInclude
*/ */
public function testInclude($code, $vars, $result) { public function testInclude($code, $vars, $result)
{
$this->exec($code, $vars, $result); $this->exec($code, $vars, $result);
} }
/** /**
* @dataProvider providerIncludeInvalid * @dataProvider providerIncludeInvalid
*/ */
public function testIncludeInvalid($code, $exception, $message, $options = 0) { public function testIncludeInvalid($code, $exception, $message, $options = 0)
{
$this->execError($code, $exception, $message, $options); $this->execError($code, $exception, $message, $options);
} }
@@ -712,28 +749,32 @@ class TemplateTest extends TestCase {
* @dataProvider providerIf * @dataProvider providerIf
* @group test-if * @group test-if
*/ */
public function testIf($code, $vars, $result, $options = 0) { public function testIf($code, $vars, $result, $options = 0)
{
$this->exec($code, $vars, $result, $options); $this->exec($code, $vars, $result, $options);
} }
/** /**
* @dataProvider providerIfInvalid * @dataProvider providerIfInvalid
*/ */
public function testIfInvalid($code, $exception, $message, $options = 0) { public function testIfInvalid($code, $exception, $message, $options = 0)
{
$this->execError($code, $exception, $message, $options); $this->execError($code, $exception, $message, $options);
} }
/** /**
* @dataProvider providerCreateVar * @dataProvider providerCreateVar
*/ */
public function testCreateVar($code, $vars, $result) { public function testCreateVar($code, $vars, $result)
{
$this->exec($code, $vars, $result); $this->exec($code, $vars, $result);
} }
/** /**
* @dataProvider providerCreateVarInvalid * @dataProvider providerCreateVarInvalid
*/ */
public function testCreateVarInvalid($code, $exception, $message, $options = 0) { public function testCreateVarInvalid($code, $exception, $message, $options = 0)
{
$this->execError($code, $exception, $message, $options); $this->execError($code, $exception, $message, $options);
} }
@@ -741,77 +782,88 @@ class TemplateTest extends TestCase {
* @group ternary * @group ternary
* @dataProvider providerTernary * @dataProvider providerTernary
*/ */
public function testTernary($code, $vars, $result = 'right') { public function testTernary($code, $vars, $result = 'right')
{
$this->exec(__FUNCTION__ . ": $code end", $vars, __FUNCTION__ . ": $result end"); $this->exec(__FUNCTION__ . ": $code end", $vars, __FUNCTION__ . ": $result end");
} }
/** /**
* @dataProvider providerForeach * @dataProvider providerForeach
*/ */
public function testForeach($code, $vars, $result) { public function testForeach($code, $vars, $result)
{
$this->exec($code, $vars, $result); $this->exec($code, $vars, $result);
} }
/** /**
* @dataProvider providerForeachInvalid * @dataProvider providerForeachInvalid
*/ */
public function testForeachInvalid($code, $exception, $message, $options = 0) { public function testForeachInvalid($code, $exception, $message, $options = 0)
{
$this->execError($code, $exception, $message, $options); $this->execError($code, $exception, $message, $options);
} }
/** /**
* @dataProvider providerFor * @dataProvider providerFor
*/ */
public function testFor($code, $vars, $result) { public function testFor($code, $vars, $result)
{
$this->exec($code, $vars, $result); $this->exec($code, $vars, $result);
} }
/** /**
* @dataProvider providerForInvalid * @dataProvider providerForInvalid
*/ */
public function testForInvalid($code, $exception, $message, $options = 0) { public function testForInvalid($code, $exception, $message, $options = 0)
{
$this->execError($code, $exception, $message, $options); $this->execError($code, $exception, $message, $options);
} }
/** /**
* @dataProvider providerIgnores * @dataProvider providerIgnores
*/ */
public function testIgnores($code, $vars, $result) { public function testIgnores($code, $vars, $result)
{
$this->exec($code, $vars, $result); $this->exec($code, $vars, $result);
} }
/** /**
* @dataProvider providerSwitch * @dataProvider providerSwitch
*/ */
public function testSwitch($code, $vars, $result) { public function testSwitch($code, $vars, $result)
{
$this->exec($code, $vars, $result); $this->exec($code, $vars, $result);
} }
/** /**
* @dataProvider providerSwitchInvalid * @dataProvider providerSwitchInvalid
*/ */
public function testSwitchInvalid($code, $exception, $message, $options = 0) { public function testSwitchInvalid($code, $exception, $message, $options = 0)
{
$this->execError($code, $exception, $message, $options); $this->execError($code, $exception, $message, $options);
} }
/** /**
* @dataProvider providerWhile * @dataProvider providerWhile
*/ */
public function testWhile($code, $vars, $result) { public function testWhile($code, $vars, $result)
{
$this->exec($code, $vars, $result); $this->exec($code, $vars, $result);
} }
/** /**
* @dataProvider providerWhileInvalid * @dataProvider providerWhileInvalid
*/ */
public function testWhileInvalid($code, $exception, $message, $options = 0) { public function testWhileInvalid($code, $exception, $message, $options = 0)
{
$this->execError($code, $exception, $message, $options); $this->execError($code, $exception, $message, $options);
} }
/** /**
* @dataProvider providerLayersInvalid * @dataProvider providerLayersInvalid
*/ */
public function testLayersInvalid($code, $exception, $message, $options = 0) { public function testLayersInvalid($code, $exception, $message, $options = 0)
{
$this->execError($code, $exception, $message, $options); $this->execError($code, $exception, $message, $options);
} }
@@ -819,7 +871,8 @@ class TemplateTest extends TestCase {
* @group is_operator * @group is_operator
* @dataProvider providerIsOperator * @dataProvider providerIsOperator
*/ */
public function testIsOperator($code, $result) { public function testIsOperator($code, $result)
{
$this->exec($code, self::getVars(), $result); $this->exec($code, self::getVars(), $result);
} }
@@ -827,7 +880,8 @@ class TemplateTest extends TestCase {
* @group in_operator * @group in_operator
* @dataProvider providerInOperator * @dataProvider providerInOperator
*/ */
public function testInOperator($code, $result) { public function testInOperator($code, $result)
{
$this->exec($code, self::getVars(), $result); $this->exec($code, self::getVars(), $result);
} }
} }

View File

@@ -2,9 +2,11 @@
namespace Fenom; namespace Fenom;
use Fenom\Tokenizer; use Fenom\Tokenizer;
class TokenizerTest extends \PHPUnit_Framework_TestCase { class TokenizerTest extends \PHPUnit_Framework_TestCase
{
public function testTokens() { public function testTokens()
{
$code = 'hello, please resolve this example: sin($x)+tan($x*$t) = {U|[0,1]}'; $code = 'hello, please resolve this example: sin($x)+tan($x*$t) = {U|[0,1]}';
$tokens = new Tokenizer($code); $tokens = new Tokenizer($code);
$this->assertSame(T_STRING, $tokens->key()); $this->assertSame(T_STRING, $tokens->key());
@@ -46,7 +48,8 @@ class TokenizerTest extends \PHPUnit_Framework_TestCase {
$this->assertSame("+", $tokens->getNext($tokens::MACRO_BINARY)); $this->assertSame("+", $tokens->getNext($tokens::MACRO_BINARY));
} }
public function testSkip() { public function testSkip()
{
$text = "1 foo: bar ( 3 + double ) "; $text = "1 foo: bar ( 3 + double ) ";
$tokens = new Tokenizer($text); $tokens = new Tokenizer($text);

View File

@@ -3,9 +3,11 @@
use Fenom\Render, use Fenom\Render,
Fenom\Provider as FS; Fenom\Provider as FS;
class FenomTest extends \Fenom\TestCase { class FenomTest extends \Fenom\TestCase
{
public static function providerOptions() { public static function providerOptions()
{
return array( return array(
array("disable_methods", Fenom::DENY_METHODS), array("disable_methods", Fenom::DENY_METHODS),
array("disable_native_funcs", Fenom::DENY_INLINE_FUNCS), array("disable_native_funcs", Fenom::DENY_INLINE_FUNCS),
@@ -18,7 +20,8 @@ class FenomTest extends \Fenom\TestCase {
); );
} }
public function testCompileFile() { public function testCompileFile()
{
$a = array( $a = array(
"a" => "a", "a" => "a",
"b" => "b" "b" => "b"
@@ -32,14 +35,16 @@ class FenomTest extends \Fenom\TestCase {
$this->assertSame(3, iterator_count(new FilesystemIterator(FENOM_RESOURCES . '/compile'))); $this->assertSame(3, iterator_count(new FilesystemIterator(FENOM_RESOURCES . '/compile')));
} }
public function testStorage() { public function testStorage()
{
$this->tpl('custom.tpl', 'Custom template'); $this->tpl('custom.tpl', 'Custom template');
$this->assertSame("Custom template", $this->fenom->fetch('custom.tpl', array())); $this->assertSame("Custom template", $this->fenom->fetch('custom.tpl', array()));
$this->tpl('custom.tpl', 'Custom template 2'); $this->tpl('custom.tpl', 'Custom template 2');
$this->assertSame("Custom template", $this->fenom->fetch('custom.tpl', array())); $this->assertSame("Custom template", $this->fenom->fetch('custom.tpl', array()));
} }
public function testCheckMTime() { public function testCheckMTime()
{
$this->fenom->setOptions(Fenom::FORCE_COMPILE); $this->fenom->setOptions(Fenom::FORCE_COMPILE);
$this->tpl('custom.tpl', 'Custom template'); $this->tpl('custom.tpl', 'Custom template');
$this->assertSame("Custom template", $this->fenom->fetch('custom.tpl', array())); $this->assertSame("Custom template", $this->fenom->fetch('custom.tpl', array()));
@@ -49,7 +54,8 @@ class FenomTest extends \Fenom\TestCase {
$this->assertSame("Custom template (new)", $this->fenom->fetch('custom.tpl', array())); $this->assertSame("Custom template (new)", $this->fenom->fetch('custom.tpl', array()));
} }
public function testForceCompile() { public function testForceCompile()
{
$this->fenom->setOptions(Fenom::FORCE_COMPILE); $this->fenom->setOptions(Fenom::FORCE_COMPILE);
$this->tpl('custom.tpl', 'Custom template'); $this->tpl('custom.tpl', 'Custom template');
$this->assertSame("Custom template", $this->fenom->fetch('custom.tpl', array())); $this->assertSame("Custom template", $this->fenom->fetch('custom.tpl', array()));
@@ -57,7 +63,8 @@ class FenomTest extends \Fenom\TestCase {
$this->assertSame("Custom template (new)", $this->fenom->fetch('custom.tpl', array())); $this->assertSame("Custom template (new)", $this->fenom->fetch('custom.tpl', array()));
} }
public function testSetModifier() { public function testSetModifier()
{
$this->fenom->addModifier("mymod", "myMod"); $this->fenom->addModifier("mymod", "myMod");
$this->tpl('custom.tpl', 'Custom modifier {$a|mymod}'); $this->tpl('custom.tpl', 'Custom modifier {$a|mymod}');
$this->assertSame("Custom modifier (myMod)Custom(/myMod)", $this->fenom->fetch('custom.tpl', array("a" => "Custom"))); $this->assertSame("Custom modifier (myMod)Custom(/myMod)", $this->fenom->fetch('custom.tpl', array("a" => "Custom")));
@@ -66,7 +73,8 @@ class FenomTest extends \Fenom\TestCase {
/** /**
* @group add_functions * @group add_functions
*/ */
public function testSetFunctions() { public function testSetFunctions()
{
$this->fenom->setOptions(Fenom::FORCE_COMPILE); $this->fenom->setOptions(Fenom::FORCE_COMPILE);
$this->fenom->addFunction("myfunc", "myFunc"); $this->fenom->addFunction("myfunc", "myFunc");
$this->fenom->addBlockFunction("myblockfunc", "myBlockFunc"); $this->fenom->addBlockFunction("myblockfunc", "myBlockFunc");
@@ -76,7 +84,8 @@ class FenomTest extends \Fenom\TestCase {
$this->assertSame("Custom function Block:foo:this block1:Block", $this->fenom->fetch('custom.tpl', array())); $this->assertSame("Custom function Block:foo:this block1:Block", $this->fenom->fetch('custom.tpl', array()));
} }
public function testSetCompilers() { public function testSetCompilers()
{
$this->fenom->setOptions(Fenom::FORCE_COMPILE); $this->fenom->setOptions(Fenom::FORCE_COMPILE);
$this->fenom->addCompiler("mycompiler", 'myCompiler'); $this->fenom->addCompiler("mycompiler", 'myCompiler');
$this->fenom->addBlockCompiler("myblockcompiler", 'myBlockCompilerOpen', 'myBlockCompilerClose', array( $this->fenom->addBlockCompiler("myblockcompiler", 'myBlockCompilerOpen', 'myBlockCompilerClose', array(
@@ -91,7 +100,8 @@ class FenomTest extends \Fenom\TestCase {
/** /**
* @dataProvider providerOptions * @dataProvider providerOptions
*/ */
public function testOptions($code, $option) { public function testOptions($code, $option)
{
static $options = array(); static $options = array();
static $flags = 0; static $flags = 0;
$options[$code] = true; $options[$code] = true;

View File

@@ -1,31 +1,38 @@
<?php <?php
function myMod($str) { function myMod($str)
{
return "(myMod)" . $str . "(/myMod)"; return "(myMod)" . $str . "(/myMod)";
} }
function myFunc($params) { function myFunc($params)
{
return "MyFunc:" . $params["name"]; return "MyFunc:" . $params["name"];
} }
function myBlockFunc($params, $content) { function myBlockFunc($params, $content)
{
return "Block:" . $params["name"] . ':' . trim($content) . ':Block'; return "Block:" . $params["name"] . ':' . trim($content) . ':Block';
} }
function myCompiler(Fenom\Tokenizer $tokenizer, Fenom\Template $tpl) { function myCompiler(Fenom\Tokenizer $tokenizer, Fenom\Template $tpl)
{
$p = $tpl->parseParams($tokenizer); $p = $tpl->parseParams($tokenizer);
return 'echo "PHP_VERSION: ".PHP_VERSION." (for ".' . $p["name"] . '.")";'; return 'echo "PHP_VERSION: ".PHP_VERSION." (for ".' . $p["name"] . '.")";';
} }
function myBlockCompilerOpen(Fenom\Tokenizer $tokenizer, Fenom\Scope $scope) { function myBlockCompilerOpen(Fenom\Tokenizer $tokenizer, Fenom\Scope $scope)
{
return myCompiler($tokenizer, $scope->tpl); return myCompiler($tokenizer, $scope->tpl);
} }
function myBlockCompilerClose(Fenom\Tokenizer $tokenizer, Fenom\Scope $scope) { function myBlockCompilerClose(Fenom\Tokenizer $tokenizer, Fenom\Scope $scope)
{
return 'echo "End of compiler";'; return 'echo "End of compiler";';
} }
function myBlockCompilerTag(Fenom\Tokenizer $tokenizer, Fenom\Scope $scope) { function myBlockCompilerTag(Fenom\Tokenizer $tokenizer, Fenom\Scope $scope)
{
$p = $scope->tpl->parseParams($tokenizer); $p = $scope->tpl->parseParams($tokenizer);
return 'echo "Tag ".' . $p["name"] . '." of compiler";'; return 'echo "Tag ".' . $p["name"] . '." of compiler";';
} }