Skip to content

Commit

Permalink
Accept any callable as callback in CallbackIterator
Browse files Browse the repository at this point in the history
  • Loading branch information
alcaeus committed Jul 7, 2023
1 parent 3bac402 commit 56a33c1
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 8 deletions.
17 changes: 9 additions & 8 deletions src/Model/CallbackIterator.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,12 +17,13 @@

namespace MongoDB\Model;

use Closure;
use Iterator;
use IteratorIterator;
use ReturnTypeWillChange;
use Traversable;

use function call_user_func;

/**
* Iterator to apply a callback before returning an element
*
Expand All @@ -35,20 +36,20 @@
*/
class CallbackIterator implements Iterator
{
/** @var Closure(TValue, TKey): TCallbackValue */
private $callback;
/** @var callable(TValue, TKey): TCallbackValue */
private $callable;

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

/**
* @param Traversable<TKey, TValue> $traversable
* @param Closure(TValue, TKey): TCallbackValue $callback
* @param Traversable<TKey, TValue> $traversable
* @param callable(TValue, TKey): TCallbackValue $callable
*/
public function __construct(Traversable $traversable, Closure $callback)
public function __construct(Traversable $traversable, callable $callable)
{
$this->iterator = $traversable instanceof Iterator ? $traversable : new IteratorIterator($traversable);
$this->callback = $callback;
$this->callable = $callable;
}

/**
Expand All @@ -58,7 +59,7 @@ public function __construct(Traversable $traversable, Closure $callback)
#[ReturnTypeWillChange]
public function current()
{
return ($this->callback)($this->iterator->current(), $this->iterator->key());
return call_user_func($this->callable, $this->iterator->current(), $this->iterator->key());
}

/**
Expand Down
18 changes: 18 additions & 0 deletions tests/Model/CallbackIteratorTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@

use function array_keys;
use function iterator_to_array;
use function strrev;

class CallbackIteratorTest extends TestCase
{
Expand Down Expand Up @@ -49,4 +50,21 @@ function ($value, $key) use (&$expectedKey, $expectedKeys) {

$this->assertSame(['a' => 2, 'b' => 4, 'c' => 6], iterator_to_array($callbackIterator));
}

public function testWithCallable(): void
{
$original = ['foo', 'bar', 'baz'];

$callbackIterator = new CallbackIterator(
new ArrayIterator($original),
[self::class, 'reverseValue']
);

$this->assertSame(['oof', 'rab', 'zab'], iterator_to_array($callbackIterator));
}

public static function reverseValue($value, $key)
{
return strrev($value);
}
}

0 comments on commit 56a33c1

Please sign in to comment.