This commit is contained in:
TiclemFR
2023-12-29 16:00:02 +01:00
parent 9d79d7c0c6
commit 884eb3011a
8361 changed files with 1160554 additions and 4 deletions

View File

@@ -0,0 +1,102 @@
<?php
namespace Egulias\EmailValidator\Parser;
use Egulias\EmailValidator\EmailLexer;
use Egulias\EmailValidator\Result\Result;
use Egulias\EmailValidator\Warning\QuotedPart;
use Egulias\EmailValidator\Result\InvalidEmail;
use Egulias\EmailValidator\Parser\CommentStrategy\CommentStrategy;
use Egulias\EmailValidator\Result\Reason\UnclosedComment;
use Egulias\EmailValidator\Result\Reason\UnOpenedComment;
use Egulias\EmailValidator\Warning\Comment as WarningComment;
class Comment extends PartParser
{
/**
* @var int
*/
private $openedParenthesis = 0;
/**
* @var CommentStrategy
*/
private $commentStrategy;
public function __construct(EmailLexer $lexer, CommentStrategy $commentStrategy)
{
$this->lexer = $lexer;
$this->commentStrategy = $commentStrategy;
}
public function parse(): Result
{
if ($this->lexer->current->isA(EmailLexer::S_OPENPARENTHESIS)) {
$this->openedParenthesis++;
if ($this->noClosingParenthesis()) {
return new InvalidEmail(new UnclosedComment(), $this->lexer->current->value);
}
}
if ($this->lexer->current->isA(EmailLexer::S_CLOSEPARENTHESIS)) {
return new InvalidEmail(new UnOpenedComment(), $this->lexer->current->value);
}
$this->warnings[WarningComment::CODE] = new WarningComment();
$moreTokens = true;
while ($this->commentStrategy->exitCondition($this->lexer, $this->openedParenthesis) && $moreTokens) {
if ($this->lexer->isNextToken(EmailLexer::S_OPENPARENTHESIS)) {
$this->openedParenthesis++;
}
$this->warnEscaping();
if ($this->lexer->isNextToken(EmailLexer::S_CLOSEPARENTHESIS)) {
$this->openedParenthesis--;
}
$moreTokens = $this->lexer->moveNext();
}
if ($this->openedParenthesis >= 1) {
return new InvalidEmail(new UnclosedComment(), $this->lexer->current->value);
}
if ($this->openedParenthesis < 0) {
return new InvalidEmail(new UnOpenedComment(), $this->lexer->current->value);
}
$finalValidations = $this->commentStrategy->endOfLoopValidations($this->lexer);
$this->warnings = [...$this->warnings, ...$this->commentStrategy->getWarnings()];
return $finalValidations;
}
/**
* @return void
*/
private function warnEscaping(): void
{
//Backslash found
if (!$this->lexer->current->isA(EmailLexer::S_BACKSLASH)) {
return;
}
if (!$this->lexer->isNextTokenAny(array(EmailLexer::S_SP, EmailLexer::S_HTAB, EmailLexer::C_DEL))) {
return;
}
$this->warnings[QuotedPart::CODE] =
new QuotedPart($this->lexer->getPrevious()->type, $this->lexer->current->type);
}
private function noClosingParenthesis(): bool
{
try {
$this->lexer->find(EmailLexer::S_CLOSEPARENTHESIS);
return false;
} catch (\RuntimeException $e) {
return true;
}
}
}

View File

@@ -0,0 +1,22 @@
<?php
namespace Egulias\EmailValidator\Parser\CommentStrategy;
use Egulias\EmailValidator\EmailLexer;
use Egulias\EmailValidator\Result\Result;
use Egulias\EmailValidator\Warning\Warning;
interface CommentStrategy
{
/**
* Return "true" to continue, "false" to exit
*/
public function exitCondition(EmailLexer $lexer, int $openedParenthesis): bool;
public function endOfLoopValidations(EmailLexer $lexer): Result;
/**
* @return Warning[]
*/
public function getWarnings(): array;
}

View File

@@ -0,0 +1,33 @@
<?php
namespace Egulias\EmailValidator\Parser\CommentStrategy;
use Egulias\EmailValidator\EmailLexer;
use Egulias\EmailValidator\Result\Result;
use Egulias\EmailValidator\Result\ValidEmail;
use Egulias\EmailValidator\Result\InvalidEmail;
use Egulias\EmailValidator\Result\Reason\ExpectingATEXT;
class DomainComment implements CommentStrategy
{
public function exitCondition(EmailLexer $lexer, int $openedParenthesis): bool
{
return !($openedParenthesis === 0 && $lexer->isNextToken(EmailLexer::S_DOT));
}
public function endOfLoopValidations(EmailLexer $lexer): Result
{
//test for end of string
if (!$lexer->isNextToken(EmailLexer::S_DOT)) {
return new InvalidEmail(new ExpectingATEXT('DOT not found near CLOSEPARENTHESIS'), $lexer->current->value);
}
//add warning
//Address is valid within the message but cannot be used unmodified for the envelope
return new ValidEmail();
}
public function getWarnings(): array
{
return [];
}
}

