UnaryNode.php 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  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. * @author Fabien Potencier <fabien@symfony.com>
  14. *
  15. * @internal
  16. */
  17. class UnaryNode extends Node
  18. {
  19. private const OPERATORS = [
  20. '!' => '!',
  21. 'not' => '!',
  22. '+' => '+',
  23. '-' => '-',
  24. ];
  25. public function __construct(string $operator, Node $node)
  26. {
  27. parent::__construct(
  28. ['node' => $node],
  29. ['operator' => $operator]
  30. );
  31. }
  32. public function compile(Compiler $compiler)
  33. {
  34. $compiler
  35. ->raw('(')
  36. ->raw(self::OPERATORS[$this->attributes['operator']])
  37. ->compile($this->nodes['node'])
  38. ->raw(')')
  39. ;
  40. }
  41. public function evaluate(array $functions, array $values)
  42. {
  43. $value = $this->nodes['node']->evaluate($functions, $values);
  44. switch ($this->attributes['operator']) {
  45. case 'not':
  46. case '!':
  47. return !$value;
  48. case '-':
  49. return -$value;
  50. }
  51. return $value;
  52. }
  53. public function toArray(): array
  54. {
  55. return ['(', $this->attributes['operator'].' ', $this->nodes['node'], ')'];
  56. }
  57. }