1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace DavidGarcia\ValueObject\Primitive\StringAlternatives; |
6
|
|
|
|
7
|
|
|
use DavidGarcia\ValueObject\Exception\InvalidValueException; |
8
|
|
|
use DavidGarcia\ValueObject\Primitive\StringValue; |
9
|
|
|
use Egulias\EmailValidator\EmailValidator; |
10
|
|
|
use Egulias\EmailValidator\Result\InvalidEmail; |
11
|
|
|
use Egulias\EmailValidator\Validation\DNSCheckValidation; |
12
|
|
|
use Egulias\EmailValidator\Validation\RFCValidation; |
13
|
|
|
use InvalidArgumentException; |
14
|
|
|
use Webmozart\Assert\Assert; |
15
|
|
|
|
16
|
|
|
class EmailValue extends StringValue |
17
|
|
|
{ |
18
|
|
|
/** |
19
|
|
|
* {@inheritdoc} |
20
|
|
|
*/ |
21
|
9 |
|
public static function create(string $value, bool $cache = false): StringValue |
22
|
|
|
{ |
23
|
9 |
|
$trimmed = trim($value); |
24
|
|
|
|
25
|
|
|
try { |
26
|
9 |
|
Assert::stringNotEmpty($trimmed, 'Email value cannot be empty'); |
27
|
1 |
|
} catch (InvalidArgumentException $exception) { |
28
|
1 |
|
throw new InvalidValueException($exception->getMessage(), $exception); |
29
|
|
|
} |
30
|
|
|
|
31
|
8 |
|
$validator = new EmailValidator(); |
32
|
|
|
|
33
|
8 |
|
if (!$validator->isValid($trimmed, new RFCValidation())) { |
34
|
1 |
|
throw new InvalidValueException(self::emailValidatorError('RFC Validation has failed', $validator->getError())); |
|
|
|
|
35
|
|
|
} |
36
|
|
|
|
37
|
7 |
|
if (!$validator->isValid($trimmed, new DNSCheckValidation())) { |
38
|
1 |
|
throw new InvalidValueException(self::emailValidatorError('DNS Validation has failed', $validator->getError())); |
39
|
|
|
} |
40
|
|
|
|
41
|
6 |
|
return parent::create($trimmed, $cache); |
42
|
|
|
} |
43
|
|
|
|
44
|
|
|
/** |
45
|
|
|
* Creates a string message to expose the validator error. |
46
|
|
|
* |
47
|
|
|
* @param string $message Generic error message |
48
|
|
|
* @param InvalidEmail $error Error captured by the validator |
49
|
|
|
* |
50
|
|
|
* @return string The error message including the validator reason for failure |
51
|
|
|
*/ |
52
|
2 |
|
private static function emailValidatorError(string $message, InvalidEmail $error): string |
53
|
|
|
{ |
54
|
2 |
|
return sprintf('%s: %s', $message, $error->description()); |
55
|
|
|
} |
56
|
|
|
} |
57
|
|
|
|