50 lines
1.3 KiB
PHP
50 lines
1.3 KiB
PHP
<?php
|
|
|
|
declare(strict_types=1);
|
|
|
|
namespace App\Rules;
|
|
|
|
use Closure;
|
|
use Illuminate\Contracts\Validation\ValidationRule;
|
|
use Illuminate\Support\Str;
|
|
use Illuminate\Support\Stringable;
|
|
|
|
class MaxStrippedLength implements ValidationRule
|
|
{
|
|
public function __construct(
|
|
protected int $max,
|
|
protected bool $decodeEntities = true
|
|
) {
|
|
}
|
|
|
|
/** @param Closure(string, ?string=): \Illuminate\Translation\PotentiallyTranslatedString $fail */
|
|
public function validate(string $attribute, mixed $value, Closure $fail): void
|
|
{
|
|
if (! is_string($value)) {
|
|
return;
|
|
}
|
|
|
|
$length = Str::of($value)
|
|
->stripTags()
|
|
->when(
|
|
$this->decodeEntities,
|
|
fn (Stringable $str) => $str->pipe(
|
|
fn (Stringable $s) => html_entity_decode(
|
|
$s->value(),
|
|
ENT_QUOTES | ENT_HTML5,
|
|
'UTF-8'
|
|
)
|
|
)
|
|
)
|
|
->replace("\r\n", "\n")
|
|
->trim()
|
|
->length('UTF-8');
|
|
|
|
if ($length > $this->max) {
|
|
$fail('validation.max.string')->translate([
|
|
'attribute' => $attribute,
|
|
'max' => $this->max,
|
|
]);
|
|
}
|
|
}
|
|
}
|