View File

@@ -0,0 +1,37 @@
<?php
namespace Egulias\EmailValidator\Parser\CommentStrategy;
use Egulias\EmailValidator\EmailLexer;
use Egulias\EmailValidator\Result\Result;
use Egulias\EmailValidator\Result\ValidEmail;
use Egulias\EmailValidator\Warning\CFWSNearAt;
use Egulias\EmailValidator\Result\InvalidEmail;
use Egulias\EmailValidator\Result\Reason\ExpectingATEXT;
class LocalComment implements CommentStrategy
{
/**
* @var array
*/
private $warnings = [];
public function exitCondition(EmailLexer $lexer, int $openedParenthesis): bool
{
return !$lexer->isNextToken(EmailLexer::S_AT);
}
public function endOfLoopValidations(EmailLexer $lexer): Result
{
if (!$lexer->isNextToken(EmailLexer::S_AT)) {
return new InvalidEmail(new ExpectingATEXT('ATEX is not expected after closing comments'), $lexer->current->value);
}
$this->warnings[CFWSNearAt::CODE] = new CFWSNearAt();
return new ValidEmail();
}
public function getWarnings(): array
{
return $this->warnings;
}
}

View File

@@ -0,0 +1,210 @@
<?php
namespace Egulias\EmailValidator\Parser;
use Egulias\EmailValidator\EmailLexer;
use Egulias\EmailValidator\Result\Result;
use Egulias\EmailValidator\Result\ValidEmail;
use Egulias\EmailValidator\Result\InvalidEmail;
use Egulias\EmailValidator\Warning\CFWSWithFWS;
use Egulias\EmailValidator\Warning\IPV6BadChar;
use Egulias\EmailValidator\Result\Reason\CRNoLF;
use Egulias\EmailValidator\Warning\IPV6ColonEnd;
use Egulias\EmailValidator\Warning\IPV6MaxGroups;
use Egulias\EmailValidator\Warning\ObsoleteDTEXT;
use Egulias\EmailValidator\Warning\AddressLiteral;
use Egulias\EmailValidator\Warning\IPV6ColonStart;
use Egulias\EmailValidator\Warning\IPV6Deprecated;
use Egulias\EmailValidator\Warning\IPV6GroupCount;
use Egulias\EmailValidator\Warning\IPV6DoubleColon;
use Egulias\EmailValidator\Result\Reason\ExpectingDTEXT;
use Egulias\EmailValidator\Result\Reason\UnusualElements;
use Egulias\EmailValidator\Warning\DomainLiteral as WarningDomainLiteral;
class DomainLiteral extends PartParser
{
public const IPV4_REGEX = '/\\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/';
public const OBSOLETE_WARNINGS = [
EmailLexer::INVALID,
EmailLexer::C_DEL,
EmailLexer::S_LF,
EmailLexer::S_BACKSLASH
];
public function parse(): Result
{
$this->addTagWarnings();
$IPv6TAG = false;
$addressLiteral = '';
do {
if ($this->lexer->current->isA(EmailLexer::C_NUL)) {
return new InvalidEmail(new ExpectingDTEXT(), $this->lexer->current->value);
}
$this->addObsoleteWarnings();
if ($this->lexer->isNextTokenAny(array(EmailLexer::S_OPENBRACKET, EmailLexer::S_OPENBRACKET))) {
return new InvalidEmail(new ExpectingDTEXT(), $this->lexer->current->value);
}
if ($this->lexer->isNextTokenAny(
array(EmailLexer::S_HTAB, EmailLexer::S_SP, EmailLexer::CRLF)
)) {
$this->warnings[CFWSWithFWS::CODE] = new CFWSWithFWS();
$this->parseFWS();
}
if ($this->lexer->isNextToken(EmailLexer::S_CR)) {
return new InvalidEmail(new CRNoLF(), $this->lexer->current->value);
}
if ($this->lexer->current->isA(EmailLexer::S_BACKSLASH)) {
return new InvalidEmail(new UnusualElements($this->lexer->current->value), $this->lexer->current->value);
}
if ($this->lexer->current->isA(EmailLexer::S_IPV6TAG)) {
$IPv6TAG = true;
}
if ($this->lexer->current->isA(EmailLexer::S_CLOSEBRACKET)) {
break;
}
$addressLiteral .= $this->lexer->current->value;
} while ($this->lexer->moveNext());
//Encapsulate
$addressLiteral = str_replace('[', '', $addressLiteral);
$isAddressLiteralIPv4 = $this->checkIPV4Tag($addressLiteral);
if (!$isAddressLiteralIPv4) {
return new ValidEmail();
}
$addressLiteral = $this->convertIPv4ToIPv6($addressLiteral);
if (!$IPv6TAG) {
$this->warnings[WarningDomainLiteral::CODE] = new WarningDomainLiteral();
return new ValidEmail();
}
$this->warnings[AddressLiteral::CODE] = new AddressLiteral();
$this->checkIPV6Tag($addressLiteral);
return new ValidEmail();
}
/**
* @param string $addressLiteral
* @param int $maxGroups
*/
public function checkIPV6Tag($addressLiteral, $maxGroups = 8): void
{
$prev = $this->lexer->getPrevious();
if ($prev->isA(EmailLexer::S_COLON)) {
$this->warnings[IPV6ColonEnd::CODE] = new IPV6ColonEnd();
}
$IPv6 = substr($addressLiteral, 5);
//Daniel Marschall's new IPv6 testing strategy
$matchesIP = explode(':', $IPv6);
$groupCount = count($matchesIP);
$colons = strpos($IPv6, '::');
if (count(preg_grep('/^[0-9A-Fa-f]{0,4}$/', $matchesIP, PREG_GREP_INVERT)) !== 0) {
$this->warnings[IPV6BadChar::CODE] = new IPV6BadChar();
}
if ($colons === false) {
// We need exactly the right number of groups
if ($groupCount !== $maxGroups) {
$this->warnings[IPV6GroupCount::CODE] = new IPV6GroupCount();
}
return;
}
if ($colons !== strrpos($IPv6, '::')) {
$this->warnings[IPV6DoubleColon::CODE] = new IPV6DoubleColon();
return;
}
if ($colons === 0 || $colons === (strlen($IPv6) - 2)) {
// RFC 4291 allows :: at the start or end of an address
//with 7 other groups in addition
++$maxGroups;
}
if ($groupCount > $maxGroups) {
$this->warnings[IPV6MaxGroups::CODE] = new IPV6MaxGroups();
} elseif ($groupCount === $maxGroups) {
$this->warnings[IPV6Deprecated::CODE] = new IPV6Deprecated();
}
}
public function convertIPv4ToIPv6(string $addressLiteralIPv4): string
{
$matchesIP = [];
$IPv4Match = preg_match(self::IPV4_REGEX, $addressLiteralIPv4, $matchesIP);
// Extract IPv4 part from the end of the address-literal (if there is one)
if ($IPv4Match > 0) {
$index = (int) strrpos($addressLiteralIPv4, $matchesIP[0]);
//There's a match but it is at the start
if ($index > 0) {
// Convert IPv4 part to IPv6 format for further testing
return substr($addressLiteralIPv4, 0, $index) . '0:0';
}
}
return $addressLiteralIPv4;
}
/**
* @param string $addressLiteral
*
* @return bool
*/
protected function checkIPV4Tag($addressLiteral): bool
{
$matchesIP = [];
$IPv4Match = preg_match(self::IPV4_REGEX, $addressLiteral, $matchesIP);
// Extract IPv4 part from the end of the address-literal (if there is one)
if ($IPv4Match > 0) {
$index = strrpos($addressLiteral, $matchesIP[0]);
//There's a match but it is at the start
if ($index === 0) {
$this->warnings[AddressLiteral::CODE] = new AddressLiteral();
return false;
}
}
return true;
}
private function addObsoleteWarnings(): void
{
if (in_array($this->lexer->current->type, self::OBSOLETE_WARNINGS)) {
$this->warnings[ObsoleteDTEXT::CODE] = new ObsoleteDTEXT();
}
}
private function addTagWarnings(): void
{
if ($this->lexer->isNextToken(EmailLexer::S_COLON)) {
$this->warnings[IPV6ColonStart::CODE] = new IPV6ColonStart();
}
if ($this->lexer->isNextToken(EmailLexer::S_IPV6TAG)) {
$lexer = clone $this->lexer;
$lexer->moveNext();
if ($lexer->isNextToken(EmailLexer::S_DOUBLECOLON)) {
$this->warnings[IPV6ColonStart::CODE] = new IPV6ColonStart();
}
}
}
}

