AtomValidator   A
last analyzed

Complexity

Total Complexity 6

Size/Duplication

Total Lines 45
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 6
eloc 12
c 1
b 0
f 0
dl 0
loc 45
rs 10

2 Methods

Rating   Name   Duplication   Size   Complexity  
A validateAtom() 0 8 2
A validate() 0 18 4
1
<?php
2
3
declare(strict_types=1);
4
5
namespace EmailValidator\Validator\LocalPart;
6
7
/**
8
 * Validates the atom format of local parts in email addresses
9
 */
10
class AtomValidator
11
{
12
    // Character sets for unquoted local part
13
    private const ALLOWED_CHARS = '!#$%&\'*+-/=?^_`{|}~.';
14
15
    /**
16
     * Validates a dot-atom format local part
17
     *
18
     * @param string $localPart The unquoted local part to validate
19
     * @return bool True if the unquoted local part is valid
20
     */
21
    public function validate(string $localPart): bool
22
    {
23
        // Empty local part is invalid
24
        if ($localPart === '') {
25
            return false;
26
        }
27
28
        // Split into atoms
29
        $atoms = explode('.', $localPart);
30
31
        // Check each atom
32
        foreach ($atoms as $atom) {
33
            if (!$this->validateAtom($atom)) {
34
                return false;
35
            }
36
        }
37
38
        return true;
39
    }
40
41
    /**
42
     * Validates a single atom
43
     *
44
     * @param string $atom The atom to validate
45
     * @return bool True if the atom is valid
46
     */
47
    private function validateAtom(string $atom): bool
48
    {
49
        if ($atom === '') {
50
            return false;
51
        }
52
53
        // Check for valid characters
54
        return (bool)preg_match('/^[a-zA-Z0-9!#$%&\'*+\-\/=?^_`{|}~]+$/', $atom);
55
    }
56
}