Skip to content

Commit

Permalink
Add filterKeys() method to KeyCollection
Browse files Browse the repository at this point in the history
  • Loading branch information
robgridley committed Aug 24, 2017
1 parent 35b7f7c commit 298b6a6
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 0 deletions.
11 changes: 11 additions & 0 deletions src/KeyCollection.php
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,17 @@ public function diff($keys)
return $this->fresh(array_diff($this->keys, ($keys instanceof self) ? $keys->keys() : (array)$keys));
}

/**
* Filter the keys in the collection using a callback.
*
* @param callable $callback
* @return KeyCollection
*/
public function filterKeys(callable $callback)
{
return $this->fresh(array_values(array_filter($this->keys, $callback)));
}

/**
* Read only the first key.
*
Expand Down
11 changes: 11 additions & 0 deletions tests/KeyCollectionTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -190,4 +190,15 @@ public function testPluckMethodWithKey()
$this->assertEquals('Test 1', $list[3]);
$this->assertEquals('Test 2', $list[4]);
}

public function testFilterKeys()
{
$model = Mockery::mock(Model::class);
$collection = new KeyCollection($model, [1, 2, 3, 4]);
$filtered = $collection->filterKeys(function ($key) {
return $key % 2 == 0;
});
$this->assertInstanceOf(KeyCollection::class, $filtered);
$this->assertEquals([2, 4], $filtered->keys());
}
}

0 comments on commit 298b6a6

Please sign in to comment.