| 1 |
<?php |
| 2 |
|
| 3 |
namespace Rakit\Validation\Rules; |
| 4 |
|
| 5 |
use Rakit\Validation\Rule; |
| 6 |
use InvalidArgumentException; |
| 7 |
use Closure; |
| 8 |
|
| 9 |
class Callback extends Rule |
| 10 |
{ |
| 11 |
|
| 12 |
/** @var string */ |
| 13 |
protected $message = "The :attribute is not valid"; |
| 14 |
|
| 15 |
/** @var array */ |
| 16 |
protected $fillableParams = ['callback']; |
| 17 |
|
| 18 |
/** |
| 19 |
* Set the Callback closure |
| 20 |
* |
| 21 |
* @param Closure $callback |
| 22 |
* @return self |
| 23 |
*/ |
| 24 |
public function setCallback(Closure $callback): Rule |
| 25 |
{ |
| 26 |
return $this->setParameter('callback', $callback); |
| 27 |
} |
| 28 |
|
| 29 |
/** |
| 30 |
* Check the $value is valid |
| 31 |
* |
| 32 |
* @param mixed $value |
| 33 |
* @return bool |
| 34 |
* @throws \Exception |
| 35 |
*/ |
| 36 |
public function check($value): bool |
| 37 |
{ |
| 38 |
$this->requireParameters($this->fillableParams); |
| 39 |
|
| 40 |
$callback = $this->parameter('callback'); |
| 41 |
if (false === $callback instanceof Closure) { |
| 42 |
$key = $this->attribute->getKey(); |
| 43 |
throw new InvalidArgumentException("Callback rule for '{$key}' is not callable."); |
| 44 |
} |
| 45 |
|
| 46 |
$callback = $callback->bindTo($this); |
| 47 |
$invalidMessage = $callback($value); |
| 48 |
|
| 49 |
if (is_string($invalidMessage)) { |
| 50 |
$this->setMessage($invalidMessage); |
| 51 |
return false; |
| 52 |
} elseif (false === $invalidMessage) { |
| 53 |
return false; |
| 54 |
} |
| 55 |
|
| 56 |
return true; |
| 57 |
} |
| 58 |
} |
| 59 |
|