View File

@@ -0,0 +1,326 @@
<?php
namespace Egulias\EmailValidator\Parser;
use Doctrine\Common\Lexer\Token;
use Egulias\EmailValidator\EmailLexer;
use Egulias\EmailValidator\Warning\TLD;
use Egulias\EmailValidator\Result\Result;
use Egulias\EmailValidator\Result\ValidEmail;
use Egulias\EmailValidator\Result\InvalidEmail;
use Egulias\EmailValidator\Result\Reason\DotAtEnd;
use Egulias\EmailValidator\Result\Reason\DotAtStart;
use Egulias\EmailValidator\Warning\DeprecatedComment;
use Egulias\EmailValidator\Result\Reason\CRLFAtTheEnd;
use Egulias\EmailValidator\Result\Reason\LabelTooLong;
use Egulias\EmailValidator\Result\Reason\NoDomainPart;
use Egulias\EmailValidator\Result\Reason\ConsecutiveAt;
use Egulias\EmailValidator\Result\Reason\DomainTooLong;
use Egulias\EmailValidator\Result\Reason\CharNotAllowed;
use Egulias\EmailValidator\Result\Reason\DomainHyphened;
use Egulias\EmailValidator\Result\Reason\ExpectingATEXT;
use Egulias\EmailValidator\Parser\CommentStrategy\DomainComment;
use Egulias\EmailValidator\Result\Reason\ExpectingDomainLiteralClose;
use Egulias\EmailValidator\Parser\DomainLiteral as DomainLiteralParser;
class DomainPart extends PartParser
{
public const DOMAIN_MAX_LENGTH = 253;
public const LABEL_MAX_LENGTH = 63;
/**
* @var string
*/
protected $domainPart = '';
/**
* @var string
*/
protected $label = '';
public function parse(): Result
{
$this->lexer->clearRecorded();
$this->lexer->startRecording();
$this->lexer->moveNext();
$domainChecks = $this->performDomainStartChecks();
if ($domainChecks->isInvalid()) {
return $domainChecks;
}
if ($this->lexer->current->isA(EmailLexer::S_AT)) {
return new InvalidEmail(new ConsecutiveAt(), $this->lexer->current->value);
}
$result = $this->doParseDomainPart();
if ($result->isInvalid()) {
return $result;
}
$end = $this->checkEndOfDomain();
if ($end->isInvalid()) {
return $end;
}
$this->lexer->stopRecording();
$this->domainPart = $this->lexer->getAccumulatedValues();
$length = strlen($this->domainPart);
if ($length > self::DOMAIN_MAX_LENGTH) {
return new InvalidEmail(new DomainTooLong(), $this->lexer->current->value);
}
return new ValidEmail();
}
private function checkEndOfDomain(): Result
{
$prev = $this->lexer->getPrevious();
if ($prev->isA(EmailLexer::S_DOT)) {
return new InvalidEmail(new DotAtEnd(), $this->lexer->current->value);
}
if ($prev->isA(EmailLexer::S_HYPHEN)) {
return new InvalidEmail(new DomainHyphened('Hypen found at the end of the domain'), $prev->value);
}
if ($this->lexer->current->isA(EmailLexer::S_SP)) {
return new InvalidEmail(new CRLFAtTheEnd(), $prev->value);
}
return new ValidEmail();
}
private function performDomainStartChecks(): Result
{
$invalidTokens = $this->checkInvalidTokensAfterAT();
if ($invalidTokens->isInvalid()) {
return $invalidTokens;
}
$missingDomain = $this->checkEmptyDomain();
if ($missingDomain->isInvalid()) {
return $missingDomain;
}
if ($this->lexer->current->isA(EmailLexer::S_OPENPARENTHESIS)) {
$this->warnings[DeprecatedComment::CODE] = new DeprecatedComment();
}
return new ValidEmail();
}
private function checkEmptyDomain(): Result
{
$thereIsNoDomain = $this->lexer->current->isA(EmailLexer::S_EMPTY) ||
($this->lexer->current->isA(EmailLexer::S_SP) &&
!$this->lexer->isNextToken(EmailLexer::GENERIC));
if ($thereIsNoDomain) {
return new InvalidEmail(new NoDomainPart(), $this->lexer->current->value);
}
return new ValidEmail();
}
private function checkInvalidTokensAfterAT(): Result
{
if ($this->lexer->current->isA(EmailLexer::S_DOT)) {
return new InvalidEmail(new DotAtStart(), $this->lexer->current->value);
}
if ($this->lexer->current->isA(EmailLexer::S_HYPHEN)) {
return new InvalidEmail(new DomainHyphened('After AT'), $this->lexer->current->value);
}
return new ValidEmail();
}
protected function parseComments(): Result
{
$commentParser = new Comment($this->lexer, new DomainComment());
$result = $commentParser->parse();
$this->warnings = [...$this->warnings, ...$commentParser->getWarnings()];
return $result;
}
protected function doParseDomainPart(): Result
{
$tldMissing = true;
$hasComments = false;
$domain = '';
do {
$prev = $this->lexer->getPrevious();
$notAllowedChars = $this->checkNotAllowedChars($this->lexer->current);
if ($notAllowedChars->isInvalid()) {
return $notAllowedChars;
}
if (
$this->lexer->current->isA(EmailLexer::S_OPENPARENTHESIS) ||
$this->lexer->current->isA(EmailLexer::S_CLOSEPARENTHESIS)
) {
$hasComments = true;
$commentsResult = $this->parseComments();
//Invalid comment parsing
if ($commentsResult->isInvalid()) {
return $commentsResult;
}
}
$dotsResult = $this->checkConsecutiveDots();
if ($dotsResult->isInvalid()) {
return $dotsResult;
}
if ($this->lexer->current->isA(EmailLexer::S_OPENBRACKET)) {
$literalResult = $this->parseDomainLiteral();
$this->addTLDWarnings($tldMissing);
return $literalResult;
}
$labelCheck = $this->checkLabelLength();
if ($labelCheck->isInvalid()) {
return $labelCheck;
}
$FwsResult = $this->parseFWS();
if ($FwsResult->isInvalid()) {
return $FwsResult;
}
$domain .= $this->lexer->current->value;
if ($this->lexer->current->isA(EmailLexer::S_DOT) && $this->lexer->isNextToken(EmailLexer::GENERIC)) {
$tldMissing = false;
}
$exceptionsResult = $this->checkDomainPartExceptions($prev, $hasComments);
if ($exceptionsResult->isInvalid()) {
return $exceptionsResult;
}
$this->lexer->moveNext();
} while (!$this->lexer->current->isA(EmailLexer::S_EMPTY));
$labelCheck = $this->checkLabelLength(true);
if ($labelCheck->isInvalid()) {
return $labelCheck;
}
$this->addTLDWarnings($tldMissing);
$this->domainPart = $domain;
return new ValidEmail();
}
/**
* @param Token<int, string> $token
*
* @return Result
*/
private function checkNotAllowedChars(Token $token): Result
{
$notAllowed = [EmailLexer::S_BACKSLASH => true, EmailLexer::S_SLASH => true];
if (isset($notAllowed[$token->type])) {
return new InvalidEmail(new CharNotAllowed(), $token->value);
}
return new ValidEmail();
}
/**
* @return Result
*/
protected function parseDomainLiteral(): Result
{
try {
$this->lexer->find(EmailLexer::S_CLOSEBRACKET);
} catch (\RuntimeException $e) {
return new InvalidEmail(new ExpectingDomainLiteralClose(), $this->lexer->current->value);
}
$domainLiteralParser = new DomainLiteralParser($this->lexer);
$result = $domainLiteralParser->parse();
$this->warnings = [...$this->warnings, ...$domainLiteralParser->getWarnings()];
return $result;
}
/**
* @param Token<int, string> $prev
* @param bool $hasComments
*
* @return Result
*/
protected function checkDomainPartExceptions(Token $prev, bool $hasComments): Result
{
if ($this->lexer->current->isA(EmailLexer::S_OPENBRACKET) && $prev->type !== EmailLexer::S_AT) {
return new InvalidEmail(new ExpectingATEXT('OPENBRACKET not after AT'), $this->lexer->current->value);
}
if ($this->lexer->current->isA(EmailLexer::S_HYPHEN) && $this->lexer->isNextToken(EmailLexer::S_DOT)) {
return new InvalidEmail(new DomainHyphened('Hypen found near DOT'), $this->lexer->current->value);
}
if (
$this->lexer->current->isA(EmailLexer::S_BACKSLASH)
&& $this->lexer->isNextToken(EmailLexer::GENERIC)
) {
return new InvalidEmail(new ExpectingATEXT('Escaping following "ATOM"'), $this->lexer->current->value);
}
return $this->validateTokens($hasComments);
}
protected function validateTokens(bool $hasComments): Result
{
$validDomainTokens = array(
EmailLexer::GENERIC => true,
EmailLexer::S_HYPHEN => true,
EmailLexer::S_DOT => true,
);
if ($hasComments) {
$validDomainTokens[EmailLexer::S_OPENPARENTHESIS] = true;
$validDomainTokens[EmailLexer::S_CLOSEPARENTHESIS] = true;
}
if (!isset($validDomainTokens[$this->lexer->current->type])) {
return new InvalidEmail(new ExpectingATEXT('Invalid token in domain: ' . $this->lexer->current->value), $this->lexer->current->value);
}
return new ValidEmail();
}
private function checkLabelLength(bool $isEndOfDomain = false): Result
{
if ($this->lexer->current->isA(EmailLexer::S_DOT) || $isEndOfDomain) {
if ($this->isLabelTooLong($this->label)) {
return new InvalidEmail(new LabelTooLong(), $this->lexer->current->value);
}
$this->label = '';
}
$this->label .= $this->lexer->current->value;
return new ValidEmail();
}
private function isLabelTooLong(string $label): bool
{
if (preg_match('/[^\x00-\x7F]/', $label)) {
idn_to_ascii($label, IDNA_DEFAULT, INTL_IDNA_VARIANT_UTS46, $idnaInfo);
return (bool) ($idnaInfo['errors'] & IDNA_ERROR_LABEL_TOO_LONG);
}
return strlen($label) > self::LABEL_MAX_LENGTH;
}
private function addTLDWarnings(bool $isTLDMissing): void
{
if ($isTLDMissing) {
$this->warnings[TLD::CODE] = new TLD();
}
}
public function domainPart(): string
{
return $this->domainPart;
}
}

