Skip to content

Commit

Permalink
Merge pull request #167 from 0x13a/master
Browse files Browse the repository at this point in the history
Allow `ArrayCollection#filter()` to filter by key and also value
  • Loading branch information
Ocramius authored Oct 15, 2018
2 parents 003f662 + f2cd5dd commit 92ab93e
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 1 deletion.
3 changes: 2 additions & 1 deletion lib/Doctrine/Common/Collections/ArrayCollection.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
use ArrayIterator;
use Closure;
use Doctrine\Common\Collections\Expr\ClosureExpressionVisitor;
use const ARRAY_FILTER_USE_BOTH;
use function array_filter;
use function array_key_exists;
use function array_keys;
Expand Down Expand Up @@ -312,7 +313,7 @@ public function map(Closure $func)
*/
public function filter(Closure $p)
{
return $this->createFrom(array_filter($this->elements, $p));
return $this->createFrom(array_filter($this->elements, $p, ARRAY_FILTER_USE_BOTH));
}

/**
Expand Down
13 changes: 13 additions & 0 deletions tests/Doctrine/Tests/Common/Collections/BaseCollectionTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,19 @@ public function testFilter() : void
self::assertEquals([0 => 1, 2 => 3], $res->toArray());
}

public function testFilterByValueAndKey() : void
{
$this->collection->add(1);
$this->collection->add('foo');
$this->collection->add(3);
$this->collection->add(4);
$this->collection->add(5);
$res = $this->collection->filter(static function ($v, $k) {
return is_numeric($v) && $k % 2 === 0;
});
self::assertSame([0 => 1, 2 => 3, 4 => 5], $res->toArray());
}

public function testFirstAndLast() : void
{
$this->collection->add('one');
Expand Down

0 comments on commit 92ab93e

Please sign in to comment.