Development

/branches/1.2/lib/validator/sfValidatorChoice.class.php

You must first sign up to be able to contribute.

root/branches/1.2/lib/validator/sfValidatorChoice.class.php

Revision 11970, 2.2 kB (checked in by dwhittle, 6 years ago)

1.2: fixed typo

  • Property svn:mime-type set to text/x-php
  • Property svn:eol-style set to native
  • Property svn:keywords set to Id
Line 
1 <?php
2
3 /*
4  * This file is part of the symfony package.
5  * (c) Fabien Potencier <fabien.potencier@symfony-project.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
11 /**
12  * sfValidatorChoice validates than the value is one of the expected values.
13  *
14  * @package    symfony
15  * @subpackage validator
16  * @author     Fabien Potencier <fabien.potencier@symfony-project.com>
17  * @version    SVN: $Id$
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
Note: See TracBrowser for help on using the browser.