EmailParser.php 2.4 KB

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