Callback.php 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. <?php
  2. /*
  3. * Copyright (c) Alexandre Gomes Gaigalas <alganet@gmail.com>
  4. * SPDX-License-Identifier: MIT
  5. */
  6. declare(strict_types=1);
  7. namespace Respect\Validation\Rules;
  8. use function array_merge;
  9. use function call_user_func_array;
  10. use function count;
  11. /**
  12. * Validates the input using the return of a given callable.
  13. *
  14. * @author Alexandre Gomes Gaigalas <alganet@gmail.com>
  15. * @author Henrique Moody <henriquemoody@gmail.com>
  16. * @author William Espindola <oi@williamespindola.com.br>
  17. */
  18. final class Callback extends AbstractRule
  19. {
  20. /**
  21. * @var callable
  22. */
  23. private $callback;
  24. /**
  25. * @var mixed[]
  26. */
  27. private $arguments;
  28. /**
  29. * Initializes the rule.
  30. *
  31. * @param mixed ...$arguments
  32. */
  33. public function __construct(callable $callback, ...$arguments)
  34. {
  35. $this->callback = $callback;
  36. $this->arguments = $arguments;
  37. }
  38. /**
  39. * {@inheritDoc}
  40. */
  41. public function validate($input): bool
  42. {
  43. return (bool) call_user_func_array($this->callback, $this->getArguments($input));
  44. }
  45. /**
  46. * @param mixed $input
  47. * @return mixed[]
  48. */
  49. private function getArguments($input): array
  50. {
  51. $arguments = [$input];
  52. if (count($this->arguments) === 0) {
  53. return $arguments;
  54. }
  55. return array_merge($arguments, $this->arguments);
  56. }
  57. }