master

laravel/framework

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

In.php

TLDR

This file contains the implementation of the In class, which is a rule used in validation. The class implements the Stringable interface and has a constructor and a __toString method.

Classes

In

The In class represents a rule used in validation. It implements the Stringable interface and has the following properties and methods:

Properties

  • $rule: The name of the rule.
  • $values: The accepted values.

Methods

  • __construct($values): Creates a new In rule instance. The $values parameter can be an instance of Illuminate\Contracts\Support\Arrayable, an array, or a string.
  • __toString(): Converts the rule to a validation string.
<?php

namespace Illuminate\Validation\Rules;

use BackedEnum;
use Illuminate\Contracts\Support\Arrayable;
use Stringable;
use UnitEnum;

class In implements Stringable
{
    /**
     * The name of the rule.
     *
     * @var string
     */
    protected $rule = 'in';

    /**
     * The accepted values.
     *
     * @var array
     */
    protected $values;

    /**
     * Create a new in rule instance.
     *
     * @param  \Illuminate\Contracts\Support\Arrayable|array|string  $values
     * @return void
     */
    public function __construct($values)
    {
        if ($values instanceof Arrayable) {
            $values = $values->toArray();
        }

        $this->values = is_array($values) ? $values : func_get_args();
    }

    /**
     * Convert the rule to a validation string.
     *
     * @return string
     *
     * @see \Illuminate\Validation\ValidationRuleParser::parseParameters
     */
    public function __toString()
    {
        $values = array_map(function ($value) {
            $value = match (true) {
                $value instanceof BackedEnum => $value->value,
                $value instanceof UnitEnum => $value->name,
                default => $value,
            };

            return '"'.str_replace('"', '""', $value).'"';
        }, $this->values);

        return $this->rule.':'.implode(',', $values);
    }
}