master

laravel/framework

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

Enum.php

TLDR

This file contains a class called Enum that implements the Rule and ValidatorAwareRule interfaces. The Enum class is used to validate if a given value is an instance of a specified enum type.

Methods

There are no additional methods in this file.

Classes

Enum

The Enum class is used to validate if a given value is an instance of a specified enum type. It implements the Rule and ValidatorAwareRule interfaces.

Some notable properties of this class are:

  • $type: specifies the type of the enum being validated.
  • $validator: the current validator instance.

Some notable methods of this class are:

  • __construct($type): constructor method that sets the $type property to the provided type.
  • passes($attribute, $value): method used to determine if the validation rule passes. It checks if the value is an instance of the specified enum type, by using the tryFrom method of the type.
  • message(): method used to get the validation error message.
  • setValidator($validator): method used to set the current validator instance.
<?php

namespace Illuminate\Validation\Rules;

use Illuminate\Contracts\Validation\Rule;
use Illuminate\Contracts\Validation\ValidatorAwareRule;
use TypeError;

class Enum implements Rule, ValidatorAwareRule
{
    /**
     * The type of the enum.
     *
     * @var string
     */
    protected $type;

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

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

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

        if (is_null($value) || ! enum_exists($this->type) || ! method_exists($this->type, 'tryFrom')) {
            return false;
        }

        try {
            return ! is_null($this->type::tryFrom($value));
        } catch (TypeError) {
            return false;
        }
    }

    /**
     * Get the validation error message.
     *
     * @return array
     */
    public function message()
    {
        $message = $this->validator->getTranslator()->get('validation.enum');

        return $message === 'validation.enum'
            ? ['The selected :attribute is invalid.']
            : $message;
    }

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

        return $this;
    }
}