View File

@@ -0,0 +1,91 @@
<?php
namespace Egulias\EmailValidator\Parser;
use Egulias\EmailValidator\EmailLexer;
use Egulias\EmailValidator\Result\ValidEmail;
use Egulias\EmailValidator\Result\InvalidEmail;
use Egulias\EmailValidator\Warning\CFWSWithFWS;
use Egulias\EmailValidator\Warning\QuotedString;
use Egulias\EmailValidator\Result\Reason\ExpectingATEXT;
use Egulias\EmailValidator\Result\Reason\UnclosedQuotedString;
use Egulias\EmailValidator\Result\Result;
class DoubleQuote extends PartParser
{
public function parse(): Result
{
$validQuotedString = $this->checkDQUOTE();
if ($validQuotedString->isInvalid()) {
return $validQuotedString;
}
$special = [
EmailLexer::S_CR => true,
EmailLexer::S_HTAB => true,
EmailLexer::S_LF => true
];
$invalid = [
EmailLexer::C_NUL => true,
EmailLexer::S_HTAB => true,
EmailLexer::S_CR => true,
EmailLexer::S_LF => true
];
$setSpecialsWarning = true;
$this->lexer->moveNext();
while (!$this->lexer->current->isA(EmailLexer::S_DQUOTE) && !$this->lexer->current->isA(EmailLexer::S_EMPTY)) {
if (isset($special[$this->lexer->current->type]) && $setSpecialsWarning) {
$this->warnings[CFWSWithFWS::CODE] = new CFWSWithFWS();
$setSpecialsWarning = false;
}
if ($this->lexer->current->isA(EmailLexer::S_BACKSLASH) && $this->lexer->isNextToken(EmailLexer::S_DQUOTE)) {
$this->lexer->moveNext();
}
$this->lexer->moveNext();
if (!$this->escaped() && isset($invalid[$this->lexer->current->type])) {
return new InvalidEmail(new ExpectingATEXT("Expecting ATEXT between DQUOTE"), $this->lexer->current->value);
}
}
$prev = $this->lexer->getPrevious();
if ($prev->isA(EmailLexer::S_BACKSLASH)) {
$validQuotedString = $this->checkDQUOTE();
if ($validQuotedString->isInvalid()) {
return $validQuotedString;
}
}
if (!$this->lexer->isNextToken(EmailLexer::S_AT) && !$prev->isA(EmailLexer::S_BACKSLASH)) {
return new InvalidEmail(new ExpectingATEXT("Expecting ATEXT between DQUOTE"), $this->lexer->current->value);
}
return new ValidEmail();
}
protected function checkDQUOTE(): Result
{
$previous = $this->lexer->getPrevious();
if ($this->lexer->isNextToken(EmailLexer::GENERIC) && $previous->isA(EmailLexer::GENERIC)) {
$description = 'https://tools.ietf.org/html/rfc5322#section-3.2.4 - quoted string should be a unit';
return new InvalidEmail(new ExpectingATEXT($description), $this->lexer->current->value);
}
try {
$this->lexer->find(EmailLexer::S_DQUOTE);
} catch (\Exception $e) {
return new InvalidEmail(new UnclosedQuotedString(), $this->lexer->current->value);
}
$this->warnings[QuotedString::CODE] = new QuotedString($previous->value, $this->lexer->current->value);
return new ValidEmail();
}
}

