Node.php 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113
  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. /**
  31. * @return string
  32. */
  33. public function __toString()
  34. {
  35. $attributes = [];
  36. foreach ($this->attributes as $name => $value) {
  37. $attributes[] = sprintf('%s: %s', $name, str_replace("\n", '', var_export($value, true)));
  38. }
  39. $repr = [str_replace('Symfony\Component\ExpressionLanguage\Node\\', '', static::class).'('.implode(', ', $attributes)];
  40. if (\count($this->nodes)) {
  41. foreach ($this->nodes as $node) {
  42. foreach (explode("\n", (string) $node) as $line) {
  43. $repr[] = ' '.$line;
  44. }
  45. }
  46. $repr[] = ')';
  47. } else {
  48. $repr[0] .= ')';
  49. }
  50. return implode("\n", $repr);
  51. }
  52. public function compile(Compiler $compiler)
  53. {
  54. foreach ($this->nodes as $node) {
  55. $node->compile($compiler);
  56. }
  57. }
  58. public function evaluate(array $functions, array $values)
  59. {
  60. $results = [];
  61. foreach ($this->nodes as $node) {
  62. $results[] = $node->evaluate($functions, $values);
  63. }
  64. return $results;
  65. }
  66. public function toArray()
  67. {
  68. throw new \BadMethodCallException(sprintf('Dumping a "%s" instance is not supported yet.', static::class));
  69. }
  70. public function dump()
  71. {
  72. $dump = '';
  73. foreach ($this->toArray() as $v) {
  74. $dump .= is_scalar($v) ? $v : $v->dump();
  75. }
  76. return $dump;
  77. }
  78. protected function dumpString(string $value)
  79. {
  80. return sprintf('"%s"', addcslashes($value, "\0\t\"\\"));
  81. }
  82. protected function isHash(array $value)
  83. {
  84. $expectedKey = 0;
  85. foreach ($value as $key => $val) {
  86. if ($key !== $expectedKey++) {
  87. return true;
  88. }
  89. }
  90. return false;
  91. }
  92. }