EmailParser.php 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. <?php
  2. namespace Egulias\EmailValidator;
  3. use Egulias\EmailValidator\Exception\ExpectingATEXT;
  4. use Egulias\EmailValidator\Exception\NoLocalPart;
  5. use Egulias\EmailValidator\Parser\DomainPart;
  6. use Egulias\EmailValidator\Parser\LocalPart;
  7. use Egulias\EmailValidator\Warning\EmailTooLong;
  8. /**
  9. * EmailParser
  10. *
  11. * @author Eduardo Gulias Davis <me@egulias.com>
  12. */
  13. class EmailParser
  14. {
  15. const EMAIL_MAX_LENGTH = 254;
  16. protected $warnings;
  17. protected $domainPart = '';
  18. protected $localPart = '';
  19. protected $lexer;
  20. protected $localPartParser;
  21. protected $domainPartParser;
  22. public function __construct(EmailLexer $lexer)
  23. {
  24. $this->lexer = $lexer;
  25. $this->localPartParser = new LocalPart($this->lexer);
  26. $this->domainPartParser = new DomainPart($this->lexer);
  27. $this->warnings = new \SplObjectStorage();
  28. }
  29. /**
  30. * @param string $str
  31. * @return array
  32. */
  33. public function parse($str)
  34. {
  35. $this->lexer->setInput($str);
  36. if (!$this->hasAtToken()) {
  37. throw new NoLocalPart();
  38. }
  39. $this->localPartParser->parse($str);
  40. $this->domainPartParser->parse($str);
  41. $this->setParts($str);
  42. if ($this->lexer->hasInvalidTokens()) {
  43. throw new ExpectingATEXT();
  44. }
  45. return array('local' => $this->localPart, 'domain' => $this->domainPart);
  46. }
  47. public function getWarnings()
  48. {
  49. $localPartWarnings = $this->localPartParser->getWarnings();
  50. $domainPartWarnings = $this->domainPartParser->getWarnings();
  51. $this->warnings = array_merge($localPartWarnings, $domainPartWarnings);
  52. $this->addLongEmailWarning($this->localPart, $this->domainPart);
  53. return $this->warnings;
  54. }
  55. public function getParsedDomainPart()
  56. {
  57. return $this->domainPart;
  58. }
  59. protected function setParts($email)
  60. {
  61. $parts = explode('@', $email);
  62. $this->domainPart = $this->domainPartParser->getDomainPart();
  63. $this->localPart = $parts[0];
  64. }
  65. protected function hasAtToken()
  66. {
  67. $this->lexer->moveNext();
  68. $this->lexer->moveNext();
  69. if ($this->lexer->token['type'] === EmailLexer::S_AT) {
  70. return false;
  71. }
  72. return true;
  73. }
  74. /**
  75. * @param string $localPart
  76. * @param string $parsedDomainPart
  77. */
  78. protected function addLongEmailWarning($localPart, $parsedDomainPart)
  79. {
  80. if (strlen($localPart . '@' . $parsedDomainPart) > self::EMAIL_MAX_LENGTH) {
  81. $this->warnings[EmailTooLong::CODE] = new EmailTooLong();
  82. }
  83. }
  84. }