ldc-supportweb/app/Rules/Hex.php
2025-03-07 10:28:17 +00:00

76 lines
1.8 KiB
PHP

<?php
namespace App\Rules;
use Illuminate\Contracts\Validation\ValidationRule;
class Hex implements ValidationRule
{
/**
* @var boolean
*/
protected $forceFull;
/**
* @var boolean
*/
protected $allowAlpha;
/**
* __construct method
*
* @param boolean $forceFull
* @param boolean $allowAlpha
*
* @return void
*/
public function __construct(bool $forceFull = false, bool $allowAlpha = false)
{
$this->forceFull = $forceFull;
$this->allowAlpha = $allowAlpha;
}
/**
* Run the validation rule.
*
* @param string $attribute
* @param mixed $value
* @param \Closure(string):\Illuminate\Translation\PotentiallyTranslatedString $fail
* @return void
* @phpcs:disable Generic.CodeAnalysis.UnusedFunctionParameter.FoundInImplementedInterfaceBeforeLastUsed
* @phpcs:disable Squiz.Commenting.FunctionComment.IncorrectTypeHint
*/
public function validate(string $attribute, mixed $value, \Closure $fail): void
{
$pattern = '/^#([a-fA-F0-9]{6}';
if (!$this->forceFull) {
$pattern .= '|[a-fA-F0-9]{3}';
}
if ($this->allowAlpha) {
$pattern .= '|[a-fA-F0-9]{8}';
if (!$this->forceFull) {
$pattern .= '|[a-fA-F0-9]{4}';
}
}
$pattern .= ')$/';
if (!(bool)preg_match($pattern, $value)) {
$fail(trans($this->message()));
}
}
/**
* Get the validation error message.
*
* @return string
*/
public function message(): string
{
return 'The hex code is not valid';
}
}