sfValidatorChoice.class.php 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  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 11970 2008-10-06 06:28:40Z dwhittle $
  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. * * multiple: true if the select tag must allow multiple selections
  26. *
  27. * @param array $options An array of options
  28. * @param array $messages An array of error messages
  29. *
  30. * @see sfValidatorBase
  31. */
  32. protected function configure($options = array(), $messages = array())
  33. {
  34. $this->addRequiredOption('choices');
  35. $this->addOption('multiple', false);
  36. }
  37. /**
  38. * @see sfValidatorBase
  39. */
  40. protected function doClean($value)
  41. {
  42. $choices = $this->getOption('choices');
  43. if ($choices instanceof sfCallable)
  44. {
  45. $choices = $choices->call();
  46. }
  47. if ($this->getOption('multiple'))
  48. {
  49. if (!is_array($value))
  50. {
  51. $value = array($value);
  52. }
  53. foreach ($value as $v)
  54. {
  55. if (!self::inChoices($v, $choices))
  56. {
  57. throw new sfValidatorError($this, 'invalid', array('value' => $v));
  58. }
  59. }
  60. }
  61. else
  62. {
  63. if (!self::inChoices($value, $choices))
  64. {
  65. throw new sfValidatorError($this, 'invalid', array('value' => $value));
  66. }
  67. }
  68. return $value;
  69. }
  70. /**
  71. * Checks if a value is part of given choices (see bug #4212)
  72. *
  73. * @param mixed $value The value to check
  74. * @param array $choices The array of available choices
  75. *
  76. * @return Boolean
  77. */
  78. static protected function inChoices($value, array $choices = array())
  79. {
  80. foreach ($choices as $choice)
  81. {
  82. if ((string) $choice == (string) $value)
  83. {
  84. return true;
  85. }
  86. }
  87. return false;
  88. }
  89. }