ldc-volena/app/Rules/WysiwygLength.php
2024-07-24 12:19:47 +02:00

83 lines
2.5 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.
*
* @package App\Rules
*/
class WysiwygLength implements ValidationRule
{
/**
* Construct method.
*
* @param integer $min The minimum length of the content (excluding tags). Default is 15.
* @param integer|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|null $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.
*
* @param string $attribute
* @param mixed $value
* @param \Closure $fail
*
* @return void
*/
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.
*
* @param string $attribute
* @return string
*/
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;
}
}