DefaultValueValidator.php 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. <?php
  2. /**
  3. * @link http://www.yiiframework.com/
  4. * @copyright Copyright (c) 2008 Yii Software LLC
  5. * @license http://www.yiiframework.com/license/
  6. */
  7. namespace yii\validators;
  8. /**
  9. * DefaultValueValidator sets the attribute to be the specified default value.
  10. *
  11. * DefaultValueValidator is not really a validator. It is provided mainly to allow
  12. * specifying attribute default values when they are empty.
  13. *
  14. * @author Qiang Xue <qiang.xue@gmail.com>
  15. * @since 2.0
  16. */
  17. class DefaultValueValidator extends Validator
  18. {
  19. /**
  20. * @var mixed the default value or an anonymous function that returns the default value which will
  21. * be assigned to the attributes being validated if they are empty. The signature of the anonymous function
  22. * should be as follows,
  23. *
  24. * ```php
  25. * function($model, $attribute) {
  26. * // compute value
  27. * return $value;
  28. * }
  29. * ```
  30. */
  31. public $value;
  32. /**
  33. * @var bool this property is overwritten to be false so that this validator will
  34. * be applied when the value being validated is empty.
  35. */
  36. public $skipOnEmpty = false;
  37. /**
  38. * {@inheritdoc}
  39. */
  40. public function validateAttribute($model, $attribute)
  41. {
  42. if ($this->isEmpty($model->$attribute)) {
  43. if ($this->value instanceof \Closure) {
  44. $model->$attribute = call_user_func($this->value, $model, $attribute);
  45. } else {
  46. $model->$attribute = $this->value;
  47. }
  48. }
  49. }
  50. }