|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace Arifszn\AdvancedValidation\Rules; |
| 4 | + |
| 5 | +use Illuminate\Contracts\Validation\Rule; |
| 6 | +use Illuminate\Support\Facades\Validator; |
| 7 | + |
| 8 | +/** |
| 9 | + * The field under validation must be divisible by the given number. |
| 10 | + * |
| 11 | + * @package Arifszn\AdvancedValidation\Rules |
| 12 | + */ |
| 13 | +class DivisibleBy implements Rule |
| 14 | +{ |
| 15 | + /** |
| 16 | + * @var string |
| 17 | + */ |
| 18 | + private $errorMessage; |
| 19 | + |
| 20 | + /** |
| 21 | + * @var int |
| 22 | + */ |
| 23 | + private $number; |
| 24 | + |
| 25 | + /** |
| 26 | + * @var string |
| 27 | + */ |
| 28 | + private $attribute; |
| 29 | + |
| 30 | + /** |
| 31 | + * Create a new rule instance. |
| 32 | + * |
| 33 | + * @param int $number Divisible by number. |
| 34 | + * @param string|null $errorMessage Custom error message. |
| 35 | + * @return void |
| 36 | + */ |
| 37 | + public function __construct(int $number, string $errorMessage = null) |
| 38 | + { |
| 39 | + $this->number = $number; |
| 40 | + $this->errorMessage = $errorMessage; |
| 41 | + } |
| 42 | + |
| 43 | + /** |
| 44 | + * Determine if the validation rule passes. |
| 45 | + * |
| 46 | + * @param string $attribute |
| 47 | + * @param mixed $value |
| 48 | + * @return bool |
| 49 | + */ |
| 50 | + public function passes($attribute, $value) |
| 51 | + { |
| 52 | + $this->attribute = $attribute; |
| 53 | + |
| 54 | + $floatValidation = Validator::make( |
| 55 | + ['float' => $value], |
| 56 | + ['float' => ['required', new FloatNumber()]], |
| 57 | + ); |
| 58 | + |
| 59 | + return !$floatValidation->fails() && (fmod(floatval($value), intval($this->number, 10)) === 0.0); |
| 60 | + } |
| 61 | + |
| 62 | + /** |
| 63 | + * Get the validation error message. |
| 64 | + * |
| 65 | + * @return string |
| 66 | + */ |
| 67 | + public function message() |
| 68 | + { |
| 69 | + return $this->errorMessage ? $this->errorMessage : trans('advancedValidation::validation.divisible_by', [ |
| 70 | + 'attribute' => $this->attribute, |
| 71 | + 'number' => $this->number |
| 72 | + ]); |
| 73 | + } |
| 74 | +} |
0 commit comments