|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace Jasny\Tests; |
|
4
|
|
|
|
|
5
|
|
|
use PHPUnit\Framework\TestCase; |
|
6
|
|
|
use function Jasny\iterable_cleanup; |
|
7
|
|
|
|
|
8
|
|
|
/** |
|
9
|
|
|
* @covers \Jasny\iterable_cleanup |
|
10
|
|
|
*/ |
|
11
|
|
|
class IterableCleanupTest extends TestCase |
|
12
|
|
|
{ |
|
13
|
|
|
use ProvideIterablesTrait; |
|
14
|
|
|
use LazyExecutionIteratorTrait; |
|
15
|
|
|
|
|
16
|
|
|
public function provider() |
|
17
|
|
|
{ |
|
18
|
|
|
return $this->provideIterables(['one', 'two', null, 'foo', 0, '', null, [], -100]); |
|
19
|
|
|
} |
|
20
|
|
|
|
|
21
|
|
|
/** |
|
22
|
|
|
* @dataProvider provider |
|
23
|
|
|
*/ |
|
24
|
|
|
public function test($values) |
|
25
|
|
|
{ |
|
26
|
|
|
$iterator = iterable_cleanup($values); |
|
27
|
|
|
$result = iterator_to_array($iterator); |
|
28
|
|
|
|
|
29
|
|
|
$expected = [0 => 'one', 1 => 'two', 3 => 'foo', 4 => 0, 5 => '', 7 => [], 8 => -100]; |
|
30
|
|
|
$this->assertEquals($expected, $result); |
|
31
|
|
|
} |
|
32
|
|
|
|
|
33
|
|
|
public function testIterateGenerator() |
|
34
|
|
|
{ |
|
35
|
|
|
$keys = [(object)['a' => 'a'], ['b' => 'b'], null, 'd', 'd']; |
|
36
|
|
|
$values = [1, 2, 3, 4, null]; |
|
37
|
|
|
|
|
38
|
|
|
$loop = function($keys, $values) { |
|
39
|
|
|
foreach ($keys as $i => $key) { |
|
40
|
|
|
yield $key => $values[$i]; |
|
41
|
|
|
} |
|
42
|
|
|
}; |
|
43
|
|
|
|
|
44
|
|
|
$generator = $loop($keys, $values); |
|
45
|
|
|
$iterator = iterable_cleanup($generator); |
|
46
|
|
|
|
|
47
|
|
|
$resultKeys = []; |
|
48
|
|
|
$resultValues = []; |
|
49
|
|
|
|
|
50
|
|
|
foreach ($iterator as $key => $value) { |
|
51
|
|
|
$resultKeys[] = $key; |
|
52
|
|
|
$resultValues[] = $value; |
|
53
|
|
|
} |
|
54
|
|
|
|
|
55
|
|
|
$this->assertSame([1, 2, 3, 4], $resultValues); |
|
56
|
|
|
$this->assertSame(array_slice($keys, 0, 4), $resultKeys); |
|
57
|
|
|
} |
|
58
|
|
|
|
|
59
|
|
|
public function testIterateEmpty() |
|
60
|
|
|
{ |
|
61
|
|
|
$iterator = iterable_cleanup(new \EmptyIterator()); |
|
62
|
|
|
$result = iterator_to_array($iterator); |
|
63
|
|
|
|
|
64
|
|
|
$this->assertSame([], $result); |
|
65
|
|
|
} |
|
66
|
|
|
|
|
67
|
|
|
/** |
|
68
|
|
|
* Test that nothing happens when not iterating |
|
69
|
|
|
*/ |
|
70
|
|
|
public function testLazyExecution() |
|
71
|
|
|
{ |
|
72
|
|
|
$iterator = $this->createLazyExecutionIterator(); |
|
73
|
|
|
|
|
74
|
|
|
iterable_cleanup($iterator); |
|
75
|
|
|
|
|
76
|
|
|
$this->assertTrue(true, "No warning"); |
|
77
|
|
|
} |
|
78
|
|
|
} |
|
79
|
|
|
|