When.php 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  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\AlwaysInvalidException;
  9. use Respect\Validation\Validatable;
  10. /**
  11. * A ternary validator that accepts three parameters.
  12. *
  13. * @author Alexandre Gomes Gaigalas <alganet@gmail.com>
  14. * @author Danilo Correa <danilosilva87@gmail.com>
  15. * @author Henrique Moody <henriquemoody@gmail.com>
  16. * @author Hugo Hamon <hugo.hamon@sensiolabs.com>
  17. */
  18. final class When extends AbstractRule
  19. {
  20. /**
  21. * @var Validatable
  22. */
  23. private $when;
  24. /**
  25. * @var Validatable
  26. */
  27. private $then;
  28. /**
  29. * @var Validatable
  30. */
  31. private $else;
  32. public function __construct(Validatable $when, Validatable $then, ?Validatable $else = null)
  33. {
  34. $this->when = $when;
  35. $this->then = $then;
  36. if ($else === null) {
  37. $else = new AlwaysInvalid();
  38. $else->setTemplate(AlwaysInvalidException::SIMPLE);
  39. }
  40. $this->else = $else;
  41. }
  42. /**
  43. * {@inheritDoc}
  44. */
  45. public function validate($input): bool
  46. {
  47. if ($this->when->validate($input)) {
  48. return $this->then->validate($input);
  49. }
  50. return $this->else->validate($input);
  51. }
  52. /**
  53. * {@inheritDoc}
  54. */
  55. public function assert($input): void
  56. {
  57. if ($this->when->validate($input)) {
  58. $this->then->assert($input);
  59. return;
  60. }
  61. $this->else->assert($input);
  62. }
  63. /**
  64. * {@inheritDoc}
  65. */
  66. public function check($input): void
  67. {
  68. if ($this->when->validate($input)) {
  69. $this->then->check($input);
  70. return;
  71. }
  72. $this->else->check($input);
  73. }
  74. }