sfValidatorChoice.class.php 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. <?php
  2. /*
  3. * This file is part of the symfony package.
  4. * (c) Fabien Potencier <fabien.potencier@symfony-project.com>
  5. *
  6. * For the full copyright and license information, please view the LICENSE
  7. * file that was distributed with this source code.
  8. */
  9. /**
  10. * sfValidatorChoice validates than the value is one of the expected values.
  11. *
  12. * @package symfony
  13. * @subpackage validator
  14. * @author Fabien Potencier <fabien.potencier@symfony-project.com>
  15. * @version SVN: $Id: sfValidatorChoice.class.php 11612 2008-09-17 15:28:38Z nicolas $
  16. */
  17. class sfValidatorChoice extends sfValidatorBase
  18. {
  19. /**
  20. * Configures the current validator.
  21. *
  22. * Available options:
  23. *
  24. * * choices: An array of expected values (required)
  25. *
  26. * @param array $options An array of options
  27. * @param array $messages An array of error messages
  28. *
  29. * @see sfValidatorBase
  30. */
  31. protected function configure($options = array(), $messages = array())
  32. {
  33. $this->addRequiredOption('choices');
  34. }
  35. /**
  36. * @see sfValidatorBase
  37. */
  38. protected function doClean($value)
  39. {
  40. $choices = $this->getOption('choices');
  41. if ($choices instanceof sfCallable)
  42. {
  43. $choices = $choices->call();
  44. }
  45. if (!self::inChoices($value, $choices))
  46. {
  47. throw new sfValidatorError($this, 'invalid', array('value' => $value));
  48. }
  49. return $value;
  50. }
  51. /**
  52. * Checks if a value is part of given choices (see bug #4212)
  53. *
  54. * @param mixed $value The value to check
  55. * @param array $choices The array of available choices
  56. *
  57. * @return Boolean
  58. */
  59. static protected function inChoices($value, array $choices = array())
  60. {
  61. foreach ($choices as $choice)
  62. {
  63. if ((string) $choice == (string) $value)
  64. {
  65. return true;
  66. }
  67. }
  68. return false;
  69. }
  70. }