EnumNode.php 1.6 KB

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