Development

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

You must first sign up to be able to contribute.

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

Revision 21875, 11.4 kB (checked in by fabien, 5 years ago)

[1.2, 1.3] fixed PHPDoc (closes #6279)

  • 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  * sfValidatorBase is the base class for all validators.
13  *
14  * It also implements the required option for all validators.
15  *
16  * @package    symfony
17  * @subpackage validator
18  * @author     Fabien Potencier <fabien.potencier@symfony-project.com>
19  * @version    SVN: $Id$
20  */
21 abstract class sfValidatorBase
22 {
23   protected static
24     $charset         = 'UTF-8',
25     $invalidMessage  = 'Invalid.',
26     $requiredMessage = 'Required.';
27
28   protected
29     $requiredOptions = array(),
30     $defaultMessages = array(),
31     $defaultOptions  = array(),
32     $messages        = array(),
33     $options         = array();
34
35   /**
36    * Constructor.
37    *
38    * Available options:
39    *
40    *  * required:    true if the value is required, false otherwise (default to true)
41    *  * trim:        true if the value must be trimmed, false otherwise (default to false)
42    *  * empty_value: empty value when value is not required
43    *
44    * Available error codes:
45    *
46    *  * required
47    *  * invalid
48    *
49    * @param array $options   An array of options
50    * @param array $messages  An array of error messages
51    */
52   public function __construct($options = array(), $messages = array())
53   {
54     $this->options  = array_merge(array('required' => true, 'trim' => false, 'empty_value' => null), $this->options);
55     $this->messages = array_merge(array('required' => self::$requiredMessage, 'invalid' => self::$invalidMessage), $this->messages);
56
57     $this->configure($options, $messages);
58
59     $this->setDefaultOptions($this->getOptions());
60     $this->setDefaultMessages($this->getMessages());
61
62     $currentOptionKeys = array_keys($this->options);
63     $optionKeys = array_keys($options);
64
65     // check option names
66     if ($diff = array_diff($optionKeys, array_merge($currentOptionKeys, $this->requiredOptions)))
67     {
68       throw new InvalidArgumentException(sprintf('%s does not support the following options: \'%s\'.', get_class($this), implode('\', \'', $diff)));
69     }
70
71     // check error code names
72     if ($diff = array_diff(array_keys($messages), array_keys($this->messages)))
73     {
74       throw new InvalidArgumentException(sprintf('%s does not support the following error codes: \'%s\'.', get_class($this), implode('\', \'', $diff)));
75     }
76
77     // check required options
78     if ($diff = array_diff($this->requiredOptions, array_merge($currentOptionKeys, $optionKeys)))
79     {
80       throw new RuntimeException(sprintf('%s requires the following options: \'%s\'.', get_class($this), implode('\', \'', $diff)));
81     }
82
83     $this->options  = array_merge($this->options, $options);
84     $this->messages = array_merge($this->messages, $messages);
85   }
86
87   /**
88    * Configures the current validator.
89    *
90    * This method allows each validator to add options and error messages
91    * during validator creation.
92    *
93    * If some options and messages are given in the sfValidatorBase constructor
94    * they will take precedence over the options and messages you configure
95    * in this method.
96    *
97    * @param array $options   An array of options
98    * @param array $messages  An array of error messages
99    *
100    * @see __construct()
101    */
102   protected function configure($options = array(), $messages = array())
103   {
104   }
105
106   /**
107    * Returns an error message given an error code.
108    *
109    * @param  string $name  The error code
110    *
111    * @return string The error message, or the empty string if the error code does not exist
112    */
113   public function getMessage($name)
114   {
115     return isset($this->messages[$name]) ? $this->messages[$name] : '';
116   }
117
118   /**
119    * Adds a new error code with a default error message.
120    *
121    * @param string $name   The error code
122    * @param string $value  The error message
123    */
124   public function addMessage($name, $value)
125   {
126     $this->messages[$name] = $value;
127   }
128
129   /**
130    * Changes an error message given the error code.
131    *
132    * @param string $name   The error code
133    * @param string $value  The error message
134    */
135   public function setMessage($name, $value)
136   {
137     if (!in_array($name, array_keys($this->messages)))
138     {
139       throw new InvalidArgumentException(sprintf('%s does not support the following error code: \'%s\'.', get_class($this), $name));
140     }
141
142     $this->messages[$name] = $value;
143   }
144
145   /**
146    * Returns an array of current error messages.
147    *
148    * @return array An array of messages
149    */
150   public function getMessages()
151   {
152     return $this->messages;
153   }
154
155   /**
156    * Changes all error messages.
157    *
158    * @param array $values  An array of error messages
159    */
160   public function setMessages($values)
161   {
162     $this->messages = $values;
163   }
164
165   /**
166    * Gets an option value.
167    *
168    * @param  string $name  The option name
169    *
170    * @return mixed  The option value
171    */
172   public function getOption($name)
173   {
174     return isset($this->options[$name]) ? $this->options[$name] : null;
175   }
176
177   /**
178    * Adds a new option value with a default value.
179    *
180    * @param string $name   The option name
181    * @param mixed  $value  The default value
182    */
183   public function addOption($name, $value = null)
184   {
185     $this->options[$name] = $value;
186   }
187
188   /**
189    * Changes an option value.
190    *
191    * @param string $name   The option name
192    * @param mixed  $value  The value
193    */
194   public function setOption($name, $value)
195   {
196     if (!in_array($name, array_merge(array_keys($this->options), $this->requiredOptions)))
197     {
198       throw new InvalidArgumentException(sprintf('%s does not support the following option: \'%s\'.', get_class($this), $name));
199     }
200
201     $this->options[$name] = $value;
202   }
203
204   /**
205    * Returns true if the option exists.
206    *
207    * @param  string $name  The option name
208    *
209    * @return bool true if the option exists, false otherwise
210    */
211   public function hasOption($name)
212   {
213     return isset($this->options[$name]);
214   }
215
216   /**
217    * Returns all options.
218    *
219    * @return array An array of options
220    */
221   public function getOptions()
222   {
223     return $this->options;
224   }
225
226   /**
227    * Changes all options.
228    *
229    * @param array $values  An array of options
230    */
231   public function setOptions($values)
232   {
233     $this->options = $values;
234   }
235
236   /**
237    * Adds a required option.
238    *
239    * @param string $name  The option name
240    */
241   public function addRequiredOption($name)
242   {
243     $this->requiredOptions[] = $name;
244   }
245
246   /**
247    * Returns all required option names.
248    *
249    * @return array An array of required option names
250    */
251   public function getRequiredOptions()
252   {
253     return $this->requiredOptions;
254   }
255
256   /**
257    * Sets the default invalid message
258    *
259    * @param string $message
260    */
261   static public function setInvalidMessage($message)
262   {
263     self::$invalidMessage = $message;
264   }
265
266   /**
267    * Sets the default required message
268    *
269    * @param string $message
270    */
271   static public function setRequiredMessage($message)
272   {
273     self::$requiredMessage = $message;
274   }
275
276   /**
277    * Cleans the input value.
278    *
279    * This method is also responsible for trimming the input value
280    * and checking the required option.
281    *
282    * @param  mixed $value  The input value
283    *
284    * @return mixed The cleaned value
285    *
286    * @throws sfValidatorError
287    */
288   public function clean($value)
289   {
290     $clean = $value;
291
292     if ($this->options['trim'] && is_string($clean))
293     {
294       $clean = trim($clean);
295     }
296
297     // empty value?
298     if ($this->isEmpty($clean))
299     {
300       // required?
301       if ($this->options['required'])
302       {
303         throw new sfValidatorError($this, 'required');
304       }
305
306       return $this->getEmptyValue();
307     }
308
309     return $this->doClean($clean);
310   }
311
312   /**
313    * Cleans the input value.
314    *
315    * Every subclass must implements this method.
316    *
317    * @param  mixed $value  The input value
318    *
319    * @return mixed The cleaned value
320    *
321    * @throws sfValidatorError
322    */
323   abstract protected function doClean($value);
324
325   /**
326    * Sets the charset to use when validating strings.
327    *
328    * @param string $charset  The charset
329    */
330   static public function setCharset($charset)
331   {
332     self::$charset = $charset;
333   }
334
335   /**
336    * Returns the charset to use when validating strings.
337    *
338    * @return string The charset (default to UTF-8)
339    */
340   static public function getCharset()
341   {
342     return self::$charset;
343   }
344
345   /**
346    * Returns true if the value is empty.
347    *
348    * @param  mixed $value  The input value
349    *
350    * @return bool true if the value is empty, false otherwise
351    */
352   protected function isEmpty($value)
353   {
354     return in_array($value, array(null, '', array()), true);
355   }
356
357   /**
358    * Returns an empty value for this validator.
359    *
360    * @return mixed The empty value for this validator
361    */
362   protected function getEmptyValue()
363   {
364     return $this->getOption('empty_value');
365   }
366
367   /**
368    * Returns an array of all error codes for this validator.
369    *
370    * @return array An array of possible error codes
371    *
372    * @see getDefaultMessages()
373    */
374   final public function getErrorCodes()
375   {
376     return array_keys($this->getDefaultMessages());
377   }
378
379   /**
380    * Returns default messages for all possible error codes.
381    *
382    * @return array An array of default error codes and messages
383    */
384   public function getDefaultMessages()
385   {
386     return $this->defaultMessages;
387   }
388
389   /**
390    * Sets default messages for all possible error codes.
391    *
392    * @param array $messages  An array of default error codes and messages
393    */
394   protected function setDefaultMessages($messages)
395   {
396     $this->defaultMessages = $messages;
397   }
398
399   /**
400    * Returns default option values.
401    *
402    * @return array An array of default option values
403    */
404   public function getDefaultOptions()
405   {
406     return $this->defaultOptions;
407   }
408
409   /**
410    * Sets default option values.
411    *
412    * @param array $options  An array of default option values
413    */
414   protected function setDefaultOptions($options)
415   {
416     $this->defaultOptions = $options;
417   }
418
419   /**
420    * Returns a string representation of this validator.
421    *
422    * @param  int $indent  Indentation (number of spaces before each line)
423    *
424    * @return string The string representation of the validator
425    */
426   public function asString($indent = 0)
427   {
428     $options = $this->getOptionsWithoutDefaults();
429     $messages = $this->getMessagesWithoutDefaults();
430
431     return sprintf('%s%s(%s%s)',
432       str_repeat(' ', $indent),
433       str_replace('sfValidator', '', get_class($this)),
434       $options ? sfYamlInline::dump($options) : ($messages ? '{}' : ''),
435       $messages ? ', '.sfYamlInline::dump($messages) : ''
436     );
437   }
438
439   /**
440    * Returns all error messages with non default values.
441    *
442    * @return string A string representation of the error messages
443    */
444   protected function getMessagesWithoutDefaults()
445   {
446     $messages = $this->messages;
447
448     // remove default option values
449     foreach ($this->getDefaultMessages() as $key => $value)
450     {
451       if (array_key_exists($key, $messages) && $messages[$key] === $value)
452       {
453         unset($messages[$key]);
454       }
455     }
456
457     return $messages;
458   }
459
460   /**
461    * Returns all options with non default values.
462    *
463    * @return string  A string representation of the options
464    */
465   protected function getOptionsWithoutDefaults()
466   {
467     $options = $this->options;
468
469     // remove default option values
470     foreach ($this->getDefaultOptions() as $key => $value)
471     {
472       if (array_key_exists($key, $options) && $options[$key] === $value)
473       {
474         unset($options[$key]);
475       }
476     }
477
478     return $options;
479   }
480 }
481
Note: See TracBrowser for help on using the browser.