Passed
Push — master ( 2395d0...e80e6b )
by John
05:44
created

EmailAddress::getSanitizedGmailAddress()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 7
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 5
c 0
b 0
f 0
dl 0
loc 7
rs 10
cc 1
nc 1
nop 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace EmailValidator;
6
7
class EmailAddress
8
{
9
    /**
10
     * @var string
11
     */
12
    private $email;
13
14
    public function __construct(string $email)
15
    {
16
        $this->email = $email;
17
    }
18
19
    /**
20
     * Returns the domain name portion of the email address.
21
     *
22
     * @return string|null
23
     */
24
    public function getDomain(): ?string
25
    {
26
        return explode('@', $this->email)[1] ?? null;
27
    }
28
29
    /**
30
     * Returns the email address.
31
     *
32
     * @return string
33
     */
34
    public function getEmailAddress(): string
35
    {
36
        return $this->email;
37
    }
38
39
    /**
40
     * Returns the username of the email address.
41
     *
42
     * @since 1.1.0
43
     * @return string|null
44
     */
45
    private function getUsername(): ?string
46
    {
47
        return explode('@', $this->email)[0] ?? '';
48
    }
49
50
    /**
51
     * Determines if a gmail account is using the "plus trick".
52
     *
53
     * @since 1.1.0
54
     * @return bool
55
     */
56
    public function isGmailWithPlusChar(): bool
57
    {
58
        $result = false;
59
        if (in_array($this->getDomain(), ['gmail.com', 'googlemail.com'])) {
60
            $result = strpos($this->getUsername(), '+') !== false;
61
        }
62
63
        return $result;
64
    }
65
66
    /**
67
     * Returns a gmail address without the "plus trick" portion of the email address.
68
     *
69
     * @since 1.1.0
70
     * @return string
71
     */
72
    public function getGmailAddressWithoutPlus(): string
73
    {
74
        return preg_replace('/^(.+?)(\+.+?)(@.+)/', '$1$3', $this->getEmailAddress());
75
    }
76
77
    /**
78
     * Returns a gmail address without the "plus trick" portion of the email address and all dots removed.
79
     *
80
     * @since 1.1.4
81
     * @return string
82
     */
83
    public function getSanitizedGmailAddress(): string
84
    {
85
        $email = new EmailAddress($this->getGmailAddressWithoutPlus());
86
        return sprintf(
87
            '%s@%s',
88
            str_replace('.', '', $email->getUsername()),
89
            $email->getDomain()
90
        );
91
    }
92
}
93