master

laravel/framework

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

ClosureValidationRule.php

TLDR

The file ClosureValidationRule.php is a part of the Illuminate\Validation namespace in the Demo Projects project. This file contains a class named ClosureValidationRule, which is a validation rule implementation that takes a closure as a callback for validation logic.

Methods

__construct

This method is the constructor for the ClosureValidationRule class. It accepts a closure as a parameter and assigns it to the $callback property.

passes

This method is used to determine if the validation rule passes. It takes an attribute and a value as parameters and invokes the closure callback provided in the constructor. If the callback returns false, the validation is considered failed.

message

This method returns the validation error messages.

setValidator

This method is used to set the current validator for the ClosureValidationRule instance.

Classes

There are no additional classes in this file.

<?php

namespace Illuminate\Validation;

use Illuminate\Contracts\Validation\Rule as RuleContract;
use Illuminate\Contracts\Validation\ValidatorAwareRule;
use Illuminate\Translation\CreatesPotentiallyTranslatedStrings;

class ClosureValidationRule implements RuleContract, ValidatorAwareRule
{
    use CreatesPotentiallyTranslatedStrings;

    /**
     * The callback that validates the attribute.
     *
     * @var \Closure
     */
    public $callback;

    /**
     * Indicates if the validation callback failed.
     *
     * @var bool
     */
    public $failed = false;

    /**
     * The validation error messages.
     *
     * @var array
     */
    public $messages = [];

    /**
     * The current validator.
     *
     * @var \Illuminate\Validation\Validator
     */
    protected $validator;

    /**
     * Create a new Closure based validation rule.
     *
     * @param  \Closure  $callback
     * @return void
     */
    public function __construct($callback)
    {
        $this->callback = $callback;
    }

    /**
     * Determine if the validation rule passes.
     *
     * @param  string  $attribute
     * @param  mixed  $value
     * @return bool
     */
    public function passes($attribute, $value)
    {
        $this->failed = false;

        $this->callback->__invoke($attribute, $value, function ($attribute, $message = null) {
            $this->failed = true;

            return $this->pendingPotentiallyTranslatedString($attribute, $message);
        }, $this->validator);

        return ! $this->failed;
    }

    /**
     * Get the validation error messages.
     *
     * @return string
     */
    public function message()
    {
        return $this->messages;
    }

    /**
     * Set the current validator.
     *
     * @param  \Illuminate\Validation\Validator  $validator
     * @return $this
     */
    public function setValidator($validator)
    {
        $this->validator = $validator;

        return $this;
    }
}