DefaultValueValidator.php 1.48 KB
Newer Older
w  
Qiang Xue committed
1 2 3
<?php
/**
 * @link http://www.yiiframework.com/
Qiang Xue committed
4
 * @copyright Copyright (c) 2008 Yii Software LLC
w  
Qiang Xue committed
5 6 7
 * @license http://www.yiiframework.com/license/
 */

w  
Qiang Xue committed
8 9
namespace yii\validators;

w  
Qiang Xue committed
10
/**
w  
Qiang Xue committed
11 12 13
 * DefaultValueValidator sets the attribute to be the specified default value.
 *
 * DefaultValueValidator is not really a validator. It is provided mainly to allow
Qiang Xue committed
14
 * specifying attribute default values when they are empty.
w  
Qiang Xue committed
15 16
 *
 * @author Qiang Xue <qiang.xue@gmail.com>
w  
Qiang Xue committed
17
 * @since 2.0
w  
Qiang Xue committed
18
 */
w  
Qiang Xue committed
19
class DefaultValueValidator extends Validator
w  
Qiang Xue committed
20
{
21
    /**
Qiang Xue committed
22 23 24
     * @var mixed the default value or a PHP callable that returns the default value which will
     * be assigned to the attributes being validated if they are empty. The signature of the PHP callable
     * should be as follows,
25
     *
Qiang Xue committed
26 27
     * ```php
     * function foo($model, $attribute) {
28 29 30
     *     // compute value
     *     return $value;
     * }
Qiang Xue committed
31
     * ```
32 33 34 35 36 37 38
     */
    public $value;
    /**
     * @var boolean this property is overwritten to be false so that this validator will
     * be applied when the value being validated is empty.
     */
    public $skipOnEmpty = false;
w  
Qiang Xue committed
39

40

41 42 43
    /**
     * @inheritdoc
     */
Qiang Xue committed
44
    public function validateAttribute($model, $attribute)
45
    {
Qiang Xue committed
46
        if ($this->isEmpty($model->$attribute)) {
47
            if ($this->value instanceof \Closure) {
Qiang Xue committed
48
                $model->$attribute = call_user_func($this->value, $model, $attribute);
49
            } else {
Qiang Xue committed
50
                $model->$attribute = $this->value;
51
            }
52 53
        }
    }
w  
Qiang Xue committed
54
}