Navigation Menu

Skip to content

Commit

Permalink
Adding the ability of using a callable for Collection::extract()
Browse files Browse the repository at this point in the history
  • Loading branch information
lorenzo committed Jan 19, 2015
1 parent 08a1c83 commit 17dd323
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 7 deletions.
14 changes: 7 additions & 7 deletions src/Collection/Iterator/ExtractIterator.php
Expand Up @@ -24,12 +24,12 @@ class ExtractIterator extends Collection
{

/**
* A path to follow inside a hierarchy in order to get a particular property,
* which name is the last in this array
* A callable responsible for extracting a single value for each
* item in the collection.
*
* @var array
* @var callable
*/
protected $_path;
protected $_extractor;

/**
* Creates the iterator that will return the requested property for each value
Expand All @@ -53,7 +53,7 @@ class ExtractIterator extends Collection
*/
public function __construct($items, $path)
{
$this->_path = explode('.', $path);
$this->_extractor = $this->_propertyExtractor($path);
parent::__construct($items);
}

Expand All @@ -65,7 +65,7 @@ public function __construct($items, $path)
*/
public function current()
{
$current = parent::current();
return $this->_extract($current, $this->_path);
$extractor = $this->_extractor;
return $extractor(parent::current());
}
}
16 changes: 16 additions & 0 deletions tests/TestCase/Collection/Iterator/ExtractIteratorTest.php
Expand Up @@ -83,4 +83,20 @@ public function testExtractFromArrayDeep()
$extractor = new ExtractIterator($items, 'a.b.c');
$this->assertEquals([10, null, null, 25], iterator_to_array($extractor));
}

/**
* Tests that it is possible to pass a callable as the extractor.
*
* @return void
*/
public function testExtractWithCallable() {
$items = [
['a' => 1, 'b' => 2],
['a' => 3, 'b' => 4]
];
$extractor = new ExtractIterator($items, function ($item) {
return $item['b'];
});
$this->assertEquals([2, 4], iterator_to_array($extractor));
}
}

0 comments on commit 17dd323

Please sign in to comment.