0 follower

Final Class Yiisoft\Validator\Rule\Compare

InheritanceYiisoft\Validator\Rule\Compare » Yiisoft\Validator\Rule\AbstractCompare
ImplementsYiisoft\Validator\DumpedRuleInterface, Yiisoft\Validator\SkipOnEmptyInterface, Yiisoft\Validator\SkipOnErrorInterface, Yiisoft\Validator\WhenInterface
Uses TraitsYiisoft\Validator\Rule\Trait\SkipOnEmptyTrait, Yiisoft\Validator\Rule\Trait\SkipOnErrorTrait, Yiisoft\Validator\Rule\Trait\WhenTrait

Defines validation options to compare the specified value with "target" value provided directly ({@see GreaterThanOrEqual::$targetValue}) or within a property ({@see GreaterThanOrEqual::$targetProperty}).

The default comparison is based on number values (including float values). It's also possible to compare values as strings byte by byte and compare original values as is. See {@see \Yiisoft\Validator\Rule\GreaterThanOrEqual::$type} for all possible options.

It supports different comparison operators, specified via the {@see \Yiisoft\Validator\Rule\Compare::$operator}.

There are shortcut classes to use instead of specifying operator manually:

  • {@see \Yiisoft\Validator\Rule\Equal} is a shortcut for new Compare(operator: '==') and new Compare(operator: '===').
  • {@see \Yiisoft\Validator\Rule\NotEqual} is a shortcut for new Compare(operator: '!=') and new Compare(operator: '!==').
  • {@see \Yiisoft\Validator\Rule\GreaterThan} is a shortcut for new Compare(operator: '>').
  • {@see \Yiisoft\Validator\Rule\GreaterThanOrEqual} is a shortcut for new Compare(operator: '>=').
  • {@see \Yiisoft\Validator\Rule\LessThan} is a shortcut for new Compare(operator: '<').
  • {@see \Yiisoft\Validator\Rule\LessThanOrEqual} is a shortcut for new Compare(operator: '<=').

See also Yiisoft\Validator\Rule\CompareHandler.

Public Methods

Hide inherited methods

Method Description Defined By
__construct() Yiisoft\Validator\Rule\AbstractCompare
getHandler() Yiisoft\Validator\Rule\AbstractCompare
getIncorrectDataSetTypeMessage() Get message used when the value returned from a custom data set s not scalar. Yiisoft\Validator\Rule\AbstractCompare
getIncorrectInputMessage() Get message used when the input is incorrect. Yiisoft\Validator\Rule\AbstractCompare
getMessage() Get a message used when the value is not valid. Yiisoft\Validator\Rule\AbstractCompare
getName() Yiisoft\Validator\Rule\AbstractCompare
getOperator() Get the operator for comparison. Yiisoft\Validator\Rule\AbstractCompare
getOptions() Yiisoft\Validator\Rule\AbstractCompare
getSkipOnEmpty() A getter for $skipOnEmpty property. Yiisoft\Validator\Rule\Trait\SkipOnEmptyTrait
getTargetProperty() Get the name of the property to be compared with. Yiisoft\Validator\Rule\AbstractCompare
getTargetValue() Get value to be compared with. Yiisoft\Validator\Rule\AbstractCompare
getType() Get the type of the values being compared. Yiisoft\Validator\Rule\AbstractCompare
getWhen() A getter for $when property. Yiisoft\Validator\Rule\Trait\WhenTrait
shouldSkipOnError() A getter for $skipOnError property. Yiisoft\Validator\Rule\Trait\SkipOnErrorTrait
skipOnEmpty() An immutable setter to change $skipOnEmpty property. Yiisoft\Validator\Rule\Trait\SkipOnEmptyTrait
skipOnError() An immutable setter to change $skipOnError property. Yiisoft\Validator\Rule\Trait\SkipOnErrorTrait
when() An immutable setter to change $when property. Yiisoft\Validator\Rule\Trait\WhenTrait

Constants

Hide inherited constants