View File

@@ -0,0 +1,87 @@
<?php
namespace Egulias\EmailValidator\Parser;
use Egulias\EmailValidator\EmailLexer;
use Egulias\EmailValidator\Warning\CFWSNearAt;
use Egulias\EmailValidator\Result\InvalidEmail;
use Egulias\EmailValidator\Warning\CFWSWithFWS;
use Egulias\EmailValidator\Result\Reason\CRNoLF;
use Egulias\EmailValidator\Result\Reason\AtextAfterCFWS;
use Egulias\EmailValidator\Result\Reason\CRLFAtTheEnd;
use Egulias\EmailValidator\Result\Reason\CRLFX2;
use Egulias\EmailValidator\Result\Reason\ExpectingCTEXT;
use Egulias\EmailValidator\Result\Result;
use Egulias\EmailValidator\Result\ValidEmail;
class FoldingWhiteSpace extends PartParser
{
public const FWS_TYPES = [
EmailLexer::S_SP,
EmailLexer::S_HTAB,
EmailLexer::S_CR,
EmailLexer::S_LF,
EmailLexer::CRLF
];
public function parse(): Result
{
if (!$this->isFWS()) {
return new ValidEmail();
}
$previous = $this->lexer->getPrevious();
$resultCRLF = $this->checkCRLFInFWS();
if ($resultCRLF->isInvalid()) {
return $resultCRLF;
}
if ($this->lexer->current->isA(EmailLexer::S_CR)) {
return new InvalidEmail(new CRNoLF(), $this->lexer->current->value);
}
if ($this->lexer->isNextToken(EmailLexer::GENERIC) && !$previous->isA(EmailLexer::S_AT)) {
return new InvalidEmail(new AtextAfterCFWS(), $this->lexer->current->value);
}
if ($this->lexer->current->isA(EmailLexer::S_LF) || $this->lexer->current->isA(EmailLexer::C_NUL)) {
return new InvalidEmail(new ExpectingCTEXT(), $this->lexer->current->value);
}
if ($this->lexer->isNextToken(EmailLexer::S_AT) || $previous->isA(EmailLexer::S_AT)) {
$this->warnings[CFWSNearAt::CODE] = new CFWSNearAt();
} else {
$this->warnings[CFWSWithFWS::CODE] = new CFWSWithFWS();
}
return new ValidEmail();
}
protected function checkCRLFInFWS(): Result
{
if (!$this->lexer->current->isA(EmailLexer::CRLF)) {
return new ValidEmail();
}
if (!$this->lexer->isNextTokenAny(array(EmailLexer::S_SP, EmailLexer::S_HTAB))) {
return new InvalidEmail(new CRLFX2(), $this->lexer->current->value);
}
//this has no coverage. Condition is repeated from above one
if (!$this->lexer->isNextTokenAny(array(EmailLexer::S_SP, EmailLexer::S_HTAB))) {
return new InvalidEmail(new CRLFAtTheEnd(), $this->lexer->current->value);
}
return new ValidEmail();
}
protected function isFWS(): bool
{
if ($this->escaped()) {
return false;
}
return in_array($this->lexer->current->type, self::FWS_TYPES);
}
}

