|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace MongoDB\Tests\Model; |
| 4 | + |
| 5 | +use ArrayIterator; |
| 6 | +use MongoDB\Model\CallbackIterator; |
| 7 | +use MongoDB\Tests\TestCase; |
| 8 | + |
| 9 | +use function array_keys; |
| 10 | +use function iterator_to_array; |
| 11 | + |
| 12 | +class CallbackIteratorTest extends TestCase |
| 13 | +{ |
| 14 | + public function testArrayIteration(): void |
| 15 | + { |
| 16 | + $expectedKey = 0; |
| 17 | + |
| 18 | + $original = [1, 2, 3]; |
| 19 | + |
| 20 | + $callbackIterator = new CallbackIterator( |
| 21 | + new ArrayIterator($original), |
| 22 | + function ($value, $key) use (&$expectedKey) { |
| 23 | + $this->assertSame($expectedKey, $key); |
| 24 | + $expectedKey++; |
| 25 | + |
| 26 | + return $value * 2; |
| 27 | + } |
| 28 | + ); |
| 29 | + |
| 30 | + $this->assertSame([2, 4, 6], iterator_to_array($callbackIterator)); |
| 31 | + } |
| 32 | + |
| 33 | + public function testHashIteration(): void |
| 34 | + { |
| 35 | + $expectedKey = 0; |
| 36 | + |
| 37 | + $original = ['a' => 1, 'b' => 2, 'c' => 3]; |
| 38 | + $expectedKeys = array_keys($original); |
| 39 | + |
| 40 | + $callbackIterator = new CallbackIterator( |
| 41 | + new ArrayIterator($original), |
| 42 | + function ($value, $key) use (&$expectedKey, $expectedKeys) { |
| 43 | + $this->assertSame($expectedKeys[$expectedKey], $key); |
| 44 | + $expectedKey++; |
| 45 | + |
| 46 | + return $value * 2; |
| 47 | + } |
| 48 | + ); |
| 49 | + |
| 50 | + $this->assertSame(['a' => 2, 'b' => 4, 'c' => 6], iterator_to_array($callbackIterator)); |
| 51 | + } |
| 52 | +} |
0 commit comments