4 * This file is part of the Symfony package.
6 * (c) Fabien Potencier <fabien@symfony.com>
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
12 namespace Symfony\Bridge\Twig\Node
;
15 * @author Fabien Potencier <fabien@symfony.com>
17 class TransNode
extends \Twig_Node
19 public function __construct(\Twig_NodeInterface
$body, \Twig_NodeInterface
$domain = null, \Twig_Node_Expression
$count = null, \Twig_Node_Expression
$vars = null, \Twig_Node_Expression
$locale = null, $lineno = 0, $tag = null)
21 parent
::__construct(array('count' => $count, 'body' => $body, 'domain' => $domain, 'vars' => $vars, 'locale' => $locale), array(), $lineno, $tag);
25 * Compiles the node to PHP.
27 * @param \Twig_Compiler $compiler A Twig_Compiler instance
29 public function compile(\Twig_Compiler
$compiler)
31 $compiler->addDebugInfo($this);
33 $vars = $this->getNode('vars');
34 $defaults = new \
Twig_Node_Expression_Array(array(), -1);
35 if ($vars instanceof \Twig_Node_Expression_Array
) {
36 $defaults = $this->getNode('vars');
39 list($msg, $defaults) = $this->compileString($this->getNode('body'), $defaults);
41 $method = null === $this->getNode('count') ? 'trans' : 'transChoice';
44 ->write('echo $this->env->getExtension(\'translator\')->getTranslator()->'.$method.'(')
50 if (null !== $this->getNode('count')) {
52 ->subcompile($this->getNode('count'))
60 ->subcompile($defaults)
62 ->subcompile($this->getNode('vars'))
66 $compiler->subcompile($defaults);
71 if (null === $this->getNode('domain')) {
72 $compiler->repr('messages');
74 $compiler->subcompile($this->getNode('domain'));
77 if (null !== $this->getNode('locale')) {
80 ->subcompile($this->getNode('locale'))
83 $compiler->raw(");\n");
86 protected function compileString(\Twig_NodeInterface
$body, \Twig_Node_Expression_Array
$vars)
88 if ($body instanceof \Twig_Node_Expression_Constant
) {
89 $msg = $body->getAttribute('value');
90 } elseif ($body instanceof \Twig_Node_Text
) {
91 $msg = $body->getAttribute('data');
93 return array($body, $vars);
96 preg_match_all('/(?<!%)%([^%]+)%/', $msg, $matches);
98 if (version_compare(\Twig_Environment
::VERSION
, '1.5', '>=')) {
99 foreach ($matches[1] as $var) {
100 $key = new \
Twig_Node_Expression_Constant('%'.$var.'%', $body->getLine());
101 if (!$vars->hasElement($key)) {
102 $vars->addElement(new \
Twig_Node_Expression_Name($var, $body->getLine()), $key);
107 foreach ($vars as $name => $var) {
108 $current[$name] = true;
110 foreach ($matches[1] as $var) {
111 if (!isset($current['%'.$var.'%'])) {
112 $vars->setNode('%'.$var.'%', new \
Twig_Node_Expression_Name($var, $body->getLine()));
117 return array(new \
Twig_Node_Expression_Constant(str_replace('%%', '%', trim($msg)), $body->getLine()), $vars);