Node.php 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Symfony\Component\ExpressionLanguage\Node;
  11. use Symfony\Component\ExpressionLanguage\Compiler;
  12. /**
  13. * Represents a node in the AST.
  14. *
  15. * @author Fabien Potencier <fabien@symfony.com>
  16. */
  17. class Node
  18. {
  19. public $nodes = [];
  20. public $attributes = [];
  21. /**
  22. * @param array $nodes An array of nodes
  23. * @param array $attributes An array of attributes
  24. */
  25. public function __construct(array $nodes = [], array $attributes = [])
  26. {
  27. $this->nodes = $nodes;
  28. $this->attributes = $attributes;
  29. }
  30. public function __toString()
  31. {
  32. $attributes = [];
  33. foreach ($this->attributes as $name => $value) {
  34. $attributes[] = sprintf('%s: %s', $name, str_replace("\n", '', var_export($value, true)));
  35. }
  36. $repr = [str_replace('Symfony\Component\ExpressionLanguage\Node\\', '', \get_class($this)).'('.implode(', ', $attributes)];
  37. if (\count($this->nodes)) {
  38. foreach ($this->nodes as $node) {
  39. foreach (explode("\n", (string) $node) as $line) {
  40. $repr[] = ' '.$line;
  41. }
  42. }
  43. $repr[] = ')';
  44. } else {
  45. $repr[0] .= ')';
  46. }
  47. return implode("\n", $repr);
  48. }
  49. public function compile(Compiler $compiler)
  50. {
  51. foreach ($this->nodes as $node) {
  52. $node->compile($compiler);
  53. }
  54. }
  55. public function evaluate($functions, $values)
  56. {
  57. $results = [];
  58. foreach ($this->nodes as $node) {
  59. $results[] = $node->evaluate($functions, $values);
  60. }
  61. return $results;
  62. }
  63. public function toArray()
  64. {
  65. throw new \BadMethodCallException(sprintf('Dumping a "%s" instance is not supported yet.', \get_class($this)));
  66. }
  67. public function dump()
  68. {
  69. $dump = '';
  70. foreach ($this->toArray() as $v) {
  71. $dump .= is_scalar($v) ? $v : $v->dump();
  72. }
  73. return $dump;
  74. }
  75. protected function dumpString($value)
  76. {
  77. return sprintf('"%s"', addcslashes($value, "\0\t\"\\"));
  78. }
  79. protected function isHash(array $value)
  80. {
  81. $expectedKey = 0;
  82. foreach ($value as $key => $val) {
  83. if ($key !== $expectedKey++) {
  84. return true;
  85. }
  86. }
  87. return false;
  88. }
  89. }