| 1 |
<?php |
|---|
| 2 |
|
|---|
| 3 |
|
|---|
| 4 |
|
|---|
| 5 |
|
|---|
| 6 |
|
|---|
| 7 |
|
|---|
| 8 |
|
|---|
| 9 |
|
|---|
| 10 |
|
|---|
| 11 |
|
|---|
| 12 |
|
|---|
| 13 |
|
|---|
| 14 |
|
|---|
| 15 |
|
|---|
| 16 |
|
|---|
| 17 |
|
|---|
| 18 |
|
|---|
| 19 |
class sfValidatorChoice extends sfValidatorBase |
|---|
| 20 |
{ |
|---|
| 21 |
|
|---|
| 22 |
* Configures the current validator. |
|---|
| 23 |
* |
|---|
| 24 |
* Available options: |
|---|
| 25 |
* |
|---|
| 26 |
* * choices: An array of expected values (required) |
|---|
| 27 |
* * multiple: true if the select tag must allow multiple selections |
|---|
| 28 |
* |
|---|
| 29 |
* @param array $options An array of options |
|---|
| 30 |
* @param array $messages An array of error messages |
|---|
| 31 |
* |
|---|
| 32 |
* @see sfValidatorBase |
|---|
| 33 |
*/ |
|---|
| 34 |
protected function configure($options = array(), $messages = array()) |
|---|
| 35 |
{ |
|---|
| 36 |
$this->addRequiredOption('choices'); |
|---|
| 37 |
$this->addOption('multiple', false); |
|---|
| 38 |
} |
|---|
| 39 |
|
|---|
| 40 |
|
|---|
| 41 |
* @see sfValidatorBase |
|---|
| 42 |
*/ |
|---|
| 43 |
protected function doClean($value) |
|---|
| 44 |
{ |
|---|
| 45 |
$choices = $this->getOption('choices'); |
|---|
| 46 |
if ($choices instanceof sfCallable) |
|---|
| 47 |
{ |
|---|
| 48 |
$choices = $choices->call(); |
|---|
| 49 |
} |
|---|
| 50 |
|
|---|
| 51 |
if ($this->getOption('multiple')) |
|---|
| 52 |
{ |
|---|
| 53 |
if (!is_array($value)) |
|---|
| 54 |
{ |
|---|
| 55 |
$value = array($value); |
|---|
| 56 |
} |
|---|
| 57 |
|
|---|
| 58 |
foreach ($value as $v) |
|---|
| 59 |
{ |
|---|
| 60 |
if (!self::inChoices($v, $choices)) |
|---|
| 61 |
{ |
|---|
| 62 |
throw new sfValidatorError($this, 'invalid', array('value' => $v)); |
|---|
| 63 |
} |
|---|
| 64 |
} |
|---|
| 65 |
} |
|---|
| 66 |
else |
|---|
| 67 |
{ |
|---|
| 68 |
if (!self::inChoices($value, $choices)) |
|---|
| 69 |
{ |
|---|
| 70 |
throw new sfValidatorError($this, 'invalid', array('value' => $value)); |
|---|
| 71 |
} |
|---|
| 72 |
} |
|---|
| 73 |
|
|---|
| 74 |
return $value; |
|---|
| 75 |
} |
|---|
| 76 |
|
|---|
| 77 |
|
|---|
| 78 |
* Checks if a value is part of given choices (see bug #4212) |
|---|
| 79 |
* |
|---|
| 80 |
* @param mixed $value The value to check |
|---|
| 81 |
* @param array $choices The array of available choices |
|---|
| 82 |
* |
|---|
| 83 |
* @return Boolean |
|---|
| 84 |
*/ |
|---|
| 85 |
static protected function inChoices($value, array $choices = array()) |
|---|
| 86 |
{ |
|---|
| 87 |
foreach ($choices as $choice) |
|---|
| 88 |
{ |
|---|
| 89 |
if ((string) $choice == (string) $value) |
|---|
| 90 |
{ |
|---|
| 91 |
return true; |
|---|
| 92 |
} |
|---|
| 93 |
} |
|---|
| 94 |
|
|---|
| 95 |
return false; |
|---|
| 96 |
} |
|---|
| 97 |
} |
|---|
| 98 |
|
|---|