Support $foo->$bar syntax in templates

기존: $__Context->$__Context->bar 로 변환되어 오작동
개선: $__Context->{$__Context->bar} 로 변환되어 정상 작동되며
      변싱 순서에 따라 이 중괄호가 다시 해석되지는 않음
This commit is contained in:
Kijin Sung 2022-10-30 21:41:40 +09:00
parent 39093a7380
commit 93a7348606
2 changed files with 18 additions and 1 deletions

View file

@ -1108,7 +1108,13 @@ class TemplateHandler
return '';
}
return preg_replace_callback('@(?<!::|\\\\|(?<!eval\()\')\$([a-z_][a-z0-9_]*)@i', function($matches) {
// Replace some variables that need to be enclosed in curly braces.
$php = preg_replace_callback('@(?<!\$__Context)->\$([a-z_][a-z0-9_]*)@i', function($matches) {
return '->{$__Context->' . $matches[1] . '}';
}, $php);
// Replace all other variables with Context attributes.
$php = preg_replace_callback('@(?<!::|\\\\|\$__Context->|(?<!eval\()\')\$([a-z_][a-z0-9_]*)@i', function($matches) {
if (preg_match('/^(?:GLOBALS|_SERVER|_COOKIE|_GET|_POST|_REQUEST|_SESSION|__Context|this|lang)$/', $matches[1]))
{
return '$' . $matches[1];
@ -1118,6 +1124,8 @@ class TemplateHandler
return '$__Context->' . $matches[1];
}
}, $php);
return $php;
}
}

View file

@ -315,6 +315,15 @@ class TemplateHandlerTest extends \Codeception\TestCase\Test
array(
'<span>{\RX_BASEDIR}</span>',
'?><span><?php echo \RX_BASEDIR ?></span>'
),
// Rhymix improvements: object attributes enclosed in curly braces
array(
'<div>{$foo->$bar[$bazz]}</div>',
'?><div><?php echo $__Context->foo->{$__Context->bar}[$__Context->bazz] ?></div>'
),
array(
'<!--@if($foo->$bar)--><div></div><!--@endif-->',
"\n" . 'if($__Context->foo->{$__Context->bar}){ ?><div></div><?php } ?>'
),
// Rhymix autoescape
array(