-
Notifications
You must be signed in to change notification settings - Fork 8
/
From.php
73 lines (63 loc) · 1.63 KB
/
From.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
<?php
/**
* From
*
* Helper class for creating Options from things
* @author Oskar Thornblad
*/
declare(strict_types=1);
namespace Prewk\Option;
use Prewk\Option;
/**
* Helper class for creating Options from things
*/
class From
{
/**
* Create a Some<T> if T is something using isset(T), None otherwise
*
* @param $thing T|null
* @return Option Option<T>
*/
public static function nullable($thing): Option
{
return isset($thing) ? new Some($thing) : new None;
}
/**
* Create a Some<V> from C[K] if it exists using array_key_exists(C, K), None otherwise
*
* @param array $coll C
* @param $key K
* @return Option Option<V>
*/
public static function key(array $coll, $key): Option
{
return array_key_exists($key, $coll) ? new Some($coll[$key]) : new None;
}
/**
* Create a Some<T> if T is non-empty using empty(T), None otherwise
*
* @param $thing T|[]|null|0
* @return Option Option<T>
*/
public static function emptyable($thing): Option
{
return !empty($thing) ? new Some($thing) : new None;
}
/**
* Iterates over T and creates a Some<V> from the first item, returning None if T is empty
*
* @param $iterable Iterable T<V>
* @return Option Option<V>
*/
public static function first($iterable): Option
{
if (!is_iterable($iterable)) {
throw new OptionException("Couldn't create Option from first item in non-iterable");
}
foreach ($iterable as $item) {
return new Some($item);
}
return new None;
}
}