Repository: egulias/EmailValidator Branch: 4.x Commit: d42c8731f062 Files: 119 Total size: 166.0 KB Directory structure: gitextract_bauv4yn0/ ├── .gitattributes ├── .github/ │ ├── FUNDING.yml │ ├── dependabot.yml │ └── workflows/ │ ├── static-analysis.yml │ ├── tests.yml │ └── upload-to-codacy.yml ├── .gitignore ├── CONTRIBUTING.md ├── LICENSE ├── README.md ├── composer.json ├── documentation/ │ ├── Other.md │ ├── RFC5321BNF.html │ └── RFC5322BNF.html ├── phpunit.xml.dist ├── psalm.xml ├── src/ │ ├── EmailLexer.php │ ├── EmailParser.php │ ├── EmailValidator.php │ ├── MessageIDParser.php │ ├── Parser/ │ │ ├── Comment.php │ │ ├── CommentStrategy/ │ │ │ ├── CommentStrategy.php │ │ │ ├── DomainComment.php │ │ │ └── LocalComment.php │ │ ├── DomainLiteral.php │ │ ├── DomainPart.php │ │ ├── DoubleQuote.php │ │ ├── FoldingWhiteSpace.php │ │ ├── IDLeftPart.php │ │ ├── IDRightPart.php │ │ ├── LocalPart.php │ │ └── PartParser.php │ ├── Parser.php │ ├── Result/ │ │ ├── InvalidEmail.php │ │ ├── MultipleErrors.php │ │ ├── Reason/ │ │ │ ├── AtextAfterCFWS.php │ │ │ ├── CRLFAtTheEnd.php │ │ │ ├── CRLFX2.php │ │ │ ├── CRNoLF.php │ │ │ ├── CharNotAllowed.php │ │ │ ├── CommaInDomain.php │ │ │ ├── CommentsInIDRight.php │ │ │ ├── ConsecutiveAt.php │ │ │ ├── ConsecutiveDot.php │ │ │ ├── DetailedReason.php │ │ │ ├── DomainAcceptsNoMail.php │ │ │ ├── DomainHyphened.php │ │ │ ├── DomainTooLong.php │ │ │ ├── DotAtEnd.php │ │ │ ├── DotAtStart.php │ │ │ ├── EmptyReason.php │ │ │ ├── ExceptionFound.php │ │ │ ├── ExpectingATEXT.php │ │ │ ├── ExpectingCTEXT.php │ │ │ ├── ExpectingDTEXT.php │ │ │ ├── ExpectingDomainLiteralClose.php │ │ │ ├── LabelTooLong.php │ │ │ ├── LocalOrReservedDomain.php │ │ │ ├── NoDNSRecord.php │ │ │ ├── NoDomainPart.php │ │ │ ├── NoLocalPart.php │ │ │ ├── RFCWarnings.php │ │ │ ├── Reason.php │ │ │ ├── SpoofEmail.php │ │ │ ├── UnOpenedComment.php │ │ │ ├── UnableToGetDNSRecord.php │ │ │ ├── UnclosedComment.php │ │ │ ├── UnclosedQuotedString.php │ │ │ └── UnusualElements.php │ │ ├── Result.php │ │ ├── SpoofEmail.php │ │ └── ValidEmail.php │ ├── Validation/ │ │ ├── DNSCheckValidation.php │ │ ├── DNSGetRecordWrapper.php │ │ ├── DNSRecords.php │ │ ├── EmailValidation.php │ │ ├── Exception/ │ │ │ └── EmptyValidationList.php │ │ ├── Extra/ │ │ │ └── SpoofCheckValidation.php │ │ ├── MessageIDValidation.php │ │ ├── MultipleValidationWithAnd.php │ │ ├── NoRFCWarningsValidation.php │ │ └── RFCValidation.php │ └── Warning/ │ ├── AddressLiteral.php │ ├── CFWSNearAt.php │ ├── CFWSWithFWS.php │ ├── Comment.php │ ├── DeprecatedComment.php │ ├── DomainLiteral.php │ ├── EmailTooLong.php │ ├── IPV6BadChar.php │ ├── IPV6ColonEnd.php │ ├── IPV6ColonStart.php │ ├── IPV6Deprecated.php │ ├── IPV6DoubleColon.php │ ├── IPV6GroupCount.php │ ├── IPV6MaxGroups.php │ ├── LocalTooLong.php │ ├── NoDNSMXRecord.php │ ├── ObsoleteDTEXT.php │ ├── QuotedPart.php │ ├── QuotedString.php │ ├── TLD.php │ └── Warning.php └── tests/ └── EmailValidator/ ├── Dummy/ │ ├── AnotherDummyReason.php │ └── DummyReason.php ├── EmailLexerTest.php ├── EmailParserTest.php ├── EmailValidatorTest.php ├── LexerTokensTest.php ├── Reason/ │ └── MultipleErrorsTest.php ├── Result/ │ └── ResultTest.php └── Validation/ ├── DNSCheckValidationTest.php ├── Extra/ │ └── SpoofCheckValidationTest.php ├── IsEmailFunctionTests.php ├── MessageIDValidationTest.php ├── MultipleValidationWithAndTest.php ├── NoRFCWarningsValidationTest.php ├── RFCValidationDomainPartTest.php └── RFCValidationTest.php ================================================ FILE CONTENTS ================================================ ================================================ FILE: .gitattributes ================================================ /documentation export-ignore /tests export-ignore /.* export-ignore /phpunit.xml.dist export-ignore /psalm.xml export-ignore /README.md export-ignore ================================================ FILE: .github/FUNDING.yml ================================================ # Thanks! github: [egulias] ================================================ FILE: .github/dependabot.yml ================================================ version: 2 updates: - package-ecosystem: "composer" directory: "/" schedule: interval: "weekly" ================================================ FILE: .github/workflows/static-analysis.yml ================================================ name: static analysis on: push: branches: - '*.x' pull_request: jobs: psalm: runs-on: ubuntu-22.04 strategy: fail-fast: true name: Psalm steps: - name: Checkout code uses: actions/checkout@v4 - name: Setup PHP uses: shivammathur/setup-php@v2 with: php-version: 8.2 ini-values: error_reporting=E_ALL tools: composer:v2 coverage: none - name: Install dependencies uses: ramsey/composer-install@v2 - name: Execute Psalm run: vendor/bin/psalm ================================================ FILE: .github/workflows/tests.yml ================================================ name: unit-tests on: push: branches: - '*.x' pull_request: jobs: tests: runs-on: ubuntu-22.04 strategy: fail-fast: true matrix: php: ['8.1', '8.2', '8.3'] deps: [highest] include: - php: '8.1' deps: lowest name: PHP ${{ matrix.php }} / ${{ matrix.deps }} steps: - name: Checkout code uses: actions/checkout@v4 - name: Setup PHP uses: shivammathur/setup-php@v2 with: php-version: ${{ matrix.php }} ini-values: error_reporting=E_ALL tools: composer:v2 coverage: xdebug - name: Install dependencies uses: ramsey/composer-install@v3 with: dependency-versions: ${{ matrix.deps }} - name: Setup logs directory run: mkdir -p build/logs - name: Execute tests run: vendor/bin/phpunit --coverage-clover build/logs/clover.xml --exclude-group flaky - name: Store artifacts if: ${{ matrix.php == '8.1' && matrix.deps == 'lowest' }} uses: actions/upload-artifact@v4 with: name: clover.xml path: build/logs ================================================ FILE: .github/workflows/upload-to-codacy.yml ================================================ name: upload-coverage-to-codacy on: workflow_run: workflows: ["unit-tests"] types: - completed jobs: upload: runs-on: ubuntu-latest if: > github.event.workflow_run.event == 'pull_request' && github.event.workflow_run.conclusion == 'success' strategy: fail-fast: true name: upload-coverage steps: - name: Setup logs directory run: mkdir -p build/coverage - name: Download clover.xml artifact uses: dawidd6/action-download-artifact@v7 with: workflow: tests.yml name: clover.xml path: build/coverage - name: Upload Coverage to Codacy shell: bash env: CODACY_PROJECT_TOKEN: ${{ secrets.CODACY_PROJECT_TOKEN }} run: bash <(curl -Ls https://coverage.codacy.com/get.sh) report -r build/coverage/clover.xml ================================================ FILE: .gitignore ================================================ build/ report/ vendor/ composer.lock phpunit.result.cache .phpunit* .idea .vscode .php-version ================================================ FILE: CONTRIBUTING.md ================================================ # Contributing When contributing to this repository make sure to follow the Pull request process below. Reduce to the minimum 3rd party dependencies. Please note we have a [code of conduct](#Code of Conduct), please follow it in all your interactions with the project. ## Pull Request Process When doing a PR to v2 remember that you also have to do the PR port to v3, or tests confirming the bug is not reproducible. 1. Supported version is v3. If you are fixing a bug in v2, please port to v3 2. Use the title as a brief description of the changes 3. Describe the changes you are proposing 1. If adding an extra validation state the benefits of adding it and the problem is solving 2. Document in the readme, by adding it to the list 4. Provide appropriate tests for the code you are submitting: aim to keep the existing coverage percentage. 5. Add your Twitter handle (if you have) so we can thank you there. ## License By contributing, you agree that your contributions will be licensed under its MIT License. ## Code of Conduct ### Our Pledge We as members, contributors, and leaders pledge to make participation in our community a harassment-free experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation. We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community. ### Our Standards Examples of behavior that contributes to a positive environment for our community include: * Demonstrating empathy and kindness toward other people * Being respectful of differing opinions, viewpoints, and experiences * Giving and gracefully accepting constructive feedback * Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience * Focusing on what is best not just for us as individuals, but for the overall community Examples of unacceptable behavior include: * The use of sexualized language or imagery, and sexual attention or advances of any kind * Trolling, insulting or derogatory comments, and personal or political attacks * Public or private harassment * Publishing others' private information, such as a physical or email address, without their explicit permission * Other conduct which could reasonably be considered inappropriate in a professional setting ### Enforcement Responsibilities Community leaders are responsible for clarifying and enforcing our standards of acceptable behavior and will take appropriate and fair corrective action in response to any behavior that they deem inappropriate, threatening, offensive, or harmful. Community leaders have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, and will communicate reasons for moderation decisions when appropriate. ### Scope This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing the community in public spaces. Examples of representing our community include using an official e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. ### Enforcement Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the community leaders responsible for enforcement at . All complaints will be reviewed and investigated promptly and fairly. All community leaders are obligated to respect the privacy and security of the reporter of any incident. #### Enforcement Guidelines Community leaders will follow these Community Impact Guidelines in determining the consequences for any action they deem in violation of this Code of Conduct: #### 1. Correction **Community Impact**: Use of inappropriate language or other behavior deemed unprofessional or unwelcome in the community. **Consequence**: A private, written warning from community leaders, providing clarity around the nature of the violation and an explanation of why the behavior was inappropriate. A public apology may be requested. #### 2. Warning **Community Impact**: A violation through a single incident or series of actions. **Consequence**: A warning with consequences for continued behavior. No interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, for a specified period of time. This includes avoiding interactions in community spaces as well as external channels like social media. Violating these terms may lead to a temporary or permanent ban. #### 3. Temporary Ban **Community Impact**: A serious violation of community standards, including sustained inappropriate behavior. **Consequence**: A temporary ban from any sort of interaction or public communication with the community for a specified period of time. No public or private interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, is allowed during this period. Violating these terms may lead to a permanent ban. #### 4. Permanent Ban **Community Impact**: Demonstrating a pattern of violation of community standards, including sustained inappropriate behavior, harassment of an individual, or aggression toward or disparagement of classes of individuals. **Consequence**: A permanent ban from any sort of public interaction within the community. ### Attribution This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 2.0, available at [https://www.contributor-covenant.org/version/2/0/code_of_conduct.html][v2.0]. Community Impact Guidelines were inspired by [Mozilla's code of conduct enforcement ladder][Mozilla CoC]. For answers to common questions about this code of conduct, see the FAQ at [https://www.contributor-covenant.org/faq][FAQ]. Translations are available at [https://www.contributor-covenant.org/translations][translations]. [homepage]: https://www.contributor-covenant.org [v2.0]: https://www.contributor-covenant.org/version/2/0/code_of_conduct.html [Mozilla CoC]: https://github.com/mozilla/diversity [FAQ]: https://www.contributor-covenant.org/faq [translations]: https://www.contributor-covenant.org/translations ================================================ FILE: LICENSE ================================================ Copyright (c) 2013-2023 Eduardo Gulias Davis Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ================================================ FILE: README.md ================================================ # EmailValidator [![Build Status](https://github.com/egulias/EmailValidator/actions/workflows/tests.yml/badge.svg)](https://github.com/egulias/EmailValidator/actions/workflows/tests.yml) [![Quality Badge](https://app.codacy.com/project/badge/Grade/55d44898c7e44ebdb4e457523563ad63)](https://app.codacy.com/gh/egulias/EmailValidator/dashboard?utm_source=gh&utm_medium=referral&utm_content=&utm_campaign=Badge_grade) [![Test Coverage](https://app.codacy.com/project/badge/Coverage/55d44898c7e44ebdb4e457523563ad63)](https://app.codacy.com/gh/egulias/EmailValidator/dashboard?utm_source=gh&utm_medium=referral&utm_content=&utm_campaign=Badge_coverage) ![Latest Release](https://img.shields.io/github/v/release/egulias/EmailValidator) A library for validating emails against several RFC. ## Supported RFCs This library aims to support RFCs: * [5321](https://tools.ietf.org/html/rfc5321), * [5322](https://tools.ietf.org/html/rfc5322), * [6530](https://tools.ietf.org/html/rfc6530), * [6531](https://tools.ietf.org/html/rfc6531), * [6532](https://tools.ietf.org/html/rfc6532), * [1035](https://tools.ietf.org/html/rfc1035) ## Supported versions | Version | Released | EOL | Only critical bug fixes | Full | |:-------:|:----------:|:---:|:-----------------------:|:----:| |**v4.x** |**2023/01/07** | - | **X** |**X** | | v3.x | 2020/12/29 | YES | | | | v2.1.x | 2016/05/16 | YES | | | | v1.2 | 2013/19/05 | YES | | | ## Requirements * PHP 8.1 * [Composer](https://getcomposer.org) is required for installation * [Spoofchecking](/src/Validation/Extra/SpoofCheckValidation.php) and [DNSCheckValidation](/src/Validation/DNSCheckValidation.php) validation requires that your PHP system has the [PHP Internationalization Libraries](https://php.net/manual/en/book.intl.php) (also known as PHP Intl) **Note**: `PHP version upgrades will happen to accomodate to the pace of major frameworks. Minor versions bumps will go via minor versions of this library (i.e: PHP7.3 -> v3.x+1). Major versions will go with major versions of the library` ## Installation Run the command below to install via Composer ```shell composer require egulias/email-validator ``` ## Getting Started `EmailValidator` requires you to decide which (or combination of them) validation/s strategy/ies you'd like to follow for each [validation](#available-validations). A basic example with the RFC validation ```php isValid("example@example.com", new RFCValidation()); //true ``` ### Available validations 1. [RFCValidation](/src/Validation/RFCValidation.php): Standard RFC-like email validation. 2. [NoRFCWarningsValidation](/src/Validation/NoRFCWarningsValidation.php): RFC-like validation that will fail when warnings* are found. 3. [DNSCheckValidation](/src/Validation/DNSCheckValidation.php): Will check if there are DNS records that signal that the server accepts emails. This does not entail that the email exists. 4. [MultipleValidationWithAnd](/src/Validation/MultipleValidationWithAnd.php): It is a validation that operates over other validations performing a logical and (&&) over the result of each validation. 5. [MessageIDValidation](/src/Validation/MessageIDValidation.php): Follows [RFC2822 for message-id](https://tools.ietf.org/html/rfc2822#section-3.6.4) to validate that field, that has some differences in the domain part. 6. [Your own validation](#how-to-extend): You can extend the library behaviour by implementing your own validations. *warnings: Warnings are deviations from the RFC that in a broader interpretation are accepted. ```php isValid("example@ietf.org", $multipleValidations); //true ``` #### Additional validations Validations not present in the RFCs 1. [SpoofCheckValidation](/src/Validation/Extra/SpoofCheckValidation.php): Will check for multi-utf-8 chars that can signal an erroneous email name. ### How to extend It's easy! You just need to implement [EmailValidation](/src/Validation/EmailValidation.php) and you can use your own validation. ## Contributing Please follow the [Contribution guide](CONTRIBUTING.md). Is short and simple and will help a lot. ## Other Contributors (You can find current contributors [here](https://github.com/egulias/EmailValidator/graphs/contributors)) As this is a port from another library and work, here are other people related to the previous one: * Ricard Clau [@ricardclau](https://github.com/ricardclau): Performance against PHP built-in filter_var (v2 and earlier) * Josepf Bielawski [@stloyd](https://github.com/stloyd): For its first re-work of Dominic's lib * Dominic Sayers [@dominicsayers](https://github.com/dominicsayers): The original `isemail` function ## License Released under the MIT License attached with this code. ================================================ FILE: composer.json ================================================ { "name": "egulias/email-validator", "description": "A library for validating emails against several RFCs", "homepage": "https://github.com/egulias/EmailValidator", "keywords": ["email", "validation", "validator", "emailvalidation", "emailvalidator"], "license": "MIT", "authors": [ {"name": "Eduardo Gulias Davis"} ], "extra": { "branch-alias": { "dev-master": "4.0.x-dev" } }, "require": { "php": ">=8.1", "doctrine/lexer": "^2.0 || ^3.0", "symfony/polyfill-intl-idn": "^1.26" }, "require-dev": { "phpunit/phpunit": "^10.2", "vimeo/psalm": "^5.12" }, "suggest": { "ext-intl": "PHP Internationalization Libraries are required to use the SpoofChecking validation" }, "autoload": { "psr-4": { "Egulias\\EmailValidator\\": "src" } }, "autoload-dev": { "psr-4": { "Egulias\\EmailValidator\\Tests\\": "tests" } } } ================================================ FILE: documentation/Other.md ================================================ Email length ------------ https://tools.ietf.org/html/rfc5321#section-4.1.2 Forward-path = Path Path = "<" [ A-d-l ":" ] Mailbox ">" https://tools.ietf.org/html/rfc5321#section-4.5.3.1.3 https://tools.ietf.org/html/rfc1035#section-2.3.4 DNS --- https://tools.ietf.org/html/rfc5321#section-2.3.5 Names that can be resolved to MX RRs or address (i.e., A or AAAA) RRs (as discussed in Section 5) are permitted, as are CNAME RRs whose targets can be resolved, in turn, to MX or address RRs. https://tools.ietf.org/html/rfc5321#section-5.1 The lookup first attempts to locate an MX record associated with the name. If a CNAME record is found, the resulting name is processed as if it were the initial name. ... If an empty list of MXs is returned, the address is treated as if it was associated with an implicit MX RR, with a preference of 0, pointing to that host. is_email() author's note: We will regard the existence of a CNAME to be sufficient evidence of the domain's existence. For performance reasons we will not repeat the DNS lookup for the CNAME's target, but we will raise a warning because we didn't immediately find an MX record. Check for TLD addresses ----------------------- TLD addresses are specifically allowed in RFC 5321 but they are unusual to say the least. We will allocate a separate status to these addresses on the basis that they are more likely to be typos than genuine addresses (unless we've already established that the domain does have an MX record) https://tools.ietf.org/html/rfc5321#section-2.3.5 In the case of a top-level domain used by itself in an email address, a single string is used without any dots. This makes the requirement, described in more detail below, that only fully-qualified domain names appear in SMTP transactions on the public Internet, particularly important where top-level domains are involved. TLD format ---------- The format of TLDs has changed a number of times. The standards used by IANA have been largely ignored by ICANN, leading to confusion over the standards being followed. These are not defined anywhere, except as a general component of a DNS host name (a label). However, this could potentially lead to 123.123.123.123 being a valid DNS name (rather than an IP address) and thereby creating an ambiguity. The most authoritative statement on TLD formats that the author can find is in a (rejected!) erratum to RFC 1123 submitted by John Klensin, the author of RFC 5321: https://www.rfc-editor.org/errata_search.php?rfc=1123&eid=1353 However, a valid host name can never have the dotted-decimal form #.#.#.#, since this change does not permit the highest-level component label to start with a digit even if it is not all-numeric. Comments -------- Comments at the start of the domain are deprecated in the text Comments at the start of a subdomain are obs-domain (https://tools.ietf.org/html/rfc5322#section-3.4.1) ================================================ FILE: documentation/RFC5321BNF.html ================================================ The BNF from RFC 5321 defining parts of a valid SMTP address
   Mailbox        = Local-part "@" ( Domain / address-literal )

   Local-part     = Dot-string / Quoted-string
                  ; MAY be case-sensitive


   Dot-string     = Atom *("."  Atom)

   Atom           = 1*atext

   Quoted-string  = DQUOTE *QcontentSMTP DQUOTE

   QcontentSMTP   = qtextSMTP / quoted-pairSMTP

   quoted-pairSMTP  = %d92 %d32-126
                    ; i.e., backslash followed by any ASCII
                    ; graphic (including itself) or SPace

   qtextSMTP      = %d32-33 / %d35-91 / %d93-126
                  ; i.e., within a quoted string, any
                  ; ASCII graphic or space is permitted
                  ; without blackslash-quoting except
                  ; double-quote and the backslash itself.

   Domain         = sub-domain *("." sub-domain)

   sub-domain     = Let-dig [Ldh-str]

   Let-dig        = ALPHA / DIGIT

   Ldh-str        = *( ALPHA / DIGIT / "-" ) Let-dig

   address-literal  = "[" ( IPv4-address-literal /
                    IPv6-address-literal /
                    General-address-literal ) "]"
                    ; See Section 4.1.3

   IPv4-address-literal  = Snum 3("."  Snum)

   IPv6-address-literal  = "IPv6:" IPv6-addr

   General-address-literal  = Standardized-tag ":" 1*dcontent

   Standardized-tag  = Ldh-str
                     ; Standardized-tag MUST be specified in a
                     ; Standards-Track RFC and registered with IANA

   dcontent       = %d33-90 / ; Printable US-ASCII
                  %d94-126 ; excl. "[", "\", "]"

   Snum           = 1*3DIGIT
                  ; representing a decimal integer
                  ; value in the range 0 through 255

   IPv6-addr      = IPv6-full / IPv6-comp / IPv6v4-full / IPv6v4-comp

   IPv6-hex       = 1*4HEXDIG

   IPv6-full      = IPv6-hex 7(":" IPv6-hex)

   IPv6-comp      = [IPv6-hex *5(":" IPv6-hex)] "::"
                  [IPv6-hex *5(":" IPv6-hex)]
                  ; The "::" represents at least 2 16-bit groups of
                  ; zeros.  No more than 6 groups in addition to the
                  ; "::" may be present.

   IPv6v4-full    = IPv6-hex 5(":" IPv6-hex) ":" IPv4-address-literal

   IPv6v4-comp    = [IPv6-hex *3(":" IPv6-hex)] "::"
                  [IPv6-hex *3(":" IPv6-hex) ":"]
                  IPv4-address-literal
                  ; The "::" represents at least 2 16-bit groups of
                  ; zeros.  No more than 4 groups in addition to the
                  ; "::" and IPv4-address-literal may be present.

