master

laravel/framework

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

NestedRules.php

TLDR

This file contains a class called NestedRules that is used for compiling nested validation rules into an array.

Methods

__construct(callable $callback)

This method is the constructor for the NestedRules class. It takes a callback as a parameter.

compile($attribute, $value, $data = null)

This method compiles the callback into an array of rules. It takes three parameters: $attribute, $value, and $data. It returns an instance of \stdClass.

Classes

NestedRules

This class is used for compiling nested validation rules into an array. It has two properties: $callback and $parser. The $callback property is a callback function that is used to compile the rules. The $parser property is an instance of the ValidationRuleParser class.

<?php

namespace Illuminate\Validation;

use Illuminate\Support\Arr;

class NestedRules
{
    /**
     * The callback to execute.
     *
     * @var callable
     */
    protected $callback;

    /**
     * Create a new nested rule instance.
     *
     * @param  callable  $callback
     * @return void
     */
    public function __construct(callable $callback)
    {
        $this->callback = $callback;
    }

    /**
     * Compile the callback into an array of rules.
     *
     * @param  string  $attribute
     * @param  mixed  $value
     * @param  mixed  $data
     * @return \stdClass
     */
    public function compile($attribute, $value, $data = null)
    {
        $rules = call_user_func($this->callback, $value, $attribute, $data);

        $parser = new ValidationRuleParser(
            Arr::undot(Arr::wrap($data))
        );

        if (is_array($rules) && ! array_is_list($rules)) {
            $nested = [];

            foreach ($rules as $key => $rule) {
                $nested[$attribute.'.'.$key] = $rule;
            }

            $rules = $nested;
        } else {
            $rules = [$attribute => $rules];
        }

        return $parser->explode(ValidationRuleParser::filterConditionalRules($rules, $data));
    }
}