View File

@@ -0,0 +1,15 @@
<?php
namespace Egulias\EmailValidator\Parser;
use Egulias\EmailValidator\Result\Result;
use Egulias\EmailValidator\Result\InvalidEmail;
use Egulias\EmailValidator\Result\Reason\CommentsInIDRight;
class IDLeftPart extends LocalPart
{
protected function parseComments(): Result
{
return new InvalidEmail(new CommentsInIDRight(), $this->lexer->current->value);
}
}

View File

@@ -0,0 +1,29 @@
<?php
namespace Egulias\EmailValidator\Parser;
use Egulias\EmailValidator\EmailLexer;
use Egulias\EmailValidator\Result\Result;
use Egulias\EmailValidator\Result\ValidEmail;
use Egulias\EmailValidator\Result\InvalidEmail;
use Egulias\EmailValidator\Result\Reason\ExpectingATEXT;
class IDRightPart extends DomainPart
{
protected function validateTokens(bool $hasComments): Result
{
$invalidDomainTokens = [
EmailLexer::S_DQUOTE => true,
EmailLexer::S_SQUOTE => true,
EmailLexer::S_BACKTICK => true,
EmailLexer::S_SEMICOLON => true,
EmailLexer::S_GREATERTHAN => true,
EmailLexer::S_LOWERTHAN => true,
];
if (isset($invalidDomainTokens[$this->lexer->current->type])) {
return new InvalidEmail(new ExpectingATEXT('Invalid token in domain: ' . $this->lexer->current->value), $this->lexer->current->value);
}
return new ValidEmail();
}
}

