master

laravel/framework

Last updated at: 29/12/2023 09:30

ExcludeIf.php

TLDR

This file contains a class called ExcludeIf that is used to create a validation rule based on a condition. The class implements the Stringable interface.

Classes

ExcludeIf

The ExcludeIf class represents a validation rule that excludes a value from validation if a condition is met. It has the following properties:

  • condition: The condition that validates the attribute. It can be a closure or a boolean.

The ExcludeIf class has the following methods:

  • __construct($condition): Initializes a new instance of the ExcludeIf class with the provided condition. The condition must be a callable or a boolean.
  • __toString(): Converts the rule to a validation string. If the condition is callable, it calls the function and returns "exclude" if the condition is true. Otherwise, it returns "exclude" if the condition is true, and an empty string otherwise.
<?php

namespace Illuminate\Validation\Rules;

use Closure;
use InvalidArgumentException;
use Stringable;

class ExcludeIf implements Stringable
{
    /**
     * The condition that validates the attribute.
     *
     * @var \Closure|bool
     */
    public $condition;

    /**
     * Create a new exclude validation rule based on a condition.
     *
     * @param  \Closure|bool  $condition
     * @return void
     *
     * @throws \InvalidArgumentException
     */
    public function __construct($condition)
    {
        if ($condition instanceof Closure || is_bool($condition)) {
            $this->condition = $condition;
        } else {
            throw new InvalidArgumentException('The provided condition must be a callable or boolean.');
        }
    }

    /**
     * Convert the rule to a validation string.
     *
     * @return string
     */
    public function __toString()
    {
        if (is_callable($this->condition)) {
            return call_user_func($this->condition) ? 'exclude' : '';
        }

        return $this->condition ? 'exclude' : '';
    }
}