forked from widmogrod/php-functional
-
Notifications
You must be signed in to change notification settings - Fork 0
/
MaybeMonadAndCollectionTest.php
79 lines (69 loc) · 2.09 KB
/
MaybeMonadAndCollectionTest.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
<?php
namespace example;
use Widmogrod\Monad\Maybe;
use Widmogrod\Monad\Maybe as m;
use Widmogrod\Primitive\Listt;
use Widmogrod\Functional as f;
class MaybeMonadAndCollectionTest extends \PHPUnit_Framework_TestCase
{
/**
* @dataProvider provideData
*/
public function test_it_should_extract_elements_which_exists($data)
{
// $get :: String a -> [b] -> Maybe b
$get = f\curryN(2, function ($key, $array) {
return isset($array[$key])
? m\just($array[$key])
: m\nothing();
});
$listOfFirstImages = f\pipeline(
Listt::of
, f\map(m\maybeNull)
, f\bind(f\bind($get('meta')))
, f\bind(f\bind($get('images')))
, f\bind(f\bind($get(0)))
, f\join
);
$result = $listOfFirstImages($data);
$this->assertEquals(
Listt::of([m\just('//first.jpg'), m\just('//third.jpg'), m\nothing()]),
$result
);
}
/**
* @dataProvider provideData
*/
public function test_it_should_extract_elements_which_exists_alternative_solution($data)
{
// $get :: String a -> Maybe [b] -> Maybe b
$get = function ($key) {
return f\bind(function ($array) use ($key) {
return isset($array[$key])
? m\just($array[$key])
: m\nothing();
});
};
$result = Listt::of($data)
->map(Maybe\maybeNull)
->bind($get('meta'))
->bind($get('images'))
->bind($get(0));
$this->assertEquals(
Listt::of([m\just('//first.jpg'), m\just('//third.jpg'), m\nothing()]),
$result
);
}
public function provideData()
{
return [
'default' => [
'$data' => [
['id' => 1, 'meta' => ['images' => ['//first.jpg', '//second.jpg']]],
['id' => 2, 'meta' => ['images' => ['//third.jpg']]],
['id' => 3],
]
],
];
}
}