View File

@@ -0,0 +1,162 @@
<?php
namespace Egulias\EmailValidator\Parser;
use Egulias\EmailValidator\EmailLexer;
use Egulias\EmailValidator\Result\Result;
use Egulias\EmailValidator\Result\ValidEmail;
use Egulias\EmailValidator\Result\InvalidEmail;
use Egulias\EmailValidator\Warning\LocalTooLong;
use Egulias\EmailValidator\Result\Reason\DotAtEnd;
use Egulias\EmailValidator\Result\Reason\DotAtStart;
use Egulias\EmailValidator\Result\Reason\ConsecutiveDot;
use Egulias\EmailValidator\Result\Reason\ExpectingATEXT;
use Egulias\EmailValidator\Parser\CommentStrategy\LocalComment;
class LocalPart extends PartParser
{
public const INVALID_TOKENS = [
EmailLexer::S_COMMA => EmailLexer::S_COMMA,
EmailLexer::S_CLOSEBRACKET => EmailLexer::S_CLOSEBRACKET,
EmailLexer::S_OPENBRACKET => EmailLexer::S_OPENBRACKET,
EmailLexer::S_GREATERTHAN => EmailLexer::S_GREATERTHAN,
EmailLexer::S_LOWERTHAN => EmailLexer::S_LOWERTHAN,
EmailLexer::S_COLON => EmailLexer::S_COLON,
EmailLexer::S_SEMICOLON => EmailLexer::S_SEMICOLON,
EmailLexer::INVALID => EmailLexer::INVALID
];
/**
* @var string
*/
private $localPart = '';
public function parse(): Result
{
$this->lexer->startRecording();
while (!$this->lexer->current->isA(EmailLexer::S_AT) && !$this->lexer->current->isA(EmailLexer::S_EMPTY)) {
if ($this->hasDotAtStart()) {
return new InvalidEmail(new DotAtStart(), $this->lexer->current->value);
}
if ($this->lexer->current->isA(EmailLexer::S_DQUOTE)) {
$dquoteParsingResult = $this->parseDoubleQuote();
//Invalid double quote parsing
if ($dquoteParsingResult->isInvalid()) {
return $dquoteParsingResult;
}
}
if (
$this->lexer->current->isA(EmailLexer::S_OPENPARENTHESIS) ||
$this->lexer->current->isA(EmailLexer::S_CLOSEPARENTHESIS)
) {
$commentsResult = $this->parseComments();
//Invalid comment parsing
if ($commentsResult->isInvalid()) {
return $commentsResult;
}
}
if ($this->lexer->current->isA(EmailLexer::S_DOT) && $this->lexer->isNextToken(EmailLexer::S_DOT)) {
return new InvalidEmail(new ConsecutiveDot(), $this->lexer->current->value);
}
if (
$this->lexer->current->isA(EmailLexer::S_DOT) &&
$this->lexer->isNextToken(EmailLexer::S_AT)
) {
return new InvalidEmail(new DotAtEnd(), $this->lexer->current->value);
}
$resultEscaping = $this->validateEscaping();
if ($resultEscaping->isInvalid()) {
return $resultEscaping;
}
$resultToken = $this->validateTokens(false);
if ($resultToken->isInvalid()) {
return $resultToken;
}
$resultFWS = $this->parseLocalFWS();
if ($resultFWS->isInvalid()) {
return $resultFWS;
}
$this->lexer->moveNext();
}
$this->lexer->stopRecording();
$this->localPart = rtrim($this->lexer->getAccumulatedValues(), '@');
if (strlen($this->localPart) > LocalTooLong::LOCAL_PART_LENGTH) {
$this->warnings[LocalTooLong::CODE] = new LocalTooLong();
}
return new ValidEmail();
}
protected function validateTokens(bool $hasComments): Result
{
if (isset(self::INVALID_TOKENS[$this->lexer->current->type])) {
return new InvalidEmail(new ExpectingATEXT('Invalid token found'), $this->lexer->current->value);
}
return new ValidEmail();
}
public function localPart(): string
{
return $this->localPart;
}
private function parseLocalFWS(): Result
{
$foldingWS = new FoldingWhiteSpace($this->lexer);
$resultFWS = $foldingWS->parse();
if ($resultFWS->isValid()) {
$this->warnings = [...$this->warnings, ...$foldingWS->getWarnings()];
}
return $resultFWS;
}
private function hasDotAtStart(): bool
{
return $this->lexer->current->isA(EmailLexer::S_DOT) && $this->lexer->getPrevious()->isA(EmailLexer::S_EMPTY);
}
private function parseDoubleQuote(): Result
{
$dquoteParser = new DoubleQuote($this->lexer);
$parseAgain = $dquoteParser->parse();
$this->warnings = [...$this->warnings, ...$dquoteParser->getWarnings()];
return $parseAgain;
}
protected function parseComments(): Result
{
$commentParser = new Comment($this->lexer, new LocalComment());
$result = $commentParser->parse();
$this->warnings = [...$this->warnings, ...$commentParser->getWarnings()];
return $result;
}
private function validateEscaping(): Result
{
//Backslash found
if (!$this->lexer->current->isA(EmailLexer::S_BACKSLASH)) {
return new ValidEmail();
}
if ($this->lexer->isNextToken(EmailLexer::GENERIC)) {
return new InvalidEmail(new ExpectingATEXT('Found ATOM after escaping'), $this->lexer->current->value);
}
return new ValidEmail();
}
}

