Created
February 21, 2023 05:11
-
-
Save ohryan/26578fe213d3f430c414b70ea914df0d to your computer and use it in GitHub Desktop.
Validate a list a comma-seperated list against an Enum
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace App\Rules; | |
use Illuminate\Contracts\Validation\Rule; | |
class EnumList implements Rule | |
{ | |
private $enumClass; | |
public function __construct($enumClass) | |
{ | |
$this->enumClass = $enumClass; | |
} | |
public function passes($attribute, $value): bool | |
{ | |
$validValues = []; | |
foreach ($this->enumClass::cases() as $enum) { | |
$validValues[$enum->name] = $enum->value; | |
} | |
$inputValues = collect(explode(',', $value))->map(fn ($v) => trim($v)); | |
return $inputValues->diff(collect($validValues))->isEmpty(); | |
} | |
public function message(): string | |
{ | |
return "The :attribute values are not valid."; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment