AbstractRule.php 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126
  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\Factory;
  10. use Respect\Validation\Validatable;
  11. /**
  12. * @author Alexandre Gomes Gaigalas <alganet@gmail.com>
  13. * @author Henrique Moody <henriquemoody@gmail.com>
  14. * @author Nick Lombard <github@jigsoft.co.za>
  15. * @author Vicente Mendoza <vicentemmor@yahoo.com.mx>
  16. */
  17. abstract class AbstractRule implements Validatable
  18. {
  19. /**
  20. * @var string|null
  21. */
  22. protected $default;
  23. /**
  24. * @var bool|false
  25. */
  26. protected $defaultType;
  27. /**
  28. * @var string|null
  29. */
  30. protected $name;
  31. /**
  32. * @var string|null
  33. */
  34. protected $template;
  35. /**
  36. * {@inheritDoc}
  37. */
  38. public function assert($input): void
  39. {
  40. if ($this->validate($input)) {
  41. return;
  42. }
  43. throw $this->reportError($input);
  44. }
  45. /**
  46. * {@inheritDoc}
  47. */
  48. public function check($input): void
  49. {
  50. $this->assert($input);
  51. }
  52. /**
  53. * {@inheritDoc}
  54. */
  55. public function getName(): ?string
  56. {
  57. return $this->name;
  58. }
  59. /**
  60. * {@inheritDoc}
  61. */
  62. public function reportError($input, array $extraParams = []): ValidationException
  63. {
  64. return Factory::getDefaultInstance()->exception($this, $input, $extraParams);
  65. }
  66. /**
  67. * {@inheritDoc}
  68. */
  69. public function setName(string $name): Validatable
  70. {
  71. $this->name = $name;
  72. return $this;
  73. }
  74. /**
  75. * {@inheritDoc}
  76. */
  77. public function setTemplate(string $template): Validatable
  78. {
  79. $this->template = $template;
  80. return $this;
  81. }
  82. /**
  83. * {@inheritDoc}
  84. */
  85. public function getDefault(): ?string
  86. {
  87. return $this->default;
  88. }
  89. /**
  90. * {@inheritDoc}
  91. */
  92. public function getDefaultType(): ?bool
  93. {
  94. return $this->defaultType;
  95. }
  96. public function setDefault(string $default, bool $defaultType=false): Validatable
  97. {
  98. $this->default = $default;
  99. $this->defaultType = $defaultType;
  100. return $this;
  101. }
  102. /**
  103. * @param mixed$input
  104. */
  105. public function __invoke($input): bool
  106. {
  107. return $this->validate($input);
  108. }
  109. }