EnumNode.php 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  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($name, NodeInterface $parent = null, array $values = array())
  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);
  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(
  38. 'The value %s is not allowed for path "%s". Permissible values: %s',
  39. json_encode($value),
  40. $this->getPath(),
  41. implode(', ', array_map('json_encode', $this->values))));
  42. $ex->setPath($this->getPath());
  43. throw $ex;
  44. }
  45. return $value;
  46. }
  47. }