1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace MichaelRubel\ValueObjects\Collection\Complex; |
6
|
|
|
|
7
|
|
|
use Illuminate\Support\Collection; |
8
|
|
|
use MichaelRubel\Formatters\Collection\FullNameFormatter; |
9
|
|
|
use MichaelRubel\ValueObjects\ValueObject; |
10
|
|
|
|
11
|
|
|
/** |
12
|
|
|
* @method static static make(string $name) |
13
|
|
|
*/ |
14
|
|
|
class FullName extends ValueObject |
15
|
|
|
{ |
16
|
|
|
/** |
17
|
|
|
* @var Collection |
18
|
|
|
*/ |
19
|
|
|
protected Collection $split; |
20
|
|
|
|
21
|
|
|
/** |
22
|
|
|
* Create a new instance of the value object. |
23
|
|
|
* |
24
|
|
|
* @param string|null $name |
25
|
|
|
*/ |
26
|
13 |
|
public function __construct(protected ?string $name) |
27
|
|
|
{ |
28
|
13 |
|
$this->name = $this->format(); |
29
|
13 |
|
$this->split = $this->split(); |
30
|
|
|
} |
31
|
|
|
|
32
|
|
|
/** |
33
|
|
|
* Get the full name. |
34
|
|
|
* |
35
|
|
|
* @return string |
36
|
|
|
*/ |
37
|
13 |
|
public function fullName(): string |
38
|
|
|
{ |
39
|
13 |
|
return (string) $this->name; |
40
|
|
|
} |
41
|
|
|
|
42
|
|
|
/** |
43
|
|
|
* Get the first name. |
44
|
|
|
* |
45
|
|
|
* @return string |
46
|
|
|
*/ |
47
|
6 |
|
public function firstName(): string |
48
|
|
|
{ |
49
|
6 |
|
return $this->split->first(); |
50
|
|
|
} |
51
|
|
|
|
52
|
|
|
/** |
53
|
|
|
* Get the last name. |
54
|
|
|
* |
55
|
|
|
* @return string |
56
|
|
|
*/ |
57
|
5 |
|
public function lastName(): string |
58
|
|
|
{ |
59
|
5 |
|
return $this->split->last(); |
60
|
|
|
} |
61
|
|
|
|
62
|
|
|
/** |
63
|
|
|
* Get the object value. |
64
|
|
|
* |
65
|
|
|
* @return string |
66
|
|
|
*/ |
67
|
13 |
|
public function value(): string |
68
|
|
|
{ |
69
|
13 |
|
return $this->fullName(); |
70
|
|
|
} |
71
|
|
|
|
72
|
|
|
/** |
73
|
|
|
* Format the value. |
74
|
|
|
* |
75
|
|
|
* @return string |
76
|
|
|
*/ |
77
|
13 |
|
protected function format(): string |
78
|
|
|
{ |
79
|
13 |
|
return format(FullNameFormatter::class, $this->value()); |
80
|
|
|
} |
81
|
|
|
|
82
|
|
|
/** |
83
|
|
|
* Split the value. |
84
|
|
|
* |
85
|
|
|
* @return Collection |
86
|
|
|
*/ |
87
|
13 |
|
protected function split(): Collection |
88
|
|
|
{ |
89
|
13 |
|
return str($this->value())->split('/\s/'); |
90
|
|
|
} |
91
|
|
|
|
92
|
|
|
/** |
93
|
|
|
* Get an array representation of the value object. |
94
|
|
|
* |
95
|
|
|
* @return array |
96
|
|
|
*/ |
97
|
1 |
|
public function toArray(): array |
98
|
|
|
{ |
99
|
|
|
return [ |
|
|
|
|
100
|
1 |
|
'fullName' => $this->fullName(), |
101
|
1 |
|
'firstName' => $this->firstName(), |
102
|
1 |
|
'lastName' => $this->lastName(), |
103
|
|
|
]; |
104
|
|
|
} |
105
|
|
|
} |
106
|
|
|
|
In the issue above, the returned value is violating the contract defined by the mentioned interface.
Let's take a look at an example: