EmailParser.php 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. <?php
  2. namespace Egulias\EmailValidator;
  3. use Egulias\EmailValidator\Result\Result;
  4. use Egulias\EmailValidator\Parser\LocalPart;
  5. use Egulias\EmailValidator\Parser\DomainPart;
  6. use Egulias\EmailValidator\Result\ValidEmail;
  7. use Egulias\EmailValidator\Result\InvalidEmail;
  8. use Egulias\EmailValidator\Warning\EmailTooLong;
  9. use Egulias\EmailValidator\Result\Reason\NoLocalPart;
  10. class EmailParser extends Parser
  11. {
  12. public const EMAIL_MAX_LENGTH = 254;
  13. /**
  14. * @var string
  15. */
  16. protected $domainPart = '';
  17. /**
  18. * @var string
  19. */
  20. protected $localPart = '';
  21. public function parse(string $str) : Result
  22. {
  23. $result = parent::parse($str);
  24. $this->addLongEmailWarning($this->localPart, $this->domainPart);
  25. return $result;
  26. }
  27. protected function preLeftParsing(): Result
  28. {
  29. if (!$this->hasAtToken()) {
  30. return new InvalidEmail(new NoLocalPart(), $this->lexer->token["value"]);
  31. }
  32. return new ValidEmail();
  33. }
  34. protected function parseLeftFromAt(): Result
  35. {
  36. return $this->processLocalPart();
  37. }
  38. protected function parseRightFromAt(): Result
  39. {
  40. return $this->processDomainPart();
  41. }
  42. private function processLocalPart() : Result
  43. {
  44. $localPartParser = new LocalPart($this->lexer);
  45. $localPartResult = $localPartParser->parse();
  46. $this->localPart = $localPartParser->localPart();
  47. $this->warnings = array_merge($localPartParser->getWarnings(), $this->warnings);
  48. return $localPartResult;
  49. }
  50. private function processDomainPart() : Result
  51. {
  52. $domainPartParser = new DomainPart($this->lexer);
  53. $domainPartResult = $domainPartParser->parse();
  54. $this->domainPart = $domainPartParser->domainPart();
  55. $this->warnings = array_merge($domainPartParser->getWarnings(), $this->warnings);
  56. return $domainPartResult;
  57. }
  58. public function getDomainPart() : string
  59. {
  60. return $this->domainPart;
  61. }
  62. public function getLocalPart() : string
  63. {
  64. return $this->localPart;
  65. }
  66. private function addLongEmailWarning(string $localPart, string $parsedDomainPart) : void
  67. {
  68. if (strlen($localPart . '@' . $parsedDomainPart) > self::EMAIL_MAX_LENGTH) {
  69. $this->warnings[EmailTooLong::CODE] = new EmailTooLong();
  70. }
  71. }
  72. }