Name.php 2.4KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. <?php
  2. /*
  3. * This file is part of Twig.
  4. *
  5. * (c) 2009 Fabien Potencier
  6. * (c) 2009 Armin Ronacher
  7. *
  8. * For the full copyright and license information, please view the LICENSE
  9. * file that was distributed with this source code.
  10. */
  11. class Twig_Node_Expression_Name extends Twig_Node_Expression
  12. {
  13. protected $specialVars = array(
  14. '_self' => '$this',
  15. '_context' => '$context',
  16. '_charset' => '$this->env->getCharset()',
  17. );
  18. public function __construct($name, $lineno)
  19. {
  20. parent::__construct(array(), array('name' => $name, 'is_defined_test' => false, 'ignore_strict_check' => false), $lineno);
  21. }
  22. public function compile(Twig_Compiler $compiler)
  23. {
  24. $name = $this->getAttribute('name');
  25. if ($this->getAttribute('is_defined_test')) {
  26. if ($this->isSpecial()) {
  27. $compiler->repr(true);
  28. } else {
  29. $compiler->raw('array_key_exists(')->repr($name)->raw(', $context)');
  30. }
  31. } elseif ($this->isSpecial()) {
  32. $compiler->raw($this->specialVars[$name]);
  33. } else {
  34. // remove the non-PHP 5.4 version when PHP 5.3 support is dropped
  35. // as the non-optimized version is just a workaround for slow ternary operator
  36. // when the context has a lot of variables
  37. if (version_compare(phpversion(), '5.4.0RC1', '>=') && ($this->getAttribute('ignore_strict_check') || !$compiler->getEnvironment()->isStrictVariables())) {
  38. // PHP 5.4 ternary operator performance was optimized
  39. $compiler
  40. ->raw('(isset($context[')
  41. ->string($name)
  42. ->raw(']) ? $context[')
  43. ->string($name)
  44. ->raw('] : null)')
  45. ;
  46. } else {
  47. $compiler
  48. ->raw('$this->getContext($context, ')
  49. ->string($name)
  50. ;
  51. if ($this->getAttribute('ignore_strict_check')) {
  52. $compiler->raw(', true');
  53. }
  54. $compiler
  55. ->raw(')')
  56. ;
  57. }
  58. }
  59. }
  60. public function isSpecial()
  61. {
  62. return isset($this->specialVars[$this->getAttribute('name')]);
  63. }
  64. public function isSimple()
  65. {
  66. return !$this->isSpecial() && !$this->getAttribute('is_defined_test');
  67. }
  68. }