Call.php 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  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 Respect\Validation\Exceptions\ValidationException;
  9. use Respect\Validation\Validatable;
  10. use Throwable;
  11. use function call_user_func;
  12. use function restore_error_handler;
  13. use function set_error_handler;
  14. /**
  15. * Validates the return of a callable for a given input.
  16. *
  17. * @author Alexandre Gomes Gaigalas <alganet@gmail.com>
  18. * @author Emmerson Siqueira <emmersonsiqueira@gmail.com>
  19. * @author Henrique Moody <henriquemoody@gmail.com>
  20. */
  21. final class Call extends AbstractRule
  22. {
  23. /**
  24. * @var callable
  25. */
  26. private $callable;
  27. /**
  28. * @var Validatable
  29. */
  30. private $rule;
  31. /**
  32. * Initializes the rule with the callable to be executed after the input is passed.
  33. */
  34. public function __construct(callable $callable, Validatable $rule)
  35. {
  36. $this->callable = $callable;
  37. $this->rule = $rule;
  38. }
  39. /**
  40. * {@inheritDoc}
  41. */
  42. public function assert($input): void
  43. {
  44. $this->setErrorHandler($input);
  45. try {
  46. $this->rule->assert(call_user_func($this->callable, $input));
  47. } catch (ValidationException $exception) {
  48. throw $exception;
  49. } catch (Throwable $throwable) {
  50. throw $this->reportError($input);
  51. } finally {
  52. restore_error_handler();
  53. }
  54. }
  55. /**
  56. * {@inheritDoc}
  57. */
  58. public function check($input): void
  59. {
  60. $this->setErrorHandler($input);
  61. try {
  62. $this->rule->check(call_user_func($this->callable, $input));
  63. } catch (ValidationException $exception) {
  64. throw $exception;
  65. } catch (Throwable $throwable) {
  66. throw $this->reportError($input);
  67. } finally {
  68. restore_error_handler();
  69. }
  70. }
  71. /**
  72. * {@inheritDoc}
  73. */
  74. public function validate($input): bool
  75. {
  76. try {
  77. $this->check($input);
  78. } catch (ValidationException $exception) {
  79. return false;
  80. }
  81. return true;
  82. }
  83. /**
  84. * @param mixed $input
  85. */
  86. private function setErrorHandler($input): void
  87. {
  88. set_error_handler(function () use ($input): void {
  89. throw $this->reportError($input);
  90. });
  91. }
  92. }