-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathOptional.php
More file actions
326 lines (297 loc) · 9.32 KB
/
Copy pathOptional.php
File metadata and controls
326 lines (297 loc) · 9.32 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
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
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
<?php
declare(strict_types=1);
namespace PetrKnap\Optional;
use InvalidArgumentException;
use Throwable;
/**
* @template-covariant T of mixed type of non-null value
*
* @implements JavaSe8\Optional<T>
*/
abstract class Optional implements JavaSe8\Optional
{
private bool|null $wasPresent = null;
/**
* @param T|null $value
*/
final protected function __construct(
protected readonly mixed $value,
) {
if ($this->value !== null && !@static::isSupported($this->value)) {
throw new InvalidArgumentException('Value is not supported.');
}
}
/**
* @return self<T>
*/
public static function empty(): self
{
/** @var T|null $typedNull */
$typedNull = null;
return static::ofNullable($typedNull);
}
/**
* @template U of T
*
* @param U $value
*
* @return (U is null ? never : self<U>)
*
* @throws InvalidArgumentException
*/
public static function of(mixed $value): self
{
if ($value === null) {
throw new InvalidArgumentException('Value must not be null.');
}
return static::ofNullable($value);
}
/**
* In many cases a failure returns `false`, this method serves as a factory for them.
*
* @template U of T
*
* @param U|false $value
*
* @return (U is null ? never : self<U>)
*
* @throws InvalidArgumentException
*/
public static function ofFalsable(mixed $value): self
{
if ($value === false) {
/** @var self<U> */
return static::empty();
}
return static::of($value);
}
/**
* @template U of T
*
* @param U|null $value
*
* @return self<U>
*/
public static function ofNullable(mixed $value): self
{
if (static::class === Optional::class) {
if ($value !== null) {
try {
/** @var self<U> */
return TypedOptional::of($value, Optional::class);
} catch (Exception\CouldNotFindTypedOptionalForValue) {
}
}
/** @var self<U> */
return new class ($value) extends Optional {
protected static function isInstanceOfStatic(object $obj): bool
{
return $obj instanceof Optional;
}
protected static function isSupported(mixed $value): bool
{
return true;
}
};
}
return new static($value);
}
/**
* In many cases you will receive an `iterable` of single value, this method serves as a factory for them.
*
* @template U of T
*
* @param iterable<U> $value
*
* @return (U is null ? ($value is empty ? self<U> : never) : self<U>)
*
* @throws InvalidArgumentException
*/
public static function ofSingle(iterable $value): self
{
$option = null;
foreach ($value as $v) {
if ($option !== null) {
throw new InvalidArgumentException('Value is not single.');
}
$option = static::of($v);
}
/** @var self<U> */
return $option ?? static::empty();
}
/**
* @param bool $strict if `true` then the value, if the value is an object, will be compared as a reference
*/
public function equals(mixed $obj, bool $strict = false): bool
{
if (!($obj instanceof JavaSe8\Optional)) {
/** @var T|null $obj */
try {
$obj = static::ofNullable($obj);
} catch (InvalidArgumentException) {
return false;
}
}
if (static::isInstanceOfStatic($obj)) {
$equals = null;
$obj->ifPresent(function (mixed $objValue) use (&$equals, $strict): void {
$equals = match (!is_object($this->value) || $strict) {
true => $this->value === $objValue,
false => $this->value == $objValue,
};
});
return $equals ?? $this->value === null;
}
return false;
}
/**
* @return self<T>
*/
public function filter(callable $predicate): self
{
if ($this->value !== null) {
$matches = $predicate($this->value);
if (!is_bool($matches)) {
throw new InvalidArgumentException('Predicate must return boolean.');
}
if (!$matches) {
return static::empty();
}
}
return $this;
}
/**
* @template U of mixed type of non-null value
* @template V of Optional<U>
*
* @param ($empty is null ? callable(T): JavaSe8\Optional<U> : callable(T): V) $mapper
* @param V|null $empty
*
* @return ($empty is null ? Optional<U> : V)
*
* @note do not use {@see self}/{@see static}, it maps itself to another {@see Optional}
*/
public function flatMap(callable $mapper, Optional|null $empty = null): Optional
{
if ($this->value === null) {
/** @var V */
return $empty ?? Optional::empty();
}
/** @var JavaSe8\Optional<T>|"" $mapped */
$mapped = $mapper($this->value);
return match (true) {
$mapped instanceof Optional => $mapped,
$mapped instanceof JavaSe8\Optional => $mapped->isPresent() ? Optional::of($mapped->get()) : Optional::empty(),
default => throw new InvalidArgumentException('Mapper must return instance of ' . JavaSe8\Optional::class . '.'),
};
}
public function get(): mixed
{
if ($this->wasPresent === null) {
self::triggerNotice('Call `isPresent()` before accessing the value.');
}
return $this->orElseThrow();
}
public function ifPresent(callable $consumer, callable|null $else = null): void
{
if ($this->value !== null) {
$consumer($this->value);
} elseif ($else !== null) {
$else();
}
}
public function isPresent(): bool
{
return $this->wasPresent = $this->value !== null;
}
/**
* @template U of mixed type of non-null value
*
* @param callable(T): U $mapper
*
* @return Optional<U>
*
* @note do not use {@see self}/{@see static}, it maps itself to another {@see Optional}
*/
public function map(callable $mapper): Optional
{
/** @var callable(T): Optional<U> $flatMapper */
$flatMapper = static function (mixed $value) use ($mapper): Optional {
/** @var T $mapped */
$mapped = $mapper($value);
return Optional::ofNullable($mapped);
};
return $this->flatMap($flatMapper);
}
public function orElse(mixed $other): mixed
{
return $this->orElseGet(static fn (): mixed => $other);
}
public function orElseGet(callable $otherSupplier): mixed
{
if ($this->value !== null) {
return $this->value;
}
/** @var T|null $other */
$other = $otherSupplier();
return $other === null || static::isSupported($other)
? $other
: throw new InvalidArgumentException('Other supplier must return supported other.');
}
/**
* @template E of Throwable
*
* @param null|class-string<E>|callable(string|null $message): E $exceptionSupplier
*
* @return T
*
* @throws E
*/
public function orElseThrow(
null|string|callable $exceptionSupplier = null,
string|null $message = null,
): mixed {
if ($exceptionSupplier === null) {
return $this->orElseThrow(static fn () => match ($message) {
null => new Exception\CouldNotGetValueOfEmptyOptional(),
default => new Exception\CouldNotGetValueOfEmptyOptional($message),
});
}
if (is_string($exceptionSupplier)) {
/** @var class-string<E> $exceptionSupplier */
if (!class_exists($exceptionSupplier, autoload: true)) {
throw new InvalidArgumentException('Exception supplier must be existing class name.');
}
return $this->orElseThrow(static fn () => match ($message) {
null => new $exceptionSupplier(),
default => new $exceptionSupplier($message),
});
}
return $this->orElseGet(static function () use ($exceptionSupplier, $message): never {
/** @var Throwable|mixed $exception */
$exception = $exceptionSupplier($message);
if ($exception instanceof Throwable) {
throw $exception;
}
throw new InvalidArgumentException('Exception supplier must return ' . Throwable::class . '.');
});
}
/**
* @internal overridden by {@see AbstractOptional}
*/
protected static function isInstanceOfStatic(object $obj): bool
{
return $obj instanceof static;
}
/**
* @param mixed $value not null
*/
abstract protected static function isSupported(mixed $value): bool;
private static function triggerNotice(string $message): void
{
trigger_error(
$message,
error_level: E_USER_NOTICE,
);
}
}