EnumNode.php 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  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\Config\Definition;
  11. use Symfony\Component\Config\Definition\Exception\InvalidConfigurationException;
  12. /**
  13. * Node which only allows a finite set of values.
  14. *
  15. * @author Johannes M. Schmitt <schmittjoh@gmail.com>
  16. */
  17. class EnumNode extends ScalarNode
  18. {
  19. private $values;
  20. public function __construct(?string $name, NodeInterface $parent = null, array $values = [], string $pathSeparator = BaseNode::DEFAULT_PATH_SEPARATOR)
  21. {
  22. $values = array_unique($values);
  23. if (empty($values)) {
  24. throw new \InvalidArgumentException('$values must contain at least one element.');
  25. }
  26. parent::__construct($name, $parent, $pathSeparator);
  27. $this->values = $values;
  28. }
  29. public function getValues()
  30. {
  31. return $this->values;
  32. }
  33. protected function finalizeValue($value)
  34. {
  35. $value = parent::finalizeValue($value);
  36. if (!\in_array($value, $this->values, true)) {
  37. $ex = new InvalidConfigurationException(sprintf('The value %s is not allowed for path "%s". Permissible values: %s', json_encode($value), $this->getPath(), implode(', ', array_map('json_encode', $this->values))));
  38. $ex->setPath($this->getPath());
  39. throw $ex;
  40. }
  41. return $value;
  42. }
  43. /**
  44. * {@inheritdoc}
  45. */
  46. protected function allowPlaceholders(): bool
  47. {
  48. return false;
  49. }
  50. }