Constant Value Description Defined By
DEFAULT_INCORRECT_DATA_SET_TYPE_MESSAGE '{Property} returned from a custom data set must have ' . 'one of the following types: integer, float, string, boolean, null or an object implementing \Stringable ' . 'interface or \DateTimeInterface.' A default for {@see $incorrectDataSetTypeMessage}. Yiisoft\Validator\Rule\AbstractCompare
DEFAULT_INCORRECT_INPUT_MESSAGE 'The allowed types for {property} are integer, float, string, ' . 'boolean, null and object implementing \Stringable interface or \DateTimeInterface. {type} given.' A default for {@see $incorrectInputMessage}. Yiisoft\Validator\Rule\AbstractCompare
VALID_OPERATORS_MAP [ '==' => 1, '===' => 1, '!=' => 1, '!==' => 1, '>' => 1, '>=' => 1, '<' => 1, '<=' => 1, ] Map of valid operators. It's used instead of a list for better performance. Yiisoft\Validator\Rule\AbstractCompare
VALID_TYPES [ \Yiisoft\Validator\Rule\CompareType::ORIGINAL, \Yiisoft\Validator\Rule\CompareType::STRING, \Yiisoft\Validator\Rule\CompareType::NUMBER, ] List of valid types. Yiisoft\Validator\Rule\AbstractCompare

Method Details

Hide inherited methods

__construct() public method
public mixed __construct ( mixed $targetValue null, string|null $targetProperty null, string $incorrectInputMessage self::DEFAULT_INCORRECT_INPUT_MESSAGE, string $incorrectDataSetTypeMessage self::DEFAULT_INCORRECT_DATA_SET_TYPE_MESSAGE, string|null $message null, string $type CompareType::NUMBER, string $operator '==', boolean|callable|null $skipOnEmpty null, boolean $skipOnError false, Closure|null $when null )
$targetValue mixed

The value to be compared with. When both this property and {@see $targetProperty} are set, this property takes precedence.

$targetProperty string|null

The name of the property to be compared with. When both this property and {@see $targetValue} are set, the {@see $targetValue} takes precedence.

$incorrectInputMessage string

A message used when the input is incorrect.

You may use the following placeholders in the message:

  • {property}: the translated label of the property being validated.
  • {type}: the type of the value being validated.
$incorrectDataSetTypeMessage string

A message used when the value returned from a custom data set is neither scalar nor null.

You may use the following placeholders in the message:

  • {type}: type of the value.
$message string|null

A message used when the value is not valid.

You may use the following placeholders in the message:

  • {property}: the translated label of the property being validated.
  • {targetValue}: the value to be compared with.
  • {targetProperty}: the name of the property to be compared with.
  • {targetPropertyValue}: the value extracted from the property to be compared with if this property was set.
  • {targetValueOrProperty}: the value to be compared with or, if it's absent, the name of the property to be compared with.
  • {value}: the value being validated.

When {@see \Yiisoft\Validator\Rule\CompareType::ORIGINAL} is used with complex types (neither scalar nor null), {targetValue}, {targetPropertyValue} and {targetValueOrProperty} parameters might contain the actual type instead of the value, e.g. "object" for predictable formatting.

$type string

The type of the values being compared:

  • {@see \Yiisoft\Validator\Rule\CompareType::NUMBER} - default, both values will be converted to float numbers before comparison.
  • {@see \Yiisoft\Validator\Rule\CompareType::ORIGINAL} - compare the values as is.
  • {@see \Yiisoft\Validator\Rule\CompareType::STRING} - cast both values to strings before comparison.

{@see \Yiisoft\Validator\Rule\CompareType::NUMBER} and {@see \Yiisoft\Validator\Rule\CompareType::STRING} allow only scalar and null values, also objects implementing {@see \Stringable} interface or {@see \DateTimeInterface} (validated values must be in Unix Timestamp format).

