PageRenderTime 102ms CodeModel.GetById 50ms app.highlight 2ms RepoModel.GetById 48ms app.codeStats 1ms

/plugins/sfFormExtraPlugin/lib/validator/sfValidatorDefault.class.php

https://bitbucket.org/Kudlaty/360kdw
PHP | 76 lines | 29 code | 6 blank | 41 comment | 1 complexity | 122f99df59284f63338fd9a1e055e4ff MD5 | raw file
 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 * Returns a default value instead of throwing an error on validation failure.
13 *
14 *     $this->validatorSchema['sort'] = new sfValidatorDefault(array(
15 *       'validator' => new sfValidatorChoice(array('choices' => array('up', 'down'))),
16 *       'default'   => 'up',
17 *     ));
18 *
19 * If no default option is provided, the supplied validator's empty value will
20 * be returned on error.
21 *
22 * @package    sfFormExtraPlugin
23 * @subpackage validator
24 * @author     Kris Wallsmith <kris.wallsmith@symfony-project.com>
25 * @version    SVN: $Id: sfValidatorDefault.class.php 27625 2010-02-06 22:07:40Z Kris.Wallsmith $
26 */
27class sfValidatorDefault extends sfValidatorBase
28{
29  /**
30   * Configures the current validator.
31   *
32   * Available options:
33   *
34   *  * validator: The validator to use
35   *  * default:   The value to return if the validator fails
36   *
37   * @see sfValidatorBase
38   */
39  protected function configure($options = array(), $messages = array())
40  {
41    $this->addRequiredOption('validator');
42    $this->addOption('default', null);
43  }
44
45  /**
46   * @see sfValidatorBase
47   */
48  protected function isEmpty($value)
49  {
50    return false;
51  }
52
53  /**
54   * @see sfValidatorBase
55   *
56   * @throws InvalidArgumentException If the validator option is not a validator object
57   */
58  protected function doClean($value)
59  {
60    $validator = $this->getOption('validator');
61
62    if (!$validator instanceof sfValidatorBase)
63    {
64      throw new InvalidArgumentException('The "validator" option must be an instance of sfValidatorBase.');
65    }
66
67    try
68    {
69      return $validator->clean($value);
70    }
71    catch (sfValidatorError $error)
72    {
73      return null === $this->getOption('default') ? $validator->getEmptyValue() : $this->getOption('default');
74    }
75  }
76}