ldc-legaulois/app/Rules/WysiwygLength.php
2026-09-25 16:25:31 +02:00

75 lines
2.3 KiB
PHP

<?php
namespace App\Rules;
use Illuminate\Contracts\Validation\ValidationRule;
use Illuminate\Support\Str;
/**
* Check the length of a Wysiwyg field, excluding tags and end spaces.
*/
class WysiwygLength implements ValidationRule
{
/**
* Construct method.
*
* @param int $min The minimum length of the content (excluding tags). Default is 15.
* @param int|null $max The maximum length of the content (excluding tags).
* Default is null (max will be defined by the type of the column in DB).
* @return void
*
* @throws \InvalidArgumentException If $max < $min.
*/
public function __construct(private int $min = 15, private ?int $max = null)
{
if ($max !== null && $max < $min && $min < 0) {
throw new \InvalidArgumentException(sprintf(
'$max should be higher than $min. $max = %d. $min = %d.',
$max,
$min
));
}
}
/**
* Run the validation rule.
*/
public function validate(string $attribute, mixed $value, \Closure $fail): void
{
$length = Str::length(\strip_tags($value));
$translatedAttribute = self::getTranslatedAttribute($attribute);
if (! \is_null($this->max) and ! ($length >= $this->min && $length <= $this->max)) {
$fail(trans('validation.between.string', [
'attribute' => $translatedAttribute,
'min' => $this->min,
'max' => $this->max,
]));
return;
}
if ($length < $this->min) {
$fail(trans('validation.min.string', [
'attribute' => $translatedAttribute,
'min' => $this->min,
]));
}
}
/**
* Get the correct translation for the given attrribute.
*/
private static function getTranslatedAttribute(string $attribute): string
{
/** @var \Illuminate\Translation\Translator $trans */
$trans = trans();
if ($trans->has('validation.attributes.' . $attribute)) {
return trans('validation.attributes.' . $attribute);
}
if ($trans->has('validation.custom.' . $attribute)) {
return trans('validation.custom.' . $attribute);
}
return $attribute;
}
}