{@see \Yiisoft\Validator\Rule\CompareType::ORIGINAL} allows any values. All PHP comparison rules apply here, see comparison operators - {@see https://www.php.net/manual/en/language.operators.comparison.php} and PHP type comparison tables - {@see https://www.php.net/manual/en/types.comparisons.php} sections in official PHP documentation.

$operator string

The operator for comparison. The following operators are supported:

  • ==: check if two values are equal. The comparison is done in non-strict mode.
  • ===: check if two values are equal. The comparison is done in strict mode.
  • !=: check if two values are NOT equal. The comparison is done in non-strict mode.
  • !==: check if two values are NOT equal. The comparison is done in strict mode.
  • >: check if value being validated is greater than the value being compared with.
  • >=: check if value being validated is greater than or equal to the value being compared with.
  • <: check if value being validated is less than the value being compared with.
  • <=: check if value being validated is less than or equal to the value being compared with.
$skipOnEmpty boolean|callable|null

Whether to skip this rule if the value validated is empty. See {@see \Yiisoft\Validator\SkipOnEmptyInterface}.

$skipOnError boolean

Whether to skip this rule if any of the previous rules gave an error. See {@see \Yiisoft\Validator\SkipOnErrorInterface}.

$when Closure|null

A callable to define a condition for applying the rule. See {@see \Yiisoft\Validator\WhenInterface}.

                public function __construct(
    private mixed $targetValue = null,
    private ?string $targetProperty = null,
    private string $incorrectInputMessage = self::DEFAULT_INCORRECT_INPUT_MESSAGE,
    private string $incorrectDataSetTypeMessage = self::DEFAULT_INCORRECT_DATA_SET_TYPE_MESSAGE,
    private ?string $message = null,
    private string $type = CompareType::NUMBER,
    private string $operator = '==',
    bool|callable|null $skipOnEmpty = null,
    private bool $skipOnError = false,
    private ?Closure $when = null,
) {
    if (!in_array($this->type, self::VALID_TYPES)) {
        $validTypesString = $this->getQuotedList(self::VALID_TYPES);
        $message = "Type \"$this->type\" is not supported. The valid types are: $validTypesString.";
        throw new InvalidArgumentException($message);
    }
    if (!isset(self::VALID_OPERATORS_MAP[$this->operator])) {
        $validOperators = array_keys(self::VALID_OPERATORS_MAP);
        $validOperatorsString = $this->getQuotedList($validOperators);
        $message = "Operator \"$operator\" is not supported. The valid operators are: $validOperatorsString.";
        throw new InvalidArgumentException($message);
    }
    $this->skipOnEmpty = $skipOnEmpty;
}

            
getHandler() public method
public string getHandler ( )

                public function getHandler(): string
{
    return CompareHandler::class;
}

            
getIncorrectDataSetTypeMessage() public method

Defined in: Yiisoft\Validator\Rule\AbstractCompare::getIncorrectDataSetTypeMessage()

Get message used when the value returned from a custom data set s not scalar.

public string getIncorrectDataSetTypeMessage ( )
return string

Error message.

                public function getIncorrectDataSetTypeMessage(): string
{
    return $this->incorrectDataSetTypeMessage;
}

            
getIncorrectInputMessage() public method

Defined in: Yiisoft\Validator\Rule\AbstractCompare::getIncorrectInputMessage()

Get message used when the input is incorrect.

public string getIncorrectInputMessage ( )
return string

Error message.

                public function getIncorrectInputMessage(): string
{
    return $this->incorrectInputMessage;
}

            
getMessage() public method

Defined in: Yiisoft\Validator\Rule\AbstractCompare::getMessage()

Get a message used when the value is not valid.

public string getMessage ( )
return string

Error message.

                public function getMessage(): string
{
    return $this->message ?? match ($this->operator) {
        '==', => '{Property} must be equal to "{targetValueOrProperty}".',
        '===' => '{Property} must be strictly equal to "{targetValueOrProperty}".',
        '!=' => '{Property} must not be equal to "{targetValueOrProperty}".',
        '!==' => '{Property} must not be strictly equal to "{targetValueOrProperty}".',
        '>' => '{Property} must be greater than "{targetValueOrProperty}".',
        '>=' => '{Property} must be greater than or equal to "{targetValueOrProperty}".',
        '<' => '{Property} must be less than "{targetValueOrProperty}".',
        '<=' => '{Property} must be less than or equal to "{targetValueOrProperty}".',
    };
}

            
getName() public method
public string getName ( )

                public function getName(): string
{
    return static::class;
}

            
getOperator() public method

Defined in: Yiisoft\Validator\Rule\AbstractCompare::getOperator()

Get the operator for comparison.

public string getOperator ( )
return string

The operator for comparison.

                public function getOperator(): string
{
    return $this->operator;
}

            
getOptions() public method
public array getOptions ( )

                public function getOptions(): array
{
    $isTargetValueSimple = $this->targetValue === null || is_scalar($this->targetValue);
    if (!$isTargetValueSimple) {
        $messageParameters = ['targetProperty' => $this->targetProperty];
    } else {
        $messageParameters = [
            'targetValue' => $this->targetValue,
            'targetProperty' => $this->targetProperty,
            'targetValueOrProperty' => $this->targetProperty ?? $this->targetValue,
        ];
    }
    $options = [
        'targetProperty' => $this->targetProperty,
        'incorrectInputMessage' => [
            'template' => $this->incorrectInputMessage,
            'parameters' => $messageParameters,
        ],
        'incorrectDataSetTypeMessage' => [
            'template' => $this->incorrectDataSetTypeMessage,
            'parameters' => $messageParameters,
        ],
        'message' => [
            'template' => $this->getMessage(),
            'parameters' => $messageParameters,
        ],
        'type' => $this->type,
        'operator' => $this->operator,
        'skipOnEmpty' => $this->getSkipOnEmptyOption(),
        'skipOnError' => $this->skipOnError,
    ];
    if (!$isTargetValueSimple) {
        return $options;
    }
    return array_merge(['targetValue' => $this->targetValue], $options);
}

            
getSkipOnEmpty() public method

Defined in: Yiisoft\Validator\Rule\Trait\SkipOnEmptyTrait::getSkipOnEmpty()

A getter for $skipOnEmpty property.

public boolean|callable|null getSkipOnEmpty ( )
return boolean|callable|null

A current raw (non-normalized) value.

                public function getSkipOnEmpty(): bool|callable|null
{
    return $this->skipOnEmpty;
}

            
getTargetProperty() public method

Defined in: Yiisoft\Validator\Rule\AbstractCompare::getTargetProperty()

Get the name of the property to be compared with.

public string|null getTargetProperty ( )
return string|null

Name of the property to be compared with or null if it was not configured.

                public function getTargetProperty(): ?string
{
    return $this->targetProperty;
}

            
getTargetValue() public method

Defined in: Yiisoft\Validator\Rule\AbstractCompare::getTargetValue()

Get value to be compared with.

public mixed getTargetValue ( )
return mixed

Value to be compared with or null if it was not configured.

                public function getTargetValue(): mixed
{
    return $this->targetValue;
}

            
getType() public method

Defined in: Yiisoft\Validator\Rule\AbstractCompare::getType()

Get the type of the values being compared.

public string getType ( )
return string

The type of the values being compared. Either {@see \Yiisoft\Validator\Rule\CompareType::STRING} or {@see \Yiisoft\Validator\Rule\CompareType::NUMBER}.

                public function getType(): string
{
    return $this->type;
}

            
getWhen() public method

Defined in: Yiisoft\Validator\Rule\Trait\WhenTrait::getWhen()

A getter for $when property.

public Closure|null getWhen ( )
return Closure|null

Current value:

  • null - always apply the validation.
  • callable - apply the validation depending on a return value: true - apply, false - do not apply.

                public function getWhen(): ?Closure
{
    return $this->when;
}

            
shouldSkipOnError() public method

Defined in: Yiisoft\Validator\Rule\Trait\SkipOnErrorTrait::shouldSkipOnError()

A getter for $skipOnError property.

public boolean shouldSkipOnError ( )
return boolean

Current value. true means to skip the current rule when the previous one errored and false - do not skip.

                public function shouldSkipOnError(): bool
{
    return $this->skipOnError;
}

            
skipOnEmpty() public method

Defined in: Yiisoft\Validator\Rule\Trait\SkipOnEmptyTrait::skipOnEmpty()

An immutable setter to change $skipOnEmpty property.

public $this skipOnEmpty ( boolean|callable|null $value )
$value boolean|callable|null

A new value.

return $this

The new instance with a changed value.

                public function skipOnEmpty(bool|callable|null $value): static
{
    $new = clone $this;
    $new->skipOnEmpty = $value;
    return $new;
}

            
skipOnError() public method

Defined in: Yiisoft\Validator\Rule\Trait\SkipOnErrorTrait::skipOnError()

An immutable setter to change $skipOnError property.

public $this skipOnError ( boolean $value )
$value boolean

A new value. true means to skip the current rule when the previous one errored and false - do not skip.

return $this

The new instance with a changed value.

                public function skipOnError(bool $value): static
{
    $new = clone $this;
    $new->skipOnError = $value;
    return $new;
}

            
when() public method

Defined in: Yiisoft\Validator\Rule\Trait\WhenTrait::when()

An immutable setter to change $when property.

public $this when ( Closure|null $value )
$value Closure|null

A new value:

  • null - always apply the validation.
  • callable - apply the validation depending on a return value: true - apply, false - do not apply.
return $this

The new instance with a changed value.

                public function when(?Closure $value): static
{
    $new = clone $this;
    $new->when = $value;
    return $new;
}