2828 */
2929class Name implements Castable, Jsonable, JsonSerializable
3030{
31+ public function __construct (protected ?string $ firstName , protected ?string $ lastName = null )
32+ {
33+ }
34+
35+ public function __get (string $ key ): ?string
36+ {
37+ if ($ this ->wantsPossessive ($ key )) {
38+ $ key = Str::replaceLast ('possessive ' , '' , $ key );
39+
40+ return $ this ->possessive ($ this ->{$ key });
41+ }
42+
43+ if (method_exists ($ this , $ method = Str::studly ($ key ))) {
44+ return $ this ->{$ method }();
45+ }
46+
47+ return null ;
48+ }
49+
50+ public function __toString (): string
51+ {
52+ return (string ) $ this ->full ();
53+ }
54+
3155 public static function from (?string $ name ): self
3256 {
3357 $ parts = explode (' ' , trim ($ name ), 2 );
@@ -39,8 +63,9 @@ public static function from(?string $name): self
3963 return new static (Arr::get ($ parts , 0 ), $ lastName );
4064 }
4165
42- public function __construct ( protected ? string $ firstName , protected ? string $ lastName = null )
66+ public static function castUsing ( array $ arguments ): CastsAttributes
4367 {
68+ return new NameCast (...$ arguments );
4469 }
4570
4671 public function first (): ?string
@@ -95,48 +120,23 @@ public function initials(): ?string
95120 ->join ('' );
96121 }
97122
98- protected function possessive (string $ name ): string
99- {
100- return sprintf ("%s'%s " , $ name , (Str::endsWith ($ name , 's ' ) ? null : 's ' ));
101- }
102-
103- protected function wantsPossessive (string $ key ): bool
104- {
105- return Str::endsWith ($ key , 'possessive ' );
106- }
107-
108- public function __get (string $ key ): ?string
123+ public function toJson ($ options = 0 ): string
109124 {
110- if ($ this ->wantsPossessive ($ key )) {
111- $ key = Str::replaceLast ('possessive ' , '' , $ key );
112-
113- return $ this ->possessive ($ this ->{$ key });
114- }
115-
116- if (method_exists ($ this , $ method = Str::studly ($ key ))) {
117- return $ this ->{$ method }();
118- }
119-
120- return null ;
125+ return json_encode ($ this ->jsonSerialize (), $ options );
121126 }
122127
123- public function __toString (): string
128+ public function jsonSerialize (): string
124129 {
125130 return (string ) $ this ->full ();
126131 }
127132
128- public static function castUsing (array $ arguments ): CastsAttributes
129- {
130- return new NameCast (...$ arguments );
131- }
132-
133- public function toJson ($ options = 0 ): string
133+ protected function possessive (string $ name ): string
134134 {
135- return json_encode ( $ this -> jsonSerialize (), $ options );
135+ return sprintf ( " %s'%s " , $ name , (Str:: endsWith ( $ name , ' s ' ) ? null : ' s ' ) );
136136 }
137137
138- public function jsonSerialize ( ): string
138+ protected function wantsPossessive ( string $ key ): bool
139139 {
140- return ( string ) $ this -> full ( );
140+ return Str:: endsWith ( $ key , ' possessive ' );
141141 }
142142}
0 commit comments