MultipleValidationWithAnd.php 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111
  1. <?php
  2. namespace Egulias\EmailValidator\Validation;
  3. use Egulias\EmailValidator\EmailLexer;
  4. use Egulias\EmailValidator\Validation\Exception\EmptyValidationList;
  5. class MultipleValidationWithAnd implements EmailValidation
  6. {
  7. /**
  8. * If one of validations gets failure skips all succeeding validation.
  9. * This means MultipleErrors will only contain a single error which first found.
  10. */
  11. const STOP_ON_ERROR = 0;
  12. /**
  13. * All of validations will be invoked even if one of them got failure.
  14. * So MultipleErrors will contain all causes.
  15. */
  16. const ALLOW_ALL_ERRORS = 1;
  17. /**
  18. * @var EmailValidation[]
  19. */
  20. private $validations = [];
  21. /**
  22. * @var array
  23. */
  24. private $warnings = [];
  25. /**
  26. * @var MultipleErrors
  27. */
  28. private $error;
  29. /**
  30. * @var bool
  31. */
  32. private $mode;
  33. /**
  34. * @param EmailValidation[] $validations The validations.
  35. * @param int $mode The validation mode (one of the constants).
  36. */
  37. public function __construct(array $validations, $mode = self::ALLOW_ALL_ERRORS)
  38. {
  39. if (count($validations) == 0) {
  40. throw new EmptyValidationList();
  41. }
  42. $this->validations = $validations;
  43. $this->mode = $mode;
  44. }
  45. /**
  46. * {@inheritdoc}
  47. */
  48. public function isValid($email, EmailLexer $emailLexer)
  49. {
  50. $result = true;
  51. $errors = [];
  52. foreach ($this->validations as $validation) {
  53. $emailLexer->reset();
  54. $validationResult = $validation->isValid($email, $emailLexer);
  55. $result = $result && $validationResult;
  56. $this->warnings = array_merge($this->warnings, $validation->getWarnings());
  57. $errors = $this->addNewError($validation->getError(), $errors);
  58. if ($this->shouldStop($result)) {
  59. break;
  60. }
  61. }
  62. if (!empty($errors)) {
  63. $this->error = new MultipleErrors($errors);
  64. }
  65. return $result;
  66. }
  67. private function addNewError($possibleError, array $errors)
  68. {
  69. if (null !== $possibleError) {
  70. $errors[] = $possibleError;
  71. }
  72. return $errors;
  73. }
  74. private function shouldStop($result)
  75. {
  76. return !$result && $this->mode === self::STOP_ON_ERROR;
  77. }
  78. /**
  79. * {@inheritdoc}
  80. */
  81. public function getError()
  82. {
  83. return $this->error;
  84. }
  85. /**
  86. * {@inheritdoc}
  87. */
  88. public function getWarnings()
  89. {
  90. return $this->warnings;
  91. }
  92. }