1: <?php declare(strict_types=1);
2:
3: namespace TH\Maybe\Option;
4:
5: use TH\DocTest\Attributes\ExamplesSetup;
6: use TH\Maybe\Option;
7: use TH\Maybe\Result;
8: use TH\Maybe\Tests\Helpers\IgnoreUnusedResults;
9: use function TH\Maybe\Internal\assertNoneValueOrIsSome;
10: use function TH\Maybe\Internal\isOfAnyClass;
11:
12: /**
13: * Return a `Option\Some` option containing `$value`.
14: *
15: * @template T
16: * @param T $value
17: * @return Option\Some<T>
18: */
19: function some(mixed $value): Option\Some
20: {
21: return new Option\Some($value);
22: }
23:
24: /**
25: * Return a `Option\None` option containing no values.
26: */
27: function none(): Option\None
28: {
29: return Option\None::instance;
30: }
31:
32: /**
33: * Transform a value into an `Option`.
34: * It will be a `Some` option containing `$value` if `$value` is different from `$noneValue` (default `null`),
35: * or, when `$isSome` is given, if `$isSome($value)` returns `true` (`$strict` is then ignored).
36: * `$noneValue` and `$isSome` cannot be used together: an `\InvalidArgumentException` is thrown if both are given.
37: *
38: * # Examples
39: *
40: * ```php
41: * self::assertEq(Option\fromValue("fruits"), Option\some("fruits"));
42: * self::assertEq(Option\fromValue(null), Option\none());
43: * ```
44: *
45: * Using a predicate:
46: *
47: * ```php
48: * self::assertEq(Option\fromValue(3, isSome: is_int(...)), Option\some(3));
49: * self::assertEq(Option\fromValue(false, isSome: is_int(...)), Option\none());
50: * ```
51: *
52: * `$noneValue` and `$isSome` are mutually exclusive:
53: *
54: * ```php
55: * Option\fromValue(3, noneValue: 0, isSome: is_int(...));
56: * // @throws InvalidArgumentException $noneValue and $isSome cannot be used together
57: * ```
58: *
59: * @template U
60: * @param U $value
61: * @param (callable(U):bool)|null $isSome
62: * @return ($isSome is null ? Option<U> : ($noneValue is null ? Option<U> : never))
63: * @throws \InvalidArgumentException if both `$noneValue` and `$isSome` are given
64: */
65: function fromValue(mixed $value, mixed $noneValue = null, bool $strict = true, ?callable $isSome = null): Option
66: {
67: assertNoneValueOrIsSome($noneValue, $isSome);
68:
69: if ($isSome !== null) {
70: return $isSome($value)
71: ? Option\some($value)
72: : Option\none();
73: }
74:
75: $same = $strict
76: ? $value === $noneValue
77: // @mago-expect analysis:possibly-null-operand -- left: `$value` may be null, comparing it to `$noneValue` is the point
78: // @mago-expect analysis:mixed-operand -- right: `$noneValue` can be anything, loose comparison is the point of `$strict = false`
79: // @mago-expect lint:identity-comparison
80: : $value == $noneValue;
81:
82: return $same
83: ? Option\none()
84: : Option\some($value);
85: }
86:
87: /**
88: * Execute a callable and transform the result into an `Option`.
89: * It will be a `Some` option containing the result if it is different from `$noneValue` (default `null`),
90: * or, when `$isSome` is given, if `$isSome($result)` returns `true` (`$noneValue` and `$isSome` cannot be used together).
91: *
92: * # Examples
93: *
94: * Successful execution:
95: *
96: * ```php
97: * self::assertEq(Option\of(fn() => "fruits"), Option\some("fruits"));
98: * ```
99: *
100: * Conversion of `null` to `Option\None`:
101: *
102: * ```php
103: * self::assertEq(Option\of(fn() => null), Option\none());
104: * ```
105: *
106: * Using a predicate:
107: *
108: * ```php
109: * self::assertEq(Option\of(fn() => strpos("fruits", "z"), isSome: is_int(...)), Option\none());
110: * ```
111: *
112: * @template U
113: * @param callable():U $callback
114: * @param (callable(U):bool)|null $isSome
115: * @return ($isSome is null ? Option<U> : ($noneValue is null ? Option<U> : never))
116: * @throws \InvalidArgumentException if both `$noneValue` and `$isSome` are given
117: */
118: function of(callable $callback, mixed $noneValue = null, bool $strict = true, ?callable $isSome = null): Option
119: {
120: assertNoneValueOrIsSome($noneValue, $isSome);
121:
122: return Option\fromValue($callback(), $noneValue, $strict, $isSome);
123: }
124:
125: /**
126: * Execute a callable and transform the result into an `Option` as `Option\of()` does
127: * but also return `Option\None` if an exception matching `$exceptionClass` was thrown.
128: *
129: * # Examples
130: *
131: * Successful execution:
132: *
133: * ```php
134: * self::assertEq(Option\tryOf(fn () => strtolower("FRUITS")), Option\some("fruits"));
135: * ```
136: *
137: * Conversion of `null` to `Option\None`:
138: *
139: * ```php
140: * self::assertEq(Option\tryOf(fn() => null), Option\none());
141: * ```
142: *
143: * Checked Exception:
144: *
145: * ```php
146: * self::assertEq(Option\tryOf(fn () => new \DateTimeImmutable("nope")), Option\none());
147: * ```
148: *
149: * Unchecked Exception:
150: *
151: * ```php
152: * self::assertEq(Option\tryOf(fn () => 1 / 0), Option\none());
153: * // @throws DivisionByZeroError Division by zero
154: * ```
155: *
156: * @template U
157: * @template E of \Throwable
158: * @param callable():U $callback
159: * @param list<class-string<E>>|class-string<E> $exceptionClass
160: * @param (callable(U):bool)|null $isSome
161: * @return ($isSome is null ? Option<U> : ($noneValue is null ? Option<U> : never))
162: * @throws \InvalidArgumentException if both `$noneValue` and `$isSome` are given
163: * @throws \Throwable
164: */
165: function tryOf(
166: callable $callback,
167: mixed $noneValue = null,
168: bool $strict = true,
169: array|string $exceptionClass = \Exception::class,
170: ?callable $isSome = null,
171: ): Option {
172: assertNoneValueOrIsSome($noneValue, $isSome);
173:
174: try {
175: return Option\of($callback, $noneValue, $strict, $isSome);
176: } catch (\Throwable $th) {
177: if (isOfAnyClass($th, (array) $exceptionClass)) {
178: return Option\none();
179: }
180:
181: throw $th;
182: }
183: }
184:
185: /**
186: * Wrap a callable into one that transforms its result into an `Option`.
187: * It will be a `Some` option containing the result if it is different from `$noneValue` (default `null`),
188: * or, when `$isSome` is given, if `$isSome($result)` returns `true` (`$noneValue` and `$isSome` cannot be used together).
189: *
190: * # Examples
191: *
192: * Successful execution:
193: *
194: * ```php
195: * self::assertEq(Option\ify(strtolower(...))("FRUITS"), Option\some("fruits"));
196: * ```
197: *
198: * Conversion of `null` to `Option\None`:
199: *
200: * ```php
201: * self::assertEq(Option\ify(fn() => null)(), Option\none());
202: * ```
203: *
204: * Option-ify `strpos()`:
205: *
206: * ```php
207: * $strpos = Option\ify(strpos(...), isSome: is_int(...));
208: *
209: * self::assertEq($strpos("fruits", "u"), Option\some(2));
210: * self::assertEq($strpos("fruits", "z"), Option\none());
211: * ```
212: *
213: * @template U
214: * @param callable(mixed...):U $callback
215: * @param (callable(U):bool)|null $isSome
216: * @return ($isSome is null ? \Closure(mixed...):Option<U> : ($noneValue is null ? \Closure(mixed...):Option<U> : never))
217: * @throws \InvalidArgumentException if both `$noneValue` and `$isSome` are given
218: */
219: function ify(callable $callback, mixed $noneValue = null, bool $strict = true, ?callable $isSome = null): \Closure
220: {
221: assertNoneValueOrIsSome($noneValue, $isSome);
222:
223: // Pick the conversion once here rather than on every call of the returned closure.
224: if ($isSome !== null) {
225: return static function (mixed ...$args) use ($callback, $isSome): Option {
226: $value = $callback(...$args);
227:
228: return $isSome($value)
229: ? Option\some($value)
230: : Option\none();
231: };
232: }
233:
234: if ($strict) {
235: return static function (mixed ...$args) use ($callback, $noneValue): Option {
236: $value = $callback(...$args);
237:
238: return $value === $noneValue
239: ? Option\none()
240: : Option\some($value);
241: };
242: }
243:
244: return static function (mixed ...$args) use ($callback, $noneValue): Option {
245: $value = $callback(...$args);
246:
247: // @mago-expect analysis:possibly-null-operand -- left: `$value` may be null, comparing it to `$noneValue` is the point
248: // @mago-expect analysis:mixed-operand -- loose comparison is the point of `$strict = false`
249: // @mago-expect lint:identity-comparison
250: return $value == $noneValue
251: ? Option\none()
252: : Option\some($value);
253: };
254: }
255:
256: /**
257: * Wrap a callable into one that transforms its result into an `Option` like `Option\ify()` does
258: * but also return `Option\None` if an exception matching `$exceptionClass` was thrown.
259: *
260: * # Examples
261: *
262: * Successful execution:
263: *
264: * ```php
265: * self::assertEq(Option\tryIfy(strtolower(...))("FRUITS"), Option\some("fruits"));
266: * ```
267: *
268: * Conversion of `null` to `Option\None`:
269: *
270: * ```php
271: * self::assertEq(Option\tryIfy(fn() => null)(), Option\none());
272: * ```
273: *
274: * Checked Exception:
275: *
276: * ```php
277: * self::assertEq(Option\tryIfy(fn () => new \DateTimeImmutable("nope"))(), Option\none());
278: * ```
279: *
280: * Unchecked Exception:
281: *
282: * ```php
283: * self::assertEq(Option\tryIfy(fn () => 1 / 0)(), Option\none());
284: * // @throws DivisionByZeroError Division by zero
285: * ```
286: *
287: * @template U
288: * @template E of \Throwable
289: * @param callable(mixed...):U $callback
290: * @param list<class-string<E>>|class-string<E> $exceptionClass
291: * @param (callable(U):bool)|null $isSome
292: * @return ($isSome is null ? \Closure(mixed...):Option<U> : ($noneValue is null ? \Closure(mixed...):Option<U> : never))
293: * @throws \InvalidArgumentException if both `$noneValue` and `$isSome` are given
294: */
295: function tryIfy(
296: callable $callback,
297: mixed $noneValue = null,
298: bool $strict = true,
299: array|string $exceptionClass = \Exception::class,
300: ?callable $isSome = null,
301: ): \Closure {
302: $ify = Option\ify($callback, $noneValue, $strict, $isSome);
303:
304: return static function (mixed ...$args) use ($ify, $exceptionClass): Option {
305: try {
306: return $ify(...$args);
307: } catch (\Throwable $th) {
308: if (isOfAnyClass($th, (array) $exceptionClass)) {
309: return Option\none();
310: }
311:
312: // @mago-ignore analysis:unhandled-thrown-type -- rethrowing exceptions not in $exceptionClass is the point
313: throw $th;
314: }
315: };
316: }
317:
318: /**
319: * Converts from `Option<Option<T>>` to `Option<T>`.
320: *
321: * # Examples
322: *
323: * ```php
324: * $x = Option\Some("vegetables");
325: * self::assertSame(Option\flatten(Option\some($x)), $x);
326: * self::assertSame(Option\flatten(Option\some(Option\none())), Option\none());
327: * self::assertSame(Option\flatten(Option\none()), Option\none());
328: * ```
329: *
330: * @template U
331: * @param Option<Option<U>> $option
332: * @return Option<U>
333: */
334: function flatten(Option $option): Option
335: {
336: return $option instanceof Option\None
337: ? $option
338: // @mago-ignore analysis:unhandled-thrown-type -- unwrap() cannot throw: $option is not None
339: : $option->unwrap();
340: }
341:
342: /**
343: * Unzips an option containing a tuple of two options.
344: *
345: * If `self` is `Some([a, b])` this method returns `[Some(a), Some(b)]`. Otherwise, `[None, None]` is returned.
346: *
347: * ```php
348: * $x = Option\Some("vegetables");
349: * self::assertEq(Option\unzip(Option\some(["a", 2])), [Option\some("a"), Option\some(2)]);
350: * self::assertSame(Option\unzip(Option\none()), [Option\none(), Option\none()]);
351: * ```
352: *
353: * @template U
354: * @template V
355: * @param Option<array{U, V}> $option
356: * @return array{Option<U>, Option<V>}
357: */
358: function unzip(Option $option): array
359: {
360: return $option->mapOrElse(static fn (array $a): array => [
361: Option\some($a[0]),
362: Option\some($a[1]),
363: ], static fn (): array => [Option\none(), Option\none()]);
364: }
365:
366: /**
367: * Transposes an `Option` of a `Result` into a `Result` of an `Option`.
368: *
369: * `None` will be mapped to `Ok(None)`.
370: * `Some(Ok(_))` and `Some(Err(_))` will be mapped to `Ok(Some(_))` and `Err(_)`.
371: *
372: * ```php
373: * use TH\Maybe\Result;
374: *
375: * self::assertEq(Result\ok(Option\some(4)), Option\transpose(Option\some(Result\ok(4))));
376: * self::assertEq(Result\err("meat"), Option\transpose(Option\some(Result\err("meat"))));
377: * self::assertEq(Option\transpose(Option\none()), Result\ok(Option\none()));
378: * ```
379: *
380: * @template U
381: * @template E
382: * @param Option<Result<U, E>> $option
383: * @return Result<Option<U>, E>
384: */
385: #[ExamplesSetup(new IgnoreUnusedResults())]
386: function transpose(Option $option): Result
387: {
388: return $option->mapOrElse(
389: static fn (Result $result) => $result->map(Option\some(...)),
390: static fn () => Result\ok(Option\none()),
391: );
392: }
393:
394: /**
395: * Takes each element in the iterable: if it is a `None`, no further elements are
396: * taken and `None` is returned. Should no `None` occur, a `Some` containing the
397: * list of all the values is returned.
398: *
399: * # Examples
400: *
401: * ```php
402: * self::assertEq(Option\collect([Option\some(1), Option\some(2)]), Option\some([1, 2]));
403: * self::assertEq(Option\collect([Option\some(1), Option\none()]), Option\none());
404: * self::assertEq(Option\collect([Option\none(), Option\some(2)]), Option\none());
405: * self::assertEq(Option\collect([]), Option\some([]));
406: * ```
407: *
408: * @template U
409: * @param iterable<Option<U>> $options
410: * @return Option<list<U>>
411: */
412: function collect(iterable $options): Option
413: {
414: $values = [];
415:
416: foreach ($options as $option) {
417: if ($option instanceof Option\None) {
418: return Option\none();
419: }
420:
421: // @mago-ignore analysis:unhandled-thrown-type -- unwrap() cannot throw: $option is not None
422: $values[] = $option->unwrap();
423: }
424:
425: return Option\some($values);
426: }
427: