0 follower

Final Class Yiisoft\Validator\EmptyCondition\WhenEmpty

InheritanceYiisoft\Validator\EmptyCondition\WhenEmpty

Empty condition is a callable returning true if a value must be considered empty.

With WhenEmpty, a value is considered empty only when it is either:

  • Not passed at all.
  • null.
  • An empty string (not trimmed by default).
  • An empty iterable.

With regard to validation process, a corresponding rule is skipped only if this condition is met and WhenEmpty is set:

  • At a rule level via $skipOnEmpty property, but only for rules implementing {@see \Yiisoft\Validator\EmptyCondition\SkipOnEmptyTrait} / including {@see \Yiisoft\Validator\EmptyCondition\SkipOnEmptyTrait}.
  • At validator level ({@see \Yiisoft\Validator\EmptyCondition\Validator::$defaultSkipOnEmptyCondition}).

A shortcut for new WhenEmpty() is true (string is not trimmed). If you want a string to be trimmed before checking, use new WhenEmpty(trimString: false).

Method Details

Hide inherited methods

__construct() public method

public mixed __construct ( boolean $trimString false )
$trimString boolean

                public function __construct(
    /*
     * @var bool Whether to trim string (both from the start and from the end) before checking. Defaults to `false`
     * meaning no trimming is done.
     */
    private readonly bool $trimString = false,
) {}

            
__invoke() public method

public boolean __invoke ( mixed $value, boolean $isPropertyMissing false )
$value mixed

The validated value.

$isPropertyMissing boolean

A flag defining whether the property is missing (not used / not passed at all).

return boolean

Whether the validated value is considered empty.

                public function __invoke(mixed $value, bool $isPropertyMissing = false): bool
{
    if ($isPropertyMissing || $value === null) {
        return true;
    }
    if (is_string($value)) {
        if ($this->trimString) {
            $value = trim($value);
        }
        return $value === '';
    }
    if (is_iterable($value)) {
        foreach ($value as $_item) {
            return false;
        }
        return true;
    }
    return false;
}