-
-
Notifications
You must be signed in to change notification settings - Fork 17
/
Option.php
112 lines (92 loc) · 1.82 KB
/
Option.php
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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
<?php
declare(strict_types = 1);
namespace PhpOption;
use ArrayAccess;
use EmptyIterator;
use IteratorAggregate;
use ArrayIterator;
use Traversable;
/**
* @template T
*
* @implements IteratorAggregate<T>
*/
abstract class Option implements IteratorAggregate
{
public const NAME = 'Option';
/**
* Creates an option from an array's value.
*
* If the key does not exist in the array, the array is not actually an
* array, or the array's value at the given key is null, None is returned.
* Otherwise, Some is returned wrapping the value at the given key.
*
* @template S
*
* @param array<string|int,S>|ArrayAccess<string|int,S>|null $array A potential array or \ArrayAccess value.
* @param string $key The key to check.
*
* @return Option<S>
*/
public static function fromArraysValue($array, $key)
{
if (!(is_array($array) || $array instanceof ArrayAccess) || !isset($array[$key])) {
return None::create();
}
return new Some($array[$key]);
}
}
/**
* @extends Option<mixed>
*/
final class None extends Option
{
/** @var None|null */
private static $instance;
/**
* @return None
*/
public static function create()
{
if (null === self::$instance) {
self::$instance = new self();
}
return self::$instance;
}
public function getIterator(): Traversable
{
return new EmptyIterator();
}
}
/**
* @template T
*
* @extends Option<T>
*/
final class Some extends Option
{
/** @var T */
private $value;
/**
* @param T $value
*/
public function __construct($value)
{
$this->value = $value;
}
/**
* @template U
*
* @param U $value
*
* @return Some<U>
*/
public static function create($value)
{
return new self($value);
}
public function getIterator(): Traversable
{
return new ArrayIterator([$this->value]);
}
}