master

laravel/framework

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

ProhibitedIf.php

TLDR

The ProhibitedIf.php file in the Demo Projects project contains a class called ProhibitedIf that implements the Stringable interface. This class represents a prohibited validation rule based on a condition.

Classes

ProhibitedIf

The ProhibitedIf class is a validation rule that is used to determine if an attribute should be prohibited based on a given condition. It has the following properties:

  • condition: A closure or boolean value that represents the condition that validates the attribute.

The ProhibitedIf class provides the following methods:

  • __construct($condition): A constructor method that initializes the condition property. It accepts a closure or boolean value as the condition.
  • __toString(): A method that converts the rule to a validation string. It returns the string 'prohibited' if the condition is met, otherwise it returns an empty string.
<?php

namespace Illuminate\Validation\Rules;

use Closure;
use InvalidArgumentException;
use Stringable;

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

    /**
     * Create a new prohibited 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) ? 'prohibited' : '';
        }

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