From 17dd323f0c892619287269d7dce93a2305845122 Mon Sep 17 00:00:00 2001 From: Jose Lorenzo Rodriguez Date: Mon, 19 Jan 2015 21:49:34 +0100 Subject: [PATCH] Adding the ability of using a callable for Collection::extract() --- src/Collection/Iterator/ExtractIterator.php | 14 +++++++------- .../Collection/Iterator/ExtractIteratorTest.php | 16 ++++++++++++++++ 2 files changed, 23 insertions(+), 7 deletions(-) diff --git a/src/Collection/Iterator/ExtractIterator.php b/src/Collection/Iterator/ExtractIterator.php index 7067b285d51..5a539c58ff0 100644 --- a/src/Collection/Iterator/ExtractIterator.php +++ b/src/Collection/Iterator/ExtractIterator.php @@ -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 @@ -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); } @@ -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()); } } diff --git a/tests/TestCase/Collection/Iterator/ExtractIteratorTest.php b/tests/TestCase/Collection/Iterator/ExtractIteratorTest.php index b6f8f9636a4..ea22c31225b 100644 --- a/tests/TestCase/Collection/Iterator/ExtractIteratorTest.php +++ b/tests/TestCase/Collection/Iterator/ExtractIteratorTest.php @@ -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)); + } }