View File

@@ -0,0 +1,63 @@
<?php
namespace Egulias\EmailValidator\Parser;
use Egulias\EmailValidator\EmailLexer;
use Egulias\EmailValidator\Result\InvalidEmail;
use Egulias\EmailValidator\Result\Reason\ConsecutiveDot;
use Egulias\EmailValidator\Result\Result;
use Egulias\EmailValidator\Result\ValidEmail;
use Egulias\EmailValidator\Warning\Warning;
abstract class PartParser
{
/**
* @var Warning[]
*/
protected $warnings = [];
/**
* @var EmailLexer
*/
protected $lexer;
public function __construct(EmailLexer $lexer)
{
$this->lexer = $lexer;
}
abstract public function parse(): Result;
/**
* @return Warning[]
*/
public function getWarnings()
{
return $this->warnings;
}
protected function parseFWS(): Result
{
$foldingWS = new FoldingWhiteSpace($this->lexer);
$resultFWS = $foldingWS->parse();
$this->warnings = [...$this->warnings, ...$foldingWS->getWarnings()];
return $resultFWS;
}
protected function checkConsecutiveDots(): Result
{
if ($this->lexer->current->isA(EmailLexer::S_DOT) && $this->lexer->isNextToken(EmailLexer::S_DOT)) {
return new InvalidEmail(new ConsecutiveDot(), $this->lexer->current->value);
}
return new ValidEmail();
}
protected function escaped(): bool
{
$previous = $this->lexer->getPrevious();
return $previous->isA(EmailLexer::S_BACKSLASH)
&& !$this->lexer->current->isA(EmailLexer::GENERIC);
}
}