| 1 |
<?php |
| 2 |
|
| 3 |
namespace FluentCart\App\Http\Rules; |
| 4 |
|
| 5 |
use FluentCart\Framework\Support\Arr; |
| 6 |
|
| 7 |
class MaxLengthRule |
| 8 |
{ |
| 9 |
public function __invoke($attr, $value, $rules, $data, ...$params) |
| 10 |
{ |
| 11 |
|
| 12 |
|
| 13 |
$value = trim($value); |
| 14 |
if (is_numeric($value)) { |
| 15 |
$value = (string)$value; |
| 16 |
} |
| 17 |
|
| 18 |
if(!is_string($value)) { |
| 19 |
return sprintf( |
| 20 |
/* translators: 1: attribute name */ |
| 21 |
__('The %s must be a valid text', 'fluent-cart'), |
| 22 |
$attr |
| 23 |
); |
| 24 |
} |
| 25 |
|
| 26 |
$maxLength = Arr::get($params, '0', 254); |
| 27 |
|
| 28 |
if(strlen($value) > $maxLength) { |
| 29 |
return sprintf( |
| 30 |
/* translators: 1: attribute name, 2: max length */ |
| 31 |
__('The %1$s must not be greater than %2$s characters.', 'fluent-cart'), |
| 32 |
$attr, |
| 33 |
$maxLength |
| 34 |
); |
| 35 |
} |
| 36 |
|
| 37 |
return null; |
| 38 |
} |
| 39 |
|
| 40 |
/** |
| 41 |
* Build a closure rule that reuses this rule's length check but returns |
| 42 |
* a caller-supplied message on failure instead of the generic one. |
| 43 |
* Validator::validateAttribute() uses a closure rule's own return value |
| 44 |
* as the final error message, bypassing messages() entirely — the only |
| 45 |
* message channel that Validator::extend()-registered rules honor. |
| 46 |
* |
| 47 |
* @param int $maxLength |
| 48 |
* @param string $message |
| 49 |
* @return \Closure |
| 50 |
*/ |
| 51 |
public static function withMessage($maxLength, $message) |
| 52 |
{ |
| 53 |
return function ($attribute, $value, $rules, $data) use ($maxLength, $message) { |
| 54 |
$error = (new static())($attribute, $value, $rules, $data, $maxLength); |
| 55 |
|
| 56 |
return $error ? $message : null; |
| 57 |
}; |
| 58 |
} |
| 59 |
} |
| 60 |
|