Improve accessor: add writable condition

This commit is contained in:
bzick 2015-06-02 10:59:28 +03:00
parent ef4458ca10
commit e0fc70b751
3 changed files with 26 additions and 5 deletions

View File

@ -19,6 +19,7 @@ use Fenom\Template;
class Fenom
{
const VERSION = '2.4';
const REV = 1;
/* Actions */
const INLINE_COMPILER = 1;
const BLOCK_COMPILER = 5;
@ -797,6 +798,18 @@ class Fenom
return $this->_options;
}
/**
* Add global accessor ($.)
* @param string $name
* @param callable $parser
* @return Fenom
*/
public function addAccessor($name, $parser)
{
$this->_accessors[$name] = $parser;
return $this;
}
/**
* Add global accessor ($.)
* @param string $name
@ -804,8 +817,7 @@ class Fenom
* @param string $parser
* @return Fenom
*/
public function addAccessor($name, $accessor, $parser = self::ACCESSOR_CUSTOM)
{
public function addAccessorSmart($name, $accessor, $parser) {
$this->_accessors[$name] = array(
"accessor" => $accessor,
"parser" => $parser

View File

@ -741,7 +741,16 @@ class Compiler
*/
public static function setOpen(Tokenizer $tokens, Tag $scope)
{
$var = $scope->tpl->parseVariable($tokens);
if($tokens->is(T_VARIABLE)) {
$var = $scope->tpl->parseVariable($tokens);
} elseif($tokens->is('$')) {
$var = $scope->tpl->parseAccessor($tokens, $is_var);
if(!$is_var) {
throw new InvalidUsageException("Accessor is not writable");
}
} else {
throw new InvalidUsageException("{set} and {add} accept only variable");
}
$before = $after = "";
if($scope->name == 'add') {
$before = "if(!isset($var)) {\n";

View File

@ -12,7 +12,7 @@ class SandboxTest extends TestCase {
{
return;
$this->fenom->setOptions(\Fenom::FORCE_VERIFY);
$this->fenom->addAccessor('q', 'Navi::$q', \Fenom::ACCESSOR_VAR);
$this->fenom->addAccessorSmart('q', 'Navi::$q', \Fenom::ACCESSOR_VAR);
// $this->assertEquals([1, 2, 4, "as" => 767, "df" => ["qert"]], [1, 2, 4, "as" => 767, "df" => ["qet"]]);
// $this->fenom->addBlockCompiler('php', 'Fenom\Compiler::nope', function ($tokens, Tag $tag) {
// return '<?php ' . $tag->cutContent();
@ -20,7 +20,7 @@ class SandboxTest extends TestCase {
// $this->tpl('welcome.tpl', '{$a}');
// var_dump($this->fenom->compileCode('{set $a=$one|min:0..$three|max:4}')->getBody());
try {
var_dump($this->fenom->compileCode('{$.q.ddqd->d() + 333}')->getBody());
var_dump($this->fenom->compileCode('{set $.q.ddqd->d() = 333}')->getBody());
} catch (\Exception $e) {
print_r($e->getMessage() . "\n" . $e->getTraceAsString());
while ($e->getPrevious()) {