Skip to content

Commit 4d9a002

Browse files
committed
Accept any callable as callback in CallbackIterator
1 parent 3bac402 commit 4d9a002

File tree

2 files changed

+27
-8
lines changed

2 files changed

+27
-8
lines changed

src/Model/CallbackIterator.php

Lines changed: 9 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -17,12 +17,13 @@
1717

1818
namespace MongoDB\Model;
1919

20-
use Closure;
2120
use Iterator;
2221
use IteratorIterator;
2322
use ReturnTypeWillChange;
2423
use Traversable;
2524

25+
use function call_user_func;
26+
2627
/**
2728
* Iterator to apply a callback before returning an element
2829
*
@@ -35,20 +36,20 @@
3536
*/
3637
class CallbackIterator implements Iterator
3738
{
38-
/** @var Closure(TValue, TKey): TCallbackValue */
39-
private $callback;
39+
/** @var callable(TValue, TKey): TCallbackValue */
40+
private $callable;
4041

4142
/** @var Iterator<TKey, TValue> */
4243
private $iterator;
4344

4445
/**
45-
* @param Traversable<TKey, TValue> $traversable
46-
* @param Closure(TValue, TKey): TCallbackValue $callback
46+
* @param Traversable<TKey, TValue> $traversable
47+
* @param callable(TValue, TKey): TCallbackValue $callable
4748
*/
48-
public function __construct(Traversable $traversable, Closure $callback)
49+
public function __construct(Traversable $traversable, callable $callable)
4950
{
5051
$this->iterator = $traversable instanceof Iterator ? $traversable : new IteratorIterator($traversable);
51-
$this->callback = $callback;
52+
$this->callable = $callable;
5253
}
5354

5455
/**
@@ -58,7 +59,7 @@ public function __construct(Traversable $traversable, Closure $callback)
5859
#[ReturnTypeWillChange]
5960
public function current()
6061
{
61-
return ($this->callback)($this->iterator->current(), $this->iterator->key());
62+
return call_user_func($this->callable, $this->iterator->current(), $this->iterator->key());
6263
}
6364

6465
/**

tests/Model/CallbackIteratorTest.php

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88

99
use function array_keys;
1010
use function iterator_to_array;
11+
use function strrev;
1112

1213
class CallbackIteratorTest extends TestCase
1314
{
@@ -49,4 +50,21 @@ function ($value, $key) use (&$expectedKey, $expectedKeys) {
4950

5051
$this->assertSame(['a' => 2, 'b' => 4, 'c' => 6], iterator_to_array($callbackIterator));
5152
}
53+
54+
public function testWithCallable(): void
55+
{
56+
$original = ['foo', 'bar', 'baz'];
57+
58+
$callbackIterator = new CallbackIterator(
59+
new ArrayIterator($original),
60+
[self::class, 'testCallable']
61+
);
62+
63+
$this->assertSame(['oof', 'rab', 'zab'], iterator_to_array($callbackIterator));
64+
}
65+
66+
public static function testCallable($value, $key)
67+
{
68+
return strrev($value);
69+
}
5270
}

0 commit comments

Comments
 (0)