-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTypedOptional.php
More file actions
53 lines (47 loc) · 1.54 KB
/
Copy pathTypedOptional.php
File metadata and controls
53 lines (47 loc) · 1.54 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
<?php
declare(strict_types=1);
namespace PetrKnap\Optional;
use InvalidArgumentException;
final class TypedOptional
{
/** @var array<class-string> stored in reverse order, see {@see self::register()} */
private static array $typedOptionals = [];
/**
* @internal use {@see Optional::of()}
*
* @template T of mixed type of non-null value
*
* @param T $value
* @param class-string $subclassOf
*
* @return Optional<T>
*
* @throws Exception\CouldNotFindTypedOptionalForValue
*/
public static function of(mixed $value, string $subclassOf): Optional
{
/** @var class-string<Optional<T>> $typedOptional */
foreach (self::$typedOptionals as $typedOptional) {
if ($typedOptional === $subclassOf || !is_a($typedOptional, $subclassOf, allow_string: true)) {
continue;
}
try {
return $typedOptional::of($value);
} catch (InvalidArgumentException) {
}
}
throw new Exception\CouldNotFindTypedOptionalForValue($value);
}
/**
* @param class-string $typedOptionalClassName
*
* @throws Exception\CouldNotRegisterNonOptional
*/
public static function register(string $typedOptionalClassName): void
{
if (!is_a($typedOptionalClassName, Optional::class, allow_string: true)) {
throw new Exception\CouldNotRegisterNonOptional($typedOptionalClassName);
}
array_unshift(self::$typedOptionals, $typedOptionalClassName);
}
}