File tree 2 files changed +51
-1
lines changed
2 files changed +51
-1
lines changed Original file line number Diff line number Diff line change @@ -23,14 +23,26 @@ public static function some($value): Some
23
23
return new Some ($ value );
24
24
}
25
25
26
- /**y
26
+ /**
27
27
* @return None
28
28
*/
29
29
public static function none (): None
30
30
{
31
31
return self ::$ none ??= new None ();
32
32
}
33
33
34
+ /**
35
+ * @template TNew
36
+ * @param TNew|null $value
37
+ * @return Option<TNew>
38
+ */
39
+ public static function fromNullable ($ value ): Option
40
+ {
41
+ return $ value === null
42
+ ? self ::none ()
43
+ : self ::some ($ value );
44
+ }
45
+
34
46
/**
35
47
* @template T
36
48
* @param list<Option<T>> $options
@@ -124,4 +136,12 @@ public function toResultLazy(callable $else): ResultInterface
124
136
->map (fn ($ t ) => new Success ($ t ))
125
137
->getOr (fn () => new Error ($ else ()));
126
138
}
139
+
140
+ /**
141
+ * @return TValue|null
142
+ */
143
+ public function toNullable ()
144
+ {
145
+ return $ this ->getOrElse (null );
146
+ }
127
147
}
Original file line number Diff line number Diff line change @@ -94,4 +94,34 @@ public function testGetOrThrowNone(): void
94
94
/** @psalm-suppress UnusedMethodCall */
95
95
$ option ->getOrThrow (new \RuntimeException ('expected ' ));
96
96
}
97
+
98
+ public function testFromNullableGivenValue (): void
99
+ {
100
+ $ option = Option::fromNullable (123 );
101
+ $ mapped = $ option ->map (fn (int $ val ) => $ val + 1 );
102
+ self ::assertEquals (124 , $ mapped ->getOrElse (-1 ));
103
+ }
104
+
105
+ public function testFromNullableGivenNull (): void
106
+ {
107
+ /** @var Option<int> $option */
108
+ $ option = Option::fromNullable (null );
109
+ $ mapped = $ option ->map (fn (int $ val ) => $ val + 1 );
110
+ self ::assertEquals (-1 , $ mapped ->getOrElse (-1 ));
111
+ }
112
+
113
+ public function testToNullableSome (): void
114
+ {
115
+ $ option = Option::some (123 );
116
+ $ nullable = $ option ->toNullable ();
117
+ self ::assertEquals (123 , $ nullable );
118
+ }
119
+
120
+ public function testToNullableNone (): void
121
+ {
122
+ /** @var Option<int> $option */
123
+ $ option = Option::none ();
124
+ $ nullable = $ option ->toNullable ();
125
+ self ::assertNull ($ nullable );
126
+ }
97
127
}
You can’t perform that action at this time.
0 commit comments