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