1
|
|
|
<?php declare(strict_types=1); |
2
|
|
|
/** |
3
|
|
|
* This file is part of the daikon-cqrs/value-object project. |
4
|
|
|
* |
5
|
|
|
* For the full copyright and license information, please view the LICENSE |
6
|
|
|
* file that was distributed with this source code. |
7
|
|
|
*/ |
8
|
|
|
|
9
|
|
|
namespace Daikon\ValueObject; |
10
|
|
|
|
11
|
|
|
use Daikon\Interop\Assertion; |
12
|
|
|
use Daikon\Interop\MakeEmptyInterface; |
13
|
|
|
|
14
|
|
|
final class Email implements MakeEmptyInterface, ValueObjectInterface |
15
|
|
|
{ |
16
|
|
|
private Text $localPart; |
17
|
|
|
|
18
|
|
|
private Text $domain; |
19
|
|
|
|
20
|
|
|
/** @param null|string $value */ |
21
|
6 |
|
public static function fromNative($value): self |
22
|
|
|
{ |
23
|
6 |
|
Assertion::nullOrString($value, 'Trying to create Email VO from unsupported value type.'); |
24
|
6 |
|
if (empty($value)) { |
25
|
1 |
|
return self::makeEmpty(); |
26
|
|
|
} |
27
|
6 |
|
Assertion::email($value, 'Trying to create email from invalid string.'); |
28
|
6 |
|
$parts = explode('@', $value); |
29
|
6 |
|
return new self(Text::fromNative($parts[0]), Text::fromNative($parts[1])); |
30
|
|
|
} |
31
|
|
|
|
32
|
2 |
|
public static function makeEmpty(): self |
33
|
|
|
{ |
34
|
2 |
|
return new self(Text::makeEmpty(), Text::makeEmpty()); |
35
|
|
|
} |
36
|
|
|
|
37
|
4 |
|
public function toNative(): ?string |
38
|
|
|
{ |
39
|
4 |
|
return $this->isEmpty() ? null : $this->localPart.'@'.$this->domain; |
40
|
|
|
} |
41
|
|
|
|
42
|
4 |
|
public function isEmpty(): bool |
43
|
|
|
{ |
44
|
4 |
|
return $this->localPart->isEmpty() || $this->domain->isEmpty(); |
45
|
|
|
} |
46
|
|
|
|
47
|
|
|
/** @param self $comparator */ |
48
|
1 |
|
public function equals($comparator): bool |
49
|
|
|
{ |
50
|
1 |
|
Assertion::isInstanceOf($comparator, self::class); |
51
|
1 |
|
return $this->toNative() === $comparator->toNative(); |
52
|
|
|
} |
53
|
|
|
|
54
|
2 |
|
public function __toString(): string |
55
|
|
|
{ |
56
|
2 |
|
return (string)$this->toNative(); |
57
|
|
|
} |
58
|
|
|
|
59
|
1 |
|
public function getLocalPart(): Text |
60
|
|
|
{ |
61
|
1 |
|
return $this->localPart; |
62
|
|
|
} |
63
|
|
|
|
64
|
1 |
|
public function getDomain(): Text |
65
|
|
|
{ |
66
|
1 |
|
return $this->domain; |
67
|
|
|
} |
68
|
|
|
|
69
|
6 |
|
private function __construct(Text $localPart, Text $domain) |
70
|
|
|
{ |
71
|
6 |
|
$this->localPart = $localPart; |
72
|
6 |
|
$this->domain = $domain; |
73
|
6 |
|
} |
74
|
|
|
} |
75
|
|
|
|