================================================ FILE: documentation/RFC5322BNF.html ================================================ The BNF from RFC 5322 defining parts of a valid internet message address
   addr-spec       =   local-part "@" domain

   local-part      =   dot-atom / quoted-string / obs-local-part

   dot-atom        =   [CFWS] dot-atom-text [CFWS]

   CFWS            =   (1*([FWS] comment) [FWS]) / FWS

   FWS             =   ([*WSP CRLF] 1*WSP) /  obs-FWS
                                          ; Folding white space

   WSP             =   SP / HTAB          ; white space

   obs-FWS         =   1*([CRLF] WSP)     ; As amended in erratum #1908

   ctext           =   %d33-39 /          ; Printable US-ASCII
                       %d42-91 /          ;  characters not including
                       %d93-126 /         ;  "(", ")", or "\"
                       obs-ctext

   obs-ctext       =   obs-NO-WS-CTL
   ccontent        =   ctext / quoted-pair / comment

   comment         =   "(" *([FWS] ccontent) [FWS] ")"

   dot-atom-text   =   1*atext *("." 1*atext)

   atext           =   ALPHA / DIGIT /    ; Printable US-ASCII
                       "!" / "#" /        ;  characters not including
                       "$" / "%" /        ;  specials.  Used for atoms.
                       "&" / "'" /
                       "*" / "+" /
                       "-" / "/" /
                       "=" / "?" /
                       "^" / "_" /
                       "`" / "{" /
                       "|" / "}" /
                       "~"

   specials        =   "(" / ")" /        ; Special characters that do
                       "<" / ">" /        ;  not appear in atext
                       "[" / "]" /
                       ":" / ";" /
                       "@" / "\" /
                       "," / "." /
                       DQUOTE

   quoted-string   =   [CFWS]
                       DQUOTE *([FWS] qcontent) [FWS] DQUOTE
                       [CFWS]

   qcontent        =   qtext / quoted-pair

   qtext           =   %d33 /             ; Printable US-ASCII
                       %d35-91 /          ;  characters not including
                       %d93-126 /         ;  "\" or the quote character
                       obs-qtext

   obs-qtext       =   obs-NO-WS-CTL

   obs-NO-WS-CTL   =   %d1-8 /            ; US-ASCII control
                       %d11 /             ;  characters that do not
                       %d12 /             ;  include the carriage
                       %d14-31 /          ;  return, line feed, and
                       %d127              ;  white space characters

   quoted-pair     =   ("\" (VCHAR / WSP)) / obs-qp

   VCHAR           =   %x21-7E            ; visible (printing) characters

   obs-qp          =   "\" (%d0 / obs-NO-WS-CTL / LF / CR)

   obs-local-part  =   word *("." word)

   word            =   atom / quoted-string

   atom            =   [CFWS] 1*atext [CFWS]

   domain          =   dot-atom / domain-literal / obs-domain

   domain-literal  =   [CFWS] "[" *([FWS] dtext) [FWS] "]" [CFWS]

   dtext           =   %d33-90 /          ; Printable US-ASCII
                       %d94-126 /         ;  characters not including
                       obs-dtext          ;  "[", "]", or "\"

   obs-dtext       =   obs-NO-WS-CTL / quoted-pair

   obs-domain      =   atom *("." atom)

NB For SMTP mail, the domain-literal is restricted by RFC5321 as follows:

   Mailbox        = Local-part "@" ( Domain / address-literal )

   address-literal  = "[" ( IPv4-address-literal /
                    IPv6-address-literal /
                    General-address-literal ) "]"

   IPv4-address-literal  = Snum 3("."  Snum)

   IPv6-address-literal  = "IPv6:" IPv6-addr

   Snum           = 1*3DIGIT
                  ; representing a decimal integer
                  ; value in the range 0 through 255

   IPv6-addr      = IPv6-full / IPv6-comp / IPv6v4-full / IPv6v4-comp

   IPv6-hex       = 1*4HEXDIG

   IPv6-full      = IPv6-hex 7(":" IPv6-hex)

   IPv6-comp      = [IPv6-hex *5(":" IPv6-hex)] "::"
                  [IPv6-hex *5(":" IPv6-hex)]
                  ; The "::" represents at least 2 16-bit groups of
                  ; zeros.  No more than 6 groups in addition to the
                  ; "::" may be present.

   IPv6v4-full    = IPv6-hex 5(":" IPv6-hex) ":" IPv4-address-literal

   IPv6v4-comp    = [IPv6-hex *3(":" IPv6-hex)] "::"
                  [IPv6-hex *3(":" IPv6-hex) ":"]
                  IPv4-address-literal
                  ; The "::" represents at least 2 16-bit groups of
                  ; zeros.  No more than 4 groups in addition to the
                  ; "::" and IPv4-address-literal may be present.

================================================ FILE: phpunit.xml.dist ================================================ ./tests/EmailValidator ./vendor/ ./src/ ./src/Result/Reason ================================================ FILE: psalm.xml ================================================ ================================================ FILE: src/EmailLexer.php ================================================ */ class EmailLexer extends AbstractLexer { //ASCII values public const S_EMPTY = -1; public const C_NUL = 0; public const S_HTAB = 9; public const S_LF = 10; public const S_CR = 13; public const S_SP = 32; public const EXCLAMATION = 33; public const S_DQUOTE = 34; public const NUMBER_SIGN = 35; public const DOLLAR = 36; public const PERCENTAGE = 37; public const AMPERSAND = 38; public const S_SQUOTE = 39; public const S_OPENPARENTHESIS = 40; public const S_CLOSEPARENTHESIS = 41; public const ASTERISK = 42; public const S_PLUS = 43; public const S_COMMA = 44; public const S_HYPHEN = 45; public const S_DOT = 46; public const S_SLASH = 47; public const S_COLON = 58; public const S_SEMICOLON = 59; public const S_LOWERTHAN = 60; public const S_EQUAL = 61; public const S_GREATERTHAN = 62; public const QUESTIONMARK = 63; public const S_AT = 64; public const S_OPENBRACKET = 91; public const S_BACKSLASH = 92; public const S_CLOSEBRACKET = 93; public const CARET = 94; public const S_UNDERSCORE = 95; public const S_BACKTICK = 96; public const S_OPENCURLYBRACES = 123; public const S_PIPE = 124; public const S_CLOSECURLYBRACES = 125; public const S_TILDE = 126; public const C_DEL = 127; public const INVERT_QUESTIONMARK = 168; public const INVERT_EXCLAMATION = 173; public const GENERIC = 300; public const S_IPV6TAG = 301; public const INVALID = 302; public const CRLF = 1310; public const S_DOUBLECOLON = 5858; public const ASCII_INVALID_FROM = 127; public const ASCII_INVALID_TO = 199; /** * US-ASCII visible characters not valid for atext (@link http://tools.ietf.org/html/rfc5322#section-3.2.3) * * @var array */ protected $charValue = [ '{' => self::S_OPENCURLYBRACES, '}' => self::S_CLOSECURLYBRACES, '(' => self::S_OPENPARENTHESIS, ')' => self::S_CLOSEPARENTHESIS, '<' => self::S_LOWERTHAN, '>' => self::S_GREATERTHAN, '[' => self::S_OPENBRACKET, ']' => self::S_CLOSEBRACKET, ':' => self::S_COLON, ';' => self::S_SEMICOLON, '@' => self::S_AT, '\\' => self::S_BACKSLASH, '/' => self::S_SLASH, ',' => self::S_COMMA, '.' => self::S_DOT, "'" => self::S_SQUOTE, "`" => self::S_BACKTICK, '"' => self::S_DQUOTE, '-' => self::S_HYPHEN, '::' => self::S_DOUBLECOLON, ' ' => self::S_SP, "\t" => self::S_HTAB, "\r" => self::S_CR, "\n" => self::S_LF, "\r\n" => self::CRLF, 'IPv6' => self::S_IPV6TAG, '' => self::S_EMPTY, '\0' => self::C_NUL, '*' => self::ASTERISK, '!' => self::EXCLAMATION, '&' => self::AMPERSAND, '^' => self::CARET, '$' => self::DOLLAR, '%' => self::PERCENTAGE, '~' => self::S_TILDE, '|' => self::S_PIPE, '_' => self::S_UNDERSCORE, '=' => self::S_EQUAL, '+' => self::S_PLUS, '¿' => self::INVERT_QUESTIONMARK, '?' => self::QUESTIONMARK, '#' => self::NUMBER_SIGN, '¡' => self::INVERT_EXCLAMATION, ]; public const INVALID_CHARS_REGEX = "/[^\p{S}\p{C}\p{Cc}]+/iu"; public const VALID_UTF8_REGEX = '/\p{Cc}+/u'; public const CATCHABLE_PATTERNS = [ '[a-zA-Z]+[46]?', //ASCII and domain literal '[^\x00-\x7F]', //UTF-8 '[0-9]+', '\r\n', '::', '\s+?', '.', ]; public const NON_CATCHABLE_PATTERNS = [ '[\xA0-\xff]+', ]; public const MODIFIERS = 'iu'; /** @var bool */ protected $hasInvalidTokens = false; /** * @var Token */ protected Token $previous; /** * The last matched/seen token. * * @var Token */ public Token $current; /** * @var Token */ private Token $nullToken; /** @var string */ private $accumulator = ''; /** @var bool */ private $hasToRecord = false; public function __construct() { /** @var Token $nullToken */ $nullToken = new Token('', self::S_EMPTY, 0); $this->nullToken = $nullToken; $this->current = $this->previous = $this->nullToken; $this->lookahead = null; } public function reset(): void { $this->hasInvalidTokens = false; parent::reset(); $this->current = $this->previous = $this->nullToken; } /** * @param int $type * @throws \UnexpectedValueException * @return boolean * */ public function find($type): bool { $search = clone $this; $search->skipUntil($type); if (!$search->lookahead) { throw new \UnexpectedValueException($type . ' not found'); } return true; } /** * moveNext * * @return boolean */ public function moveNext(): bool { if ($this->hasToRecord && $this->previous === $this->nullToken) { $this->accumulator .= $this->current->value; } $this->previous = $this->current; if ($this->lookahead === null) { $this->lookahead = $this->nullToken; } $hasNext = parent::moveNext(); $this->current = $this->token ?? $this->nullToken; if ($this->hasToRecord) { $this->accumulator .= $this->current->value; } return $hasNext; } /** * Retrieve token type. Also processes the token value if necessary. * * @param string $value * @throws \InvalidArgumentException * @return integer */ protected function getType(&$value): int { $encoded = $value; if (mb_detect_encoding($value, 'auto', true) !== 'UTF-8') { $encoded = mb_convert_encoding($value, 'UTF-8', 'Windows-1252'); } if ($this->isValid($encoded)) { return $this->charValue[$encoded]; } if ($this->isNullType($encoded)) { return self::C_NUL; } if ($this->isInvalidChar($encoded)) { $this->hasInvalidTokens = true; return self::INVALID; } return self::GENERIC; } protected function isValid(string $value): bool { return isset($this->charValue[$value]); } protected function isNullType(string $value): bool { return $value === "\0"; } protected function isInvalidChar(string $value): bool { return !preg_match(self::INVALID_CHARS_REGEX, $value); } protected function isUTF8Invalid(string $value): bool { return preg_match(self::VALID_UTF8_REGEX, $value) !== false; } public function hasInvalidTokens(): bool { return $this->hasInvalidTokens; } /** * getPrevious * * @return Token */ public function getPrevious(): Token { return $this->previous; } /** * Lexical catchable patterns. * * @return string[] */ protected function getCatchablePatterns(): array { return self::CATCHABLE_PATTERNS; } /** * Lexical non-catchable patterns. * * @return string[] */ protected function getNonCatchablePatterns(): array { return self::NON_CATCHABLE_PATTERNS; } protected function getModifiers(): string { return self::MODIFIERS; } public function getAccumulatedValues(): string { return $this->accumulator; } public function startRecording(): void { $this->hasToRecord = true; } public function stopRecording(): void { $this->hasToRecord = false; } public function clearRecorded(): void { $this->accumulator = ''; } } ================================================ FILE: src/EmailParser.php ================================================ addLongEmailWarning($this->localPart, $this->domainPart); return $result; } protected function preLeftParsing(): Result { if (!$this->hasAtToken()) { return new InvalidEmail(new NoLocalPart(), $this->lexer->current->value); } return new ValidEmail(); } protected function parseLeftFromAt(): Result { return $this->processLocalPart(); } protected function parseRightFromAt(): Result { return $this->processDomainPart(); } private function processLocalPart(): Result { $localPartParser = new LocalPart($this->lexer); $localPartResult = $localPartParser->parse(); $this->localPart = $localPartParser->localPart(); $this->warnings = [...$localPartParser->getWarnings(), ...$this->warnings]; return $localPartResult; } private function processDomainPart(): Result { $domainPartParser = new DomainPart($this->lexer); $domainPartResult = $domainPartParser->parse(); $this->domainPart = $domainPartParser->domainPart(); $this->warnings = [...$domainPartParser->getWarnings(), ...$this->warnings]; return $domainPartResult; } public function getDomainPart(): string { return $this->domainPart; } public function getLocalPart(): string { return $this->localPart; } private function addLongEmailWarning(string $localPart, string $parsedDomainPart): void { if (strlen($localPart . '@' . $parsedDomainPart) > self::EMAIL_MAX_LENGTH) { $this->warnings[EmailTooLong::CODE] = new EmailTooLong(); } } } ================================================ FILE: src/EmailValidator.php ================================================ lexer = new EmailLexer(); } /** * @param string $email * @param EmailValidation $emailValidation * @return bool */ public function isValid(string $email, EmailValidation $emailValidation) { $isValid = $emailValidation->isValid($email, $this->lexer); $this->warnings = $emailValidation->getWarnings(); $this->error = $emailValidation->getError(); return $isValid; } /** * @return boolean */ public function hasWarnings() { return !empty($this->warnings); } /** * @return array */ public function getWarnings() { return $this->warnings; } /** * @return InvalidEmail|null */ public function getError() { return $this->error; } } ================================================ FILE: src/MessageIDParser.php ================================================ addLongEmailWarning($this->idLeft, $this->idRight); return $result; } protected function preLeftParsing(): Result { if (!$this->hasAtToken()) { return new InvalidEmail(new NoLocalPart(), $this->lexer->current->value); } return new ValidEmail(); } protected function parseLeftFromAt(): Result { return $this->processIDLeft(); } protected function parseRightFromAt(): Result { return $this->processIDRight(); } private function processIDLeft(): Result { $localPartParser = new IDLeftPart($this->lexer); $localPartResult = $localPartParser->parse(); $this->idLeft = $localPartParser->localPart(); $this->warnings = [...$localPartParser->getWarnings(), ...$this->warnings]; return $localPartResult; } private function processIDRight(): Result { $domainPartParser = new IDRightPart($this->lexer); $domainPartResult = $domainPartParser->parse(); $this->idRight = $domainPartParser->domainPart(); $this->warnings = [...$domainPartParser->getWarnings(), ...$this->warnings]; return $domainPartResult; } public function getLeftPart(): string { return $this->idLeft; } public function getRightPart(): string { return $this->idRight; } private function addLongEmailWarning(string $localPart, string $parsedDomainPart): void { if (strlen($localPart . '@' . $parsedDomainPart) > self::EMAILID_MAX_LENGTH) { $this->warnings[EmailTooLong::CODE] = new EmailTooLong(); } } } ================================================ FILE: src/Parser/Comment.php ================================================ 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; } } } ================================================ FILE: src/Parser/CommentStrategy/CommentStrategy.php ================================================ 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 []; } } ================================================ FILE: src/Parser/CommentStrategy/LocalComment.php ================================================ */ 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; } } ================================================ FILE: src/Parser/DomainLiteral.php ================================================ 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(); } } } } ================================================ FILE: src/Parser/DomainPart.php ================================================ 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 $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 $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); /** @psalm-var array{errors: int, ...} $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; } } ================================================ FILE: src/Parser/DoubleQuote.php ================================================ 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(); } } ================================================ FILE: src/Parser/FoldingWhiteSpace.php ================================================ 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); } } ================================================ FILE: src/Parser/IDLeftPart.php ================================================ lexer->current->value); } } ================================================ FILE: src/Parser/IDRightPart.php ================================================ 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(); } } ================================================ FILE: src/Parser/LocalPart.php ================================================ 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->clearRecorded(); $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(); } } ================================================ FILE: src/Parser/PartParser.php ================================================ 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); } } ================================================ FILE: src/Parser.php ================================================ lexer = $lexer; } public function parse(string $str): Result { $this->lexer->setInput($str); if ($this->lexer->hasInvalidTokens()) { return new InvalidEmail(new ExpectingATEXT("Invalid tokens found"), $this->lexer->current->value); } $preParsingResult = $this->preLeftParsing(); if ($preParsingResult->isInvalid()) { return $preParsingResult; } $localPartResult = $this->parseLeftFromAt(); if ($localPartResult->isInvalid()) { return $localPartResult; } $domainPartResult = $this->parseRightFromAt(); if ($domainPartResult->isInvalid()) { return $domainPartResult; } return new ValidEmail(); } /** * @return Warning\Warning[] */ public function getWarnings(): array { return $this->warnings; } protected function hasAtToken(): bool { $this->lexer->moveNext(); $this->lexer->moveNext(); return !$this->lexer->current->isA(EmailLexer::S_AT); } } ================================================ FILE: src/Result/InvalidEmail.php ================================================ token = $token; $this->reason = $reason; } public function isValid(): bool { return false; } public function isInvalid(): bool { return true; } public function description(): string { return $this->reason->description() . " in char " . $this->token; } public function code(): int { return $this->reason->code(); } public function reason(): Reason { return $this->reason; } } ================================================ FILE: src/Result/MultipleErrors.php ================================================ reasons[$reason->code()] = $reason; } /** * @return Reason[] */ public function getReasons() : array { return $this->reasons; } public function reason() : Reason { return 0 !== count($this->reasons) ? current($this->reasons) : new EmptyReason(); } public function description() : string { $description = ''; foreach($this->reasons as $reason) { $description .= $reason->description() . PHP_EOL; } return $description; } public function code() : int { return 0; } } ================================================ FILE: src/Result/Reason/AtextAfterCFWS.php ================================================ detailedDescription = $details; } } ================================================ FILE: src/Result/Reason/DomainAcceptsNoMail.php ================================================ exception = $exception; } public function code() : int { return 999; } public function description() : string { return $this->exception->getMessage(); } } ================================================ FILE: src/Result/Reason/ExpectingATEXT.php ================================================ detailedDescription; } } ================================================ FILE: src/Result/Reason/ExpectingCTEXT.php ================================================ element = $element; } public function code() : int { return 201; } public function description() : string { return 'Unusual element found, wourld render invalid in majority of cases. Element found: ' . $this->element; } } ================================================ FILE: src/Result/Result.php ================================================ reason = new ReasonSpoofEmail(); parent::__construct($this->reason, ''); } } ================================================ FILE: src/Result/ValidEmail.php ================================================ dnsGetRecord = $dnsGetRecord; } public function isValid(string $email, EmailLexer $emailLexer): bool { // use the input to check DNS if we cannot extract something similar to a domain $host = $email; // Arguable pattern to extract the domain. Not aiming to validate the domain nor the email if (false !== $lastAtPos = strrpos($email, '@')) { $host = substr($email, $lastAtPos + 1); } // Get the domain parts $hostParts = explode('.', $host); $isLocalDomain = count($hostParts) <= 1; $isReservedTopLevel = in_array($hostParts[(count($hostParts) - 1)], self::RESERVED_DNS_TOP_LEVEL_NAMES, true); // Exclude reserved top level DNS names if ($isLocalDomain || $isReservedTopLevel) { $this->error = new InvalidEmail(new LocalOrReservedDomain(), $host); return false; } return $this->checkDns($host); } public function getError(): ?InvalidEmail { return $this->error; } /** * @return Warning[] */ public function getWarnings(): array { return $this->warnings; } /** * @param string $host * * @return bool */ protected function checkDns($host) { $variant = INTL_IDNA_VARIANT_UTS46; $host = rtrim(idn_to_ascii($host, IDNA_DEFAULT, $variant), '.'); $hostParts = explode('.', $host); $host = array_pop($hostParts); while (count($hostParts) > 0) { $host = array_pop($hostParts) . '.' . $host; if ($this->validateDnsRecords($host)) { return true; } } return false; } /** * Validate the DNS records for given host. * * @param string $host A set of DNS records in the format returned by dns_get_record. * * @return bool True on success. */ private function validateDnsRecords($host): bool { $dnsRecordsResult = $this->dnsGetRecord->getRecords($host, DNS_A + DNS_MX); if ($dnsRecordsResult->withError()) { $this->error = new InvalidEmail(new UnableToGetDNSRecord(), ''); return false; } $dnsRecords = $dnsRecordsResult->getRecords(); // Combined check for A+MX+AAAA can fail with SERVFAIL, even in the presence of valid A/MX records $aaaaRecordsResult = $this->dnsGetRecord->getRecords($host, DNS_AAAA); if (! $aaaaRecordsResult->withError()) { $dnsRecords = array_merge($dnsRecords, $aaaaRecordsResult->getRecords()); } // No MX, A or AAAA DNS records if ($dnsRecords === []) { $this->error = new InvalidEmail(new ReasonNoDNSRecord(), ''); return false; } // For each DNS record foreach ($dnsRecords as $dnsRecord) { if (!$this->validateMXRecord($dnsRecord)) { // No MX records (fallback to A or AAAA records) if (empty($this->mxRecords)) { $this->warnings[NoDNSMXRecord::CODE] = new NoDNSMXRecord(); } return false; } } return true; } /** * Validate an MX record * * @param array $dnsRecord Given DNS record. * * @return bool True if valid. */ private function validateMxRecord($dnsRecord): bool { if (!isset($dnsRecord['type'])) { $this->error = new InvalidEmail(new ReasonNoDNSRecord(), ''); return false; } if ($dnsRecord['type'] !== 'MX') { return true; } // "Null MX" record indicates the domain accepts no mail (https://tools.ietf.org/html/rfc7505) if (empty($dnsRecord['target']) || $dnsRecord['target'] === '.') { $this->error = new InvalidEmail(new DomainAcceptsNoMail(), ""); return false; } $this->mxRecords[] = $dnsRecord; return true; } } ================================================ FILE: src/Validation/DNSGetRecordWrapper.php ================================================ > $records * @param bool $error */ public function __construct(private readonly array $records, private readonly bool $error = false) { } /** * @return list> */ public function getRecords(): array { return $this->records; } public function withError(): bool { return $this->error; } } ================================================ FILE: src/Validation/EmailValidation.php ================================================ setChecks(Spoofchecker::SINGLE_SCRIPT); if ($checker->isSuspicious($email)) { $this->error = new SpoofEmail(); } return $this->error === null; } public function getError() : ?InvalidEmail { return $this->error; } public function getWarnings() : array { return []; } } ================================================ FILE: src/Validation/MessageIDValidation.php ================================================ parse($email); $this->warnings = $parser->getWarnings(); if ($result->isInvalid()) { /** @psalm-suppress PropertyTypeCoercion */ $this->error = $result; return false; } } catch (\Exception $invalid) { $this->error = new InvalidEmail(new ExceptionFound($invalid), ''); return false; } return true; } /** * @return Warning[] */ public function getWarnings(): array { return $this->warnings; } public function getError(): ?InvalidEmail { return $this->error; } } ================================================ FILE: src/Validation/MultipleValidationWithAnd.php ================================================ validations as $validation) { $emailLexer->reset(); $validationResult = $validation->isValid($email, $emailLexer); $result = $result && $validationResult; $this->warnings = [...$this->warnings, ...$validation->getWarnings()]; if (!$validationResult) { $this->processError($validation); } if ($this->shouldStop($result)) { break; } } return $result; } private function initErrorStorage(): void { if (null === $this->error) { $this->error = new MultipleErrors(); } } private function processError(EmailValidation $validation): void { if (null !== $validation->getError()) { $this->initErrorStorage(); /** @psalm-suppress PossiblyNullReference */ $this->error->addReason($validation->getError()->reason()); } } private function shouldStop(bool $result): bool { return !$result && $this->mode === self::STOP_ON_ERROR; } /** * Returns the validation errors. */ public function getError(): ?InvalidEmail { return $this->error; } /** * @return Warning[] */ public function getWarnings(): array { return $this->warnings; } } ================================================ FILE: src/Validation/NoRFCWarningsValidation.php ================================================ getWarnings())) { return true; } $this->error = new InvalidEmail(new RFCWarnings(), ''); return false; } /** * {@inheritdoc} */ public function getError() : ?InvalidEmail { return $this->error ?: parent::getError(); } } ================================================ FILE: src/Validation/RFCValidation.php ================================================ parse($email); $this->warnings = $parser->getWarnings(); if ($result->isInvalid()) { /** @psalm-suppress PropertyTypeCoercion */ $this->error = $result; return false; } } catch (\Exception $invalid) { $this->error = new InvalidEmail(new ExceptionFound($invalid), ''); return false; } return true; } public function getError(): ?InvalidEmail { return $this->error; } /** * @return Warning[] */ public function getWarnings(): array { return $this->warnings; } } ================================================ FILE: src/Warning/AddressLiteral.php ================================================ message = 'Address literal in domain part'; $this->rfcNumber = 5321; } } ================================================ FILE: src/Warning/CFWSNearAt.php ================================================ message = "Deprecated folding white space near @"; } } ================================================ FILE: src/Warning/CFWSWithFWS.php ================================================ message = 'Folding whites space followed by folding white space'; } } ================================================ FILE: src/Warning/Comment.php ================================================ message = "Comments found in this email"; } } ================================================ FILE: src/Warning/DeprecatedComment.php ================================================ message = 'Deprecated comments'; } } ================================================ FILE: src/Warning/DomainLiteral.php ================================================ message = 'Domain Literal'; $this->rfcNumber = 5322; } } ================================================ FILE: src/Warning/EmailTooLong.php ================================================ message = 'Email is too long, exceeds ' . EmailParser::EMAIL_MAX_LENGTH; } } ================================================ FILE: src/Warning/IPV6BadChar.php ================================================ message = 'Bad char in IPV6 domain literal'; $this->rfcNumber = 5322; } } ================================================ FILE: src/Warning/IPV6ColonEnd.php ================================================ message = ':: found at the end of the domain literal'; $this->rfcNumber = 5322; } } ================================================ FILE: src/Warning/IPV6ColonStart.php ================================================ message = ':: found at the start of the domain literal'; $this->rfcNumber = 5322; } } ================================================ FILE: src/Warning/IPV6Deprecated.php ================================================ message = 'Deprecated form of IPV6'; $this->rfcNumber = 5321; } } ================================================ FILE: src/Warning/IPV6DoubleColon.php ================================================ message = 'Double colon found after IPV6 tag'; $this->rfcNumber = 5322; } } ================================================ FILE: src/Warning/IPV6GroupCount.php ================================================ message = 'Group count is not IPV6 valid'; $this->rfcNumber = 5322; } } ================================================ FILE: src/Warning/IPV6MaxGroups.php ================================================ message = 'Reached the maximum number of IPV6 groups allowed'; $this->rfcNumber = 5321; } } ================================================ FILE: src/Warning/LocalTooLong.php ================================================ message = 'Local part is too long, exceeds 64 chars (octets)'; $this->rfcNumber = 5322; } } ================================================ FILE: src/Warning/NoDNSMXRecord.php ================================================ message = 'No MX DSN record was found for this email'; $this->rfcNumber = 5321; } } ================================================ FILE: src/Warning/ObsoleteDTEXT.php ================================================ rfcNumber = 5322; $this->message = 'Obsolete DTEXT in domain literal'; } } ================================================ FILE: src/Warning/QuotedPart.php ================================================ name; } if ($postToken instanceof UnitEnum) { $postToken = $postToken->name; } $this->message = "Deprecated Quoted String found between $prevToken and $postToken"; } } ================================================ FILE: src/Warning/QuotedString.php ================================================ message = "Quoted String found between $prevToken and $postToken"; } } ================================================ FILE: src/Warning/TLD.php ================================================ message = "RFC5321, TLD"; } } ================================================ FILE: src/Warning/Warning.php ================================================ message; } /** * @return int */ public function code() { return self::CODE; } /** * @return int */ public function RFCNumber() { return $this->rfcNumber; } /** * @return string */ public function __toString(): string { return $this->message() . " rfc: " . $this->rfcNumber . "internal code: " . static::CODE; } } ================================================ FILE: tests/EmailValidator/Dummy/AnotherDummyReason.php ================================================ assertInstanceOf('Doctrine\Common\Lexer\AbstractLexer', $lexer); } /** * @dataProvider getTokens * */ public function testLexerTokens($str, $token) { $lexer = new EmailLexer(); $lexer->setInput($str); $lexer->moveNext(); $lexer->moveNext(); $this->assertEquals($token, $lexer->current->type); } public function testLexerParsesMultipleSpaces() { $lexer = new EmailLexer(); $lexer->setInput(' '); $lexer->moveNext(); $lexer->moveNext(); $this->assertEquals(EmailLexer::S_SP, $lexer->current->type); $lexer->moveNext(); $this->assertEquals(EmailLexer::S_SP, $lexer->current->type); } /** * @dataProvider invalidUTF8CharsProvider */ public function testLexerParsesInvalidUTF8($char) { $lexer = new EmailLexer(); $lexer->setInput($char); $lexer->moveNext(); $lexer->moveNext(); $this->assertEquals(EmailLexer::INVALID, $lexer->current->type); } public static function invalidUTF8CharsProvider() { $chars = array(); for ($i = 0; $i < 0x100; ++$i) { $c = self::utf8Chr($i); if (preg_match('/(?=\p{Cc})(?=[^\t\n\n\r])/u', $c) && !preg_match('/\x{0000}/u', $c)) { $chars[] = array($c); } } return $chars; } protected static function utf8Chr($code_point) { if ($code_point < 0 || 0x10FFFF < $code_point || (0xD800 <= $code_point && $code_point <= 0xDFFF)) { return ''; } if ($code_point < 0x80) { $hex[0] = $code_point; $ret = chr($hex[0]); } elseif ($code_point < 0x800) { $hex[0] = 0x1C0 | $code_point >> 6; $hex[1] = 0x80 | $code_point & 0x3F; $ret = chr($hex[0]) . chr($hex[1]); } elseif ($code_point < 0x10000) { $hex[0] = 0xE0 | $code_point >> 12; $hex[1] = 0x80 | $code_point >> 6 & 0x3F; $hex[2] = 0x80 | $code_point & 0x3F; $ret = chr($hex[0]) . chr($hex[1]) . chr($hex[2]); } else { $hex[0] = 0xF0 | $code_point >> 18; $hex[1] = 0x80 | $code_point >> 12 & 0x3F; $hex[2] = 0x80 | $code_point >> 6 & 0x3F; $hex[3] = 0x80 | $code_point & 0x3F; $ret = chr($hex[0]) . chr($hex[1]) . chr($hex[2]) . chr($hex[3]); } return $ret; } public function testLexerForTab() { $lexer = new EmailLexer(); $lexer->setInput("foo\tbar"); $lexer->moveNext(); $lexer->skipUntil(EmailLexer::S_HTAB); $lexer->moveNext(); $this->assertEquals(EmailLexer::S_HTAB, $lexer->current->type); } public function testLexerForUTF8() { $lexer = new EmailLexer(); $lexer->setInput("áÇ@bar.com"); $lexer->moveNext(); $lexer->moveNext(); $this->assertEquals(EmailLexer::GENERIC, $lexer->current->type); $lexer->moveNext(); $this->assertEquals(EmailLexer::GENERIC, $lexer->current->type); } public function testLexerSearchToken() { $lexer = new EmailLexer(); $lexer->setInput("foo\tbar"); $lexer->moveNext(); $this->assertTrue($lexer->find(EmailLexer::S_HTAB)); } public static function getTokens() { return array( array("foo", EmailLexer::GENERIC), array("\r", EmailLexer::S_CR), array("\t", EmailLexer::S_HTAB), array("\r\n", EmailLexer::CRLF), array("\n", EmailLexer::S_LF), array(" ", EmailLexer::S_SP), array("@", EmailLexer::S_AT), array("IPv6", EmailLexer::S_IPV6TAG), array("::", EmailLexer::S_DOUBLECOLON), array(":", EmailLexer::S_COLON), array(".", EmailLexer::S_DOT), array("\"", EmailLexer::S_DQUOTE), array("`", EmailLexer::S_BACKTICK), array("'", EmailLexer::S_SQUOTE), array("-", EmailLexer::S_HYPHEN), array("\\", EmailLexer::S_BACKSLASH), array("/", EmailLexer::S_SLASH), array("(", EmailLexer::S_OPENPARENTHESIS), array(")", EmailLexer::S_CLOSEPARENTHESIS), array('<', EmailLexer::S_LOWERTHAN), array('>', EmailLexer::S_GREATERTHAN), array('[', EmailLexer::S_OPENBRACKET), array(']', EmailLexer::S_CLOSEBRACKET), array(';', EmailLexer::S_SEMICOLON), array(',', EmailLexer::S_COMMA), array('<', EmailLexer::S_LOWERTHAN), array('>', EmailLexer::S_GREATERTHAN), array('{', EmailLexer::S_OPENCURLYBRACES), array('}', EmailLexer::S_CLOSECURLYBRACES), array('|', EmailLexer::S_PIPE), array('~', EmailLexer::S_TILDE), array('=', EmailLexer::S_EQUAL), array('+', EmailLexer::S_PLUS), array('¿', EmailLexer::INVERT_QUESTIONMARK), array('?', EmailLexer::QUESTIONMARK), array('#', EmailLexer::NUMBER_SIGN), array('¡', EmailLexer::INVERT_EXCLAMATION), array('_', EmailLexer::S_UNDERSCORE), array('', EmailLexer::S_EMPTY), array(chr(31), EmailLexer::INVALID), array(chr(226), EmailLexer::GENERIC), array(chr(0), EmailLexer::C_NUL) ); } public function testRecordIsOffAtStart() { $lexer = new EmailLexer(); $lexer->setInput('foo-bar'); $lexer->moveNext(); $this->assertEquals('', $lexer->getAccumulatedValues()); } public function testRecord() { $lexer = new EmailLexer(); $lexer->setInput('foo-bar'); $lexer->startRecording(); $lexer->moveNext(); $lexer->moveNext(); $this->assertEquals('foo', $lexer->getAccumulatedValues()); } public function testRecordAndClear() { $lexer = new EmailLexer(); $lexer->setInput('foo-bar'); $lexer->startRecording(); $lexer->moveNext(); $lexer->moveNext(); $lexer->clearRecorded(); $this->assertEquals('', $lexer->getAccumulatedValues()); } } ================================================ FILE: tests/EmailValidator/EmailParserTest.php ================================================ parse($email); $this->assertEquals($local, $parser->getLocalPart()); $this->assertEquals($domain, $parser->getDomainPart()); } public function testMultipleEmailAddresses() { $parser = new EmailParser(new EmailLexer()); $parser->parse('some-local-part@some-random-but-large-domain-part.example.com'); $this->assertSame('some-local-part', $parser->getLocalPart()); $this->assertSame('some-random-but-large-domain-part.example.com', $parser->getDomainPart()); $parser->parse('another-local-part@another.example.com'); $this->assertSame('another-local-part', $parser->getLocalPart()); $this->assertSame('another.example.com', $parser->getDomainPart()); } } ================================================ FILE: tests/EmailValidator/EmailValidatorTest.php ================================================ getMockBuilder(EmailValidation::class)->getMock(); $validation->expects($this->once())->method("isValid")->willReturn(true); $validation->expects($this->once())->method("getWarnings")->willReturn([]); $validation->expects($this->once())->method("getError")->willReturn($invalidEmail); $this->assertTrue($validator->isValid("example@example.com", $validation)); } public function testMultipleValidation() { $validator = new EmailValidator(); $validation = $this->getMockBuilder(EmailValidation::class)->getMock(); $validation->expects($this->once())->method("isValid")->willReturn(true); $validation->expects($this->once())->method("getWarnings")->willReturn([]); $validation->expects($this->never(2))->method("getError"); $multiple = new MultipleValidationWithAnd([$validation]); $this->assertTrue($validator->isValid("example@example.com", $multiple)); } public function testValidationIsFalse() { $invalidEmail = new InvalidEmail(new DummyReason(), ''); $validator = new EmailValidator(); $validation = $this->getMockBuilder(EmailValidation::class)->getMock(); $validation->expects($this->once())->method("isValid")->willReturn(false); $validation->expects($this->once())->method("getWarnings")->willReturn([]); $validation->expects($this->once())->method("getError")->willReturn($invalidEmail); $this->assertFalse($validator->isValid("example@example.com", $validation)); $this->assertEquals(false, $validator->hasWarnings()); $this->assertEquals([], $validator->getWarnings()); $this->assertEquals($invalidEmail, $validator->getError()); } } ================================================ FILE: tests/EmailValidator/LexerTokensTest.php ================================================ markTestIncomplete("implement better lexer tokens"); } } ================================================ FILE: tests/EmailValidator/Reason/MultipleErrorsTest.php ================================================ addReason($error1); $multiError->addReason($error2); $this->assertCount(1, $multiError->getReasons()); } public function testRegisterDifferentReasons() { $error1 = new DummyReason(); $error2 = new AnotherDummyReason(); $expectedReason = $error1->description() . PHP_EOL . $error2->description() . PHP_EOL; $multiError = new MultipleErrors(); $multiError->addReason($error1); $multiError->addReason($error2); $this->assertCount(2, $multiError->getReasons()); $this->assertEquals($expectedReason, $multiError->description()); $this->assertEquals($error1, $multiError->reason()); } public function testRetrieveFirstReasonWithReasonCodeEqualsZero(): void { $error1 = new DummyReason(); $multiError = new MultipleErrors(); $multiError->addReason($error1); $this->assertEquals($error1, $multiError->reason()); } public function testRetrieveFirstReasonWithReasonCodeDistinctToZero(): void { $error1 = new AnotherDummyReason(); $multiError = new MultipleErrors(); $multiError->addReason($error1); $this->assertEquals($error1, $multiError->reason()); } public function testRetrieveFirstReasonWithNoReasonAdded() { $emptyReason = new EmptyReason(); $multiError = new MultipleErrors(); $this->assertEquals($emptyReason, $multiError->reason()); } } ================================================ FILE: tests/EmailValidator/Result/ResultTest.php ================================================ assertTrue($result->isValid()); $this->assertEquals($expectedCode, $result->code()); $this->assertEquals($expectedDescription, $result->description()); } public function testResultIsInvalidEmail() { $reason = new CharNotAllowed(); $token = "T"; $result = new InvalidEmail($reason, $token); $expectedCode = $reason->code(); $expectedDescription = $reason->description() . " in char " . $token; $this->assertFalse($result->isValid()); $this->assertEquals($expectedCode, $result->code()); $this->assertEquals($expectedDescription, $result->description()); } } ================================================ FILE: tests/EmailValidator/Validation/DNSCheckValidationTest.php ================================================ assertTrue($validation->isValid($validEmail, new EmailLexer())); } public function testInvalidDNS() { $validation = new DNSCheckValidation(); $this->assertFalse($validation->isValid("example@invalid.example.com", new EmailLexer())); } /** * @dataProvider localOrReservedEmailsProvider */ public function testLocalOrReservedDomainError($localOrReservedEmails) { $validation = new DNSCheckValidation(); $expectedError = new InvalidEmail(new LocalOrReservedDomain(), $localOrReservedEmails); $validation->isValid($localOrReservedEmails, new EmailLexer()); $this->assertEquals($expectedError, $validation->getError()); } public function testDomainAcceptsNoMailError() { $validation = new DNSCheckValidation(); $expectedError = new InvalidEmail(new DomainAcceptsNoMail(), ""); $isValidResult = $validation->isValid("nullmx@example.com", new EmailLexer()); $this->assertEquals($expectedError, $validation->getError()); $this->assertFalse($isValidResult); } public function testDNSWarnings() { $this->markTestSkipped('Need to found a domain with AAAA records and no MX that fails later in the validations'); $validation = new DNSCheckValidation(); $expectedWarnings = [NoDNSMXRecord::CODE => new NoDNSMXRecord()]; $validation->isValid("example@invalid.example.com", new EmailLexer()); $this->assertEquals($expectedWarnings, $validation->getWarnings()); } public function testNoDNSError() { $validation = new DNSCheckValidation(); $expectedError = new InvalidEmail(new NoDNSRecord(), ''); $validation->isValid("example@invalid.example.com", new EmailLexer()); $this->assertEquals($expectedError, $validation->getError()); } /** * @group flaky */ public function testUnableToGetDNSRecord() { error_reporting(\E_ALL); // UnableToGetDNSRecord raises on network errors (e.g. timeout) that we can‘t emulate in tests (for sure), // but we can simulate with the wrapper helper $wrapper = new class extends DNSGetRecordWrapper { public function getRecords(string $host, int $type) : DNSRecords { return new DNSRecords([], true); } }; $validation = new DNSCheckValidation($wrapper); $expectedError = new InvalidEmail(new UnableToGetDNSRecord(), ''); $validation->isValid('example@invalid.example.com', new EmailLexer()); $this->assertEquals($expectedError, $validation->getError()); } public function testMissingTypeKey() { $wrapper = new class extends DNSGetRecordWrapper { public function getRecords(string $host, int $type): DNSRecords { return new DNSRecords(['host' => 'test']); } }; $validation = new DNSCheckValidation($wrapper); $expectedError = new InvalidEmail(new NoDNSRecord(), ''); $validation->isValid('example@invalid.example.com', new EmailLexer()); $this->assertEquals($expectedError, $validation->getError()); } } ================================================ FILE: tests/EmailValidator/Validation/Extra/SpoofCheckValidationTest.php ================================================ assertTrue($validation->isValid($email, new EmailLexer())); } public function testEmailWithSpoofsIsInvalid() { $validation = new SpoofCheckValidation(); $this->assertFalse($validation->isValid("Кириллица"."latin漢字"."ひらがな"."カタカナ", new EmailLexer())); } public static function validUTF8EmailsProvider() { return [ // Cyrillic ['Кириллица@Кириллица'], // Latin + Han + Hiragana + Katakana ["latin漢字"."ひらがな"."カタカナ"."@example.com"], // Latin + Han + Hangul ["latin"."漢字"."조선말"."@example.com"], // Latin + Han + Bopomofo ["latin"."漢字"."ㄅㄆㄇㄈ"."@example.com"] ]; } } ================================================ FILE: tests/EmailValidator/Validation/IsEmailFunctionTests.php ================================================ assertFalse($validator->isValid($email, $validations), "Tested email " . $email); } public function isEmailTestSuite() { $testSuite = __DIR__ . '/../../resources/is_email_tests.xml'; $document = new \DOMDocument(); $document->load($testSuite); $elements = $document->getElementsByTagName('test'); $tests = []; foreach($elements as $testElement) { $childNode = $testElement->childNodes; $tests[][] = ($childNode->item(1)->getAttribute('value')); } return $tests; } } ================================================ FILE: tests/EmailValidator/Validation/MessageIDValidationTest.php ================================================ assertTrue($validator->isValid($messageID, new EmailLexer())); } public static function validMessageIDs() : array { return [ ['a@b.c+&%$.d'], ['a.b+&%$.c@d'], ['a@ä'], ]; } /** * @dataProvider invalidMessageIDs */ public function testInvalidMessageIDs(string $messageID) { $validator = new MessageIDValidation(); $this->assertFalse($validator->isValid($messageID, new EmailLexer())); } public static function invalidMessageIDs() : array { return [ ['example'], ['example@with space'], ['example@iana.'], ['example@ia\na.'], /** * RFC 2822, section 3.6.4, Page 25 * Since the msg-id has * a similar syntax to angle-addr (identical except that comments and * folding white space are not allowed), a good method is to put the * domain name (or a domain literal IP address) of the host on which the * message identifier was created on the right hand side of the "@", and * put a combination of the current absolute date and time along with * some other currently unique (perhaps sequential) identifier available * on the system (for example, a process id number) on the left hand * side. */ ['example(comment)@example.com'], ["\r\nFWS@example.com"] ]; } public function testInvalidMessageIDsWithError() { $this->markTestIncomplete("missing error check"); } } ================================================ FILE: tests/EmailValidator/Validation/MultipleValidationWithAndTest.php ================================================ getMockBuilder(EmailValidation::class)->getMock(); $validationTrue->expects($this->any())->method("isValid")->willReturn(true); $validationTrue->expects($this->any())->method("getWarnings")->willReturn([]); $validationFalse = $this->getMockBuilder(EmailValidation::class)->getMock(); $validationFalse->expects($this->any())->method("isValid")->willReturn(false); $validationFalse->expects($this->any())->method("getWarnings")->willReturn([]); $validationFalse->expects($this->any())->method("getError")->willReturn($invalidEmail); $multipleValidation = new MultipleValidationWithAnd([$validationTrue, $validationFalse]); $this->assertFalse($multipleValidation->isValid("exmpale@example.com", $lexer)); } public function testEmptyListIsNotAllowed() { $this->expectException(EmptyValidationList::class); new MultipleValidationWithAnd([]); } public function testValidationIsValid() { $lexer = new EmailLexer(); $validation = $this->getMockBuilder(EmailValidation::class)->getMock(); $validation->expects($this->any())->method("isValid")->willReturn(true); $validation->expects($this->once())->method("getWarnings")->willReturn([]); $validation->expects($this->any())->method("getError")->willReturn(null); $multipleValidation = new MultipleValidationWithAnd([$validation]); $this->assertTrue($multipleValidation->isValid("example@example.com", $lexer)); $this->assertNull($multipleValidation->getError()); } public function testAccumulatesWarnings() { $invalidEmail = new InvalidEmail(new DummyReason(), ''); $warnings1 = [ AddressLiteral::CODE => new AddressLiteral() ]; $warnings2 = [ DomainLiteral::CODE => new DomainLiteral() ]; $expectedResult = array_merge($warnings1, $warnings2); $lexer = new EmailLexer(); $validation1 = $this->getMockBuilder(EmailValidation::class)->getMock(); $validation1->expects($this->any())->method("isValid")->willReturn(true); $validation1->expects($this->once())->method("getWarnings")->willReturn($warnings1); $validation1->expects($this->any())->method("getError")->willReturn($invalidEmail); $validation2 = $this->getMockBuilder(EmailValidation::class)->getMock(); $validation2->expects($this->any())->method("isValid")->willReturn(false); $validation2->expects($this->once())->method("getWarnings")->willReturn($warnings2); $validation2->expects($this->any())->method("getError")->willReturn($invalidEmail); $multipleValidation = new MultipleValidationWithAnd([$validation1, $validation2]); $multipleValidation->isValid("example@example.com", $lexer); $this->assertEquals($expectedResult, $multipleValidation->getWarnings()); } public function testGathersAllTheErrors() { $invalidEmail = new InvalidEmail(new DummyReason(), ''); $invalidEmail2 = new InvalidEmail(new AnotherDummyReason(), ''); $error1 = new DummyReason(); $error2 = new AnotherDummyReason(); $expectedResult = new MultipleErrors(); $expectedResult->addReason($error1); $expectedResult->addReason($error2); $lexer = new EmailLexer(); $validation1 = $this->getMockBuilder(EmailValidation::class)->getMock(); $validation1->expects($this->once())->method("isValid")->willReturn(false); $validation1->expects($this->once())->method("getWarnings")->willReturn([]); $validation1->expects($this->exactly(2))->method("getError")->willReturn($invalidEmail); $validation2 = $this->getMockBuilder(EmailValidation::class)->getMock(); $validation2->expects($this->once())->method("isValid")->willReturn(false); $validation2->expects($this->once())->method("getWarnings")->willReturn([]); $validation2->expects($this->exactly(2))->method("getError")->willReturn($invalidEmail2); $multipleValidation = new MultipleValidationWithAnd([$validation1, $validation2]); $multipleValidation->isValid("example@example.com", $lexer); $this->assertEquals($expectedResult, $multipleValidation->getError()); } public function testStopsAfterFirstError() { $invalidEmail = new InvalidEmail(new DummyReason(), ''); $invalidEmail2 = new InvalidEmail(new AnotherDummyReason(), ''); $error1 = new DummyReason(); $expectedResult = new MultipleErrors(); $expectedResult->addReason($error1); $lexer = new EmailLexer(); $validation1 = $this->getMockBuilder(EmailValidation::class)->getMock(); $validation1->expects($this->any())->method("isValid")->willReturn(false); $validation1->expects($this->once())->method("getWarnings")->willReturn([]); $validation1->expects($this->exactly(2))->method("getError")->willReturn($invalidEmail); $validation2 = $this->getMockBuilder(EmailValidation::class)->getMock(); $validation2->expects($this->any())->method("isValid")->willReturn(false); $validation2->expects($this->never())->method("getWarnings")->willReturn([]); $validation1->expects($this->exactly(2))->method("getError")->willReturn($invalidEmail2); $multipleValidation = new MultipleValidationWithAnd([$validation1, $validation2], MultipleValidationWithAnd::STOP_ON_ERROR); $multipleValidation->isValid("example@example.com", $lexer); $this->assertEquals($expectedResult, $multipleValidation->getError()); } public function testBreakOutOfLoopWhenError() { $invalidEmail = new InvalidEmail(new DummyReason(), ''); $error1 = new DummyReason(); $expectedResult = new MultipleErrors(); $expectedResult->addReason($error1); $lexer = new EmailLexer(); $validation1 = $this->getMockBuilder(EmailValidation::class)->getMock(); $validation1->expects($this->any())->method("isValid")->willReturn(false); $validation1->expects($this->once())->method("getWarnings")->willReturn([]); $validation1->expects($this->exactly(2))->method("getError")->willReturn($invalidEmail); $validation2 = $this->getMockBuilder(EmailValidation::class)->getMock(); $validation2->expects($this->never())->method("isValid"); $validation2->expects($this->never())->method("getWarnings"); $validation2->expects($this->never())->method("getError"); $multipleValidation = new MultipleValidationWithAnd([$validation1, $validation2], MultipleValidationWithAnd::STOP_ON_ERROR); $multipleValidation->isValid("example@example.com", $lexer); $this->assertEquals($expectedResult, $multipleValidation->getError()); } public function testBreakoutOnInvalidEmail() { $lexer = new EmailLexer(); $validationNotCalled = $this->getMockBuilder(EmailValidation::class)->getMock(); $validationNotCalled->expects($this->never())->method("isValid"); $validationNotCalled->expects($this->never())->method("getWarnings"); $validationNotCalled->expects($this->never())->method("getError"); $multipleValidation = new MultipleValidationWithAnd([new RFCValidation(), $validationNotCalled], MultipleValidationWithAnd::STOP_ON_ERROR); $this->assertFalse($multipleValidation->isValid("invalid-email", $lexer)); } } ================================================ FILE: tests/EmailValidator/Validation/NoRFCWarningsValidationTest.php ================================================ assertFalse($validation->isValid('non-email-string', new EmailLexer())); $this->assertInstanceOf(NoDomainPart::class, $validation->getError()->reason()); } public function testEmailWithWarningsIsInvalid() { $validation = new NoRFCWarningsValidation(); $this->assertFalse($validation->isValid('test()@example.com', new EmailLexer())); $this->assertInstanceOf(RFCWarnings::class, $validation->getError()->reason()); } /** * @dataProvider getValidEmailsWithoutWarnings */ public function testEmailWithoutWarningsIsValid($email) { $validation = new NoRFCWarningsValidation(); $this->assertTrue($validation->isValid('example@example.com', new EmailLexer())); $this->assertTrue($validation->isValid($email, new EmailLexer())); $this->assertNull($validation->getError()); } public static function getValidEmailsWithoutWarnings() { return [ ['example@example.com',], [sprintf('example@%s.com', str_repeat('ъ', 40)),], ]; } } ================================================ FILE: tests/EmailValidator/Validation/RFCValidationDomainPartTest.php ================================================ validator = new RFCValidation(); $this->lexer = new EmailLexer(); } protected function tearDown() : void { $this->validator = null; } /** * @dataProvider getValidEmails */ public function testValidEmails($email) { $this->assertTrue($this->validator->isValid($email, $this->lexer)); } public static function getValidEmails() { return array( ['fabien@symfony.com'], ['example@example.co.uk'], ['example@localhost'], ['example@faked(fake).co.uk'], ['инфо@письмо.рф'], ['müller@möller.de'], ["1500111@профи-инвест.рф"], ['validipv6@[IPv6:2001:db8:1ff::a0b:dbd0]'], ['validipv4@[127.0.0.0]'], ['validipv4@127.0.0.0'], ['withhyphen@domain-exam.com'], ['valid_long_domain@71846jnrsoj91yfhc18rkbrf90ue3onl8y46js38kae8inz0t1.5a-xdycuau.na49.le.example.com'] ); } /** * @dataProvider getInvalidEmails */ public function testInvalidEmails($email) { $this->assertFalse($this->validator->isValid($email, $this->lexer)); } public static function getInvalidEmails() { return [ ['test@example.com test'], ['example@example@example.co.uk'], ['test_exampel@example.fr]'], ['example@local\host'], ['example@localhost\\'], ['example@localhost.'], ['username@ example . com'], ['username@ example.com'], ['example@(fake].com'], ['example@(fake.com'], ['username@example,com'], ['test@' . chr(226) . '.org'], ['test@iana.org \r\n'], ['test@iana.org \r\n '], ['test@iana.org \r\n \r\n'], ['test@iana.org \r\n\r\n'], ['test@iana.org \r\n\r\n '], ['test@iana/icann.org'], ['test@foo;bar.com'], ['test@example..com'], ["test@examp'le.com"], ['email.email@email."'], ['test@email>'], ['test@email<'], ['test@email{'], ['username@examp,le.com'], ['test@ '], ['invalidipv4@[127.\0.0.0]'], ['test@example.com []'], ['test@example.com. []'], ['test@test. example.com'], ['example@toolonglocalparttoolonglocalparttoolonglocalparttoolonglocalparttoolonglocalparttoolonglocal'. 'parttoolonglocalparttoolonglocalparttoolonglocalparttoolonglocalparttoolonglocalparttoolonglocalpart'. 'toolonglocalparttoolonglocalparttoolonglocalparttoolonglocalpar'], ['example@toolonglocalparttoolonglocalparttoolonglocalparttoolonglocalpart.co.uk'], ['example@toolonglocalparttoolonglocalparttoolonglocalparttoolonglocalpart.test.co.uk'], ['example@test.toolonglocalparttoolonglocalparttoolonglocalparttoolonglocalpart.co.uk'], ['test@email*a.com'], ['test@email!a.com'], ['test@email&a.com'], ['test@email^a.com'], ['test@email%a.com'], ['test@email$a.com'], ['test@email`a.com'], ['test@email|a.com'], ['test@email~a.com'], ['test@email{a.com'], ['test@email}a.com'], ['test@email=a.com'], ['test@email+a.com'], ['test@email_a.com'], ['test@email¡a.com'], ['test@email?a.com'], ['test@email#a.com'], ['test@email¨a.com'], ['test@email€a.com'], ['test@email$a.com'], ['test@email£a.com'], ]; } /** * @dataProvider getInvalidEmailsWithErrors */ public function testInvalidEmailsWithErrorsCheck($error, $email) { $this->assertFalse($this->validator->isValid($email, $this->lexer)); $this->assertEquals($error, $this->validator->getError()); } public static function getInvalidEmailsWithErrors() { return [ [new InvalidEmail(new NoDomainPart(), ''), 'example@'], [new InvalidEmail(new DomainHyphened('Hypen found near DOT'), '-'), 'example@example-.co.uk'], [new InvalidEmail(new CRNoLF(), "\r"), "example@example\r.com"], [new InvalidEmail(new DomainHyphened('Hypen found at the end of the domain'), '-'), 'example@example-'], [new InvalidEmail(new ConsecutiveAt(), '@'), 'example@@example.co.uk'], [new InvalidEmail(new ConsecutiveDot(), '.'), 'example@example..co.uk'], [new InvalidEmail(new DotAtStart(), '.'), 'example@.localhost'], [new InvalidEmail(new DomainHyphened('After AT'), '-'), 'example@-localhost'], [new InvalidEmail(new DotAtEnd(), ''), 'example@localhost.'], [new InvalidEmail(new UnOpenedComment(), ')'), 'example@comment)localhost'], [new InvalidEmail(new UnOpenedComment(), ')'), 'example@localhost(comment))'], [new InvalidEmail(new UnOpenedComment(), 'com'), 'example@(comment))example.com'], [new InvalidEmail(new ExpectingDTEXT(), '['), "example@[[]"], [new InvalidEmail(new CRNoLF(), "\r"), "example@exa\rmple.co.uk"], [new InvalidEmail(new CRNoLF(), "["), "example@[\r]"], [new InvalidEmail(new ExpectingATEXT('Invalid token in domain: ,'), ','), 'example@exam,ple.com'], [new InvalidEmail(new ExpectingATEXT("Invalid token in domain: '"), "'"), "test@example.com'"], [new InvalidEmail(new LabelTooLong(), "."), sprintf('example@%s.com', str_repeat('ъ', 64))], [new InvalidEmail(new LabelTooLong(), "."), sprintf('example@%s.com', str_repeat('a4t', 22))], [new InvalidEmail(new LabelTooLong(), ""), sprintf('example@%s', str_repeat('a4t', 22))], ]; } /** * @dataProvider getValidEmailsWithWarnings */ public function testValidEmailsWithWarningsCheck($expectedWarnings, $email) { $this->assertTrue($this->validator->isValid($email, $this->lexer)); $warnings = $this->validator->getWarnings(); $this->assertCount( count($expectedWarnings), $warnings, "Expected: " . implode(",", $expectedWarnings) . " and got: " . PHP_EOL . implode(PHP_EOL, $warnings) ); foreach ($warnings as $warning) { $this->assertArrayHasKey($warning->code(), $expectedWarnings); } } public static function getValidEmailsWithWarnings() { return [ //Check if this is actually possible //[[CFWSNearAt::CODE], 'example@ invalid.example.com'], [[Comment::CODE], 'example@invalid.example(examplecomment).com'], [[AddressLiteral::CODE, TLD::CODE], 'example@[127.0.0.1]'], [[AddressLiteral::CODE, TLD::CODE], 'example@[IPv6:2001:0db8:85a3:0000:0000:8a2e:0370:7334]'], [[AddressLiteral::CODE, IPV6Deprecated::CODE, TLD::CODE], 'example@[IPv6:2001:0db8:85a3:0000:0000:8a2e:0370::]'], [[AddressLiteral::CODE, IPV6MaxGroups::CODE, TLD::CODE], 'example@[IPv6:2001:0db8:85a3:0000:0000:8a2e:0370:7334::]'], [[AddressLiteral::CODE, IPV6DoubleColon::CODE, TLD::CODE], 'example@[IPv6:1::1::1]'], [[ObsoleteDTEXT::CODE, DomainLiteral::CODE, TLD::CODE], "example@[\n]"], [[DomainLiteral::CODE, TLD::CODE], 'example@[::1]'], [[DomainLiteral::CODE, TLD::CODE], 'example@[::123.45.67.178]'], [ [IPV6ColonStart::CODE, AddressLiteral::CODE, IPV6GroupCount::CODE, TLD::CODE], 'example@[IPv6::2001:0db8:85a3:0000:0000:8a2e:0370:7334]' ], [ [AddressLiteral::CODE, IPV6BadChar::CODE, TLD::CODE], 'example@[IPv6:z001:0db8:85a3:0000:0000:8a2e:0370:7334]' ], [ [AddressLiteral::CODE, IPV6ColonEnd::CODE, TLD::CODE], 'example@[IPv6:2001:0db8:85a3:0000:0000:8a2e:0370:]' ], ]; } public static function invalidUTF16Chars() { return [ ['example@symƒony.com'], ]; } /** * @dataProvider invalidUTF16Chars */ public function testInvalidUTF16($email) { $this->markTestSkipped('Util finding a way to control this kind of chars'); $this->assertFalse($this->validator->isValid($email, $this->lexer)); } } ================================================ FILE: tests/EmailValidator/Validation/RFCValidationTest.php ================================================ validator = new RFCValidation(); $this->lexer = new EmailLexer(); } protected function tearDown() : void { $this->validator = null; } /** * @dataProvider getValidEmails */ public function testValidEmails($email) { $this->assertTrue($this->validator->isValid($email, $this->lexer)); } public static function getValidEmails() { return array( ['â@iana.org'], ['fabien@symfony.com'], ['example@example.co.uk'], ['fabien_potencier@example.fr'], ['fab\'ien@symfony.com'], ['fab\ ien@symfony.com'], ['example((example))@fakedfake.co.uk'], ['fabien+a@symfony.com'], ['exampl=e@example.com'], ['инфо@письмо.рф'], ['"username"@example.com'], ['"user,name"@example.com'], ['"user name"@example.com'], ['"user@name"@example.com'], ['"user\"name"@example.com'], ['"\a"@iana.org'], ['"test\ test"@iana.org'], ['""@iana.org'], ['"\""@iana.org'], ['müller@möller.de'], ["1500111@профи-инвест.рф"], [sprintf('example@%s.com', str_repeat('ъ', 40))], ); } /** * @dataProvider getValidEmailsWithWarnings */ public function testValidEmailsWithWarningsCheck($email, $expectedWarnings) { $this->assertTrue($this->validator->isValid($email, $this->lexer)); $this->assertEquals($expectedWarnings, $this->validator->getWarnings()); } public static function getValidEmailsWithWarnings() { return [ ['a5aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa@example.com', [new LocalTooLong()]], ['example@example', [new TLD()]], ['example @invalid.example.com', [new CFWSNearAt()]], ['example(examplecomment)@invalid.example.com',[new Comment(), new CFWSNearAt()]], ["\"\t\"@invalid.example.com", [new QuotedString("", '"'), new CFWSWithFWS(),]], ["\"\r\"@invalid.example.com", [new QuotedString('', '"'), new CFWSWithFWS(),]], ['"example"@invalid.example.com', [new QuotedString('', '"')]], ['too_long_localpart_too_long_localpart_too_long_localpart_too_long_localpart@invalid.example.com', [new LocalTooLong()]], ]; } public function testInvalidUTF8Email() { $email = "\x80\x81\x82@\x83\x84\x85.\x86\x87\x88"; $this->assertFalse($this->validator->isValid($email, $this->lexer)); } /** * @dataProvider getInvalidEmails */ public function testInvalidEmails($email) { $this->assertFalse($this->validator->isValid($email, $this->lexer)); } public static function getInvalidEmails() { return [ ['user name@example.com'], ['user name@example.com'], ['example.@example.co.uk'], ['example@example@example.co.uk'], ['(test_exampel@example.fr'], ['example(example]example@example.co.uk'], ['.example@localhost'], ['ex\ample@localhost'], ['user name@example.com'], ['usern,ame@example.com'], ['user[na]me@example.com'], ['"""@iana.org'], ['"\"@iana.org'], ['"test"test@iana.org'], ['"test""test"@iana.org'], ['"test"."test"@iana.org'], ['"test".test@iana.org'], ['"test"' . chr(0) . '@iana.org'], ['"test\"@iana.org'], [chr(226) . '@iana.org'], ['\r\ntest@iana.org'], ['\r\n test@iana.org'], ['\r\n \r\ntest@iana.org'], ['\r\n \r\ntest@iana.org'], ['\r\n \r\n test@iana.org'], ['test;123@foobar.com'], ['examp║le@symfony.com'], ['example@invalid-.domain.com'], ['example@-invalid.com'], ['0'], [0], ]; } /** * @dataProvider getInvalidEmailsWithErrors */ public function testInvalidDEmailsWithErrorsCheck($error, $email) { $this->assertFalse($this->validator->isValid($email, $this->lexer)); $this->assertEquals($error, $this->validator->getError()); } public static function getInvalidEmailsWithErrors() { return [ [new InvalidEmail(new NoLocalPart(), "@"), '@example.co.uk'], [new InvalidEmail(new ConsecutiveDot(), '.'), 'example..example@example.co.uk'], [new InvalidEmail(new ExpectingATEXT('Invalid token found'), '<'), '@example.fr'], [new InvalidEmail(new DotAtStart(), '.'), '.example@localhost'], [new InvalidEmail(new DotAtEnd(), '.'), 'example.@example.co.uk'], [new InvalidEmail(new UnclosedComment(), '('), '(example@localhost'], [new InvalidEmail(new UnclosedQuotedString(), '"'), '"example@localhost'], [ new InvalidEmail( new ExpectingATEXT('https://tools.ietf.org/html/rfc5322#section-3.2.4 - quoted string should be a unit'), '"'), 'exa"mple@localhost' ], [new InvalidEmail(new UnOpenedComment(), ')'), 'comment)example@localhost'], [new InvalidEmail(new UnOpenedComment(), ')'), 'example(comment))@localhost'], [new InvalidEmail(new AtextAfterCFWS(), "\n"), "exampl\ne@example.co.uk"], [new InvalidEmail(new AtextAfterCFWS(), "\t"), "exampl\te@example.co.uk"], [new InvalidEmail(new CRNoLF(), "\r"), "exam\rple@example.co.uk"], ]; } }