Created
October 26, 2009 05:28
-
-
Save co3k/218446 to your computer and use it in GitHub Desktop.
Twig で symfony のヘルパー関数を超強引に使えるようにする Extension (HelperTokenParser はもっと簡単に書けた。後で直す)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class HelperTwigExtension extends Twig_Extension | |
{ | |
static protected $helpers = array(); | |
public function getTokenParsers() | |
{ | |
if (empty(self::$helpers)) | |
{ | |
self::$helpers = $this->generateHelperList(); | |
} | |
$parsers = array(); | |
foreach (self::$helpers as $helper) | |
{ | |
$parsers[] = new HelperTokenParser($helper); | |
} | |
return $parsers; | |
} | |
public function generateHelperList() | |
{ | |
$result = array(); | |
$funcs = get_defined_functions(); | |
foreach ($funcs['user'] as $func) | |
{ | |
$reflection = new ReflectionFunction($func); | |
if (strpos($reflection->getFileName(), 'helper')) | |
{ | |
$result[] = $func; | |
} | |
} | |
return $result; | |
} | |
public function getName() | |
{ | |
return 'helper'; | |
} | |
} | |
class HelperTokenParser extends Twig_TokenParser | |
{ | |
protected $name = ''; | |
public function __construct($name) | |
{ | |
$this->name = $name; | |
} | |
public function parse(Twig_Token $token) | |
{ | |
$allowed = array(Twig_Token::NAME_TYPE, Twig_Token::NUMBER_TYPE, Twig_Token::STRING_TYPE); | |
$values = array(); | |
while (true) | |
{ | |
$stream = $this->parser->getStream()->next(); | |
if ($stream->getType() === Twig_Token::BLOCK_END_TYPE) | |
{ | |
break; | |
} | |
if (!in_array($stream->getType(), $allowed)) | |
{ | |
continue; | |
} | |
$values[] = $stream->getValue(); | |
} | |
return new HelperNode($this->getTag(), $values); | |
} | |
public function getTag() | |
{ | |
return $this->name; | |
} | |
} | |
class HelperNode extends Twig_Node | |
{ | |
protected $name, $values; | |
public function __construct($name, $values) | |
{ | |
$this->name = $name; | |
$this->values = $values; | |
} | |
public function compile($compiler) | |
{ | |
$compiler->write('echo call_user_func_array("'.$this->name.'", ') | |
->repr($this->values) | |
->write(');'); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment