Name.php 2.6KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  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, 'always_defined' => 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. } elseif ($this->getAttribute('always_defined')) {
  34. $compiler
  35. ->raw('$context[')
  36. ->string($name)
  37. ->raw(']')
  38. ;
  39. } else {
  40. // remove the non-PHP 5.4 version when PHP 5.3 support is dropped
  41. // as the non-optimized version is just a workaround for slow ternary operator
  42. // when the context has a lot of variables
  43. if (version_compare(phpversion(), '5.4.0RC1', '>=') && ($this->getAttribute('ignore_strict_check') || !$compiler->getEnvironment()->isStrictVariables())) {
  44. // PHP 5.4 ternary operator performance was optimized
  45. $compiler
  46. ->raw('(isset($context[')
  47. ->string($name)
  48. ->raw(']) ? $context[')
  49. ->string($name)
  50. ->raw('] : null)')
  51. ;
  52. } else {
  53. $compiler
  54. ->raw('$this->getContext($context, ')
  55. ->string($name)
  56. ;
  57. if ($this->getAttribute('ignore_strict_check')) {
  58. $compiler->raw(', true');
  59. }
  60. $compiler
  61. ->raw(')')
  62. ;
  63. }
  64. }
  65. }
  66. public function isSpecial()
  67. {
  68. return isset($this->specialVars[$this->getAttribute('name')]);
  69. }
  70. public function isSimple()
  71. {
  72. return !$this->isSpecial() && !$this->getAttribute('is_defined_test');
  73. }
  74. }