From 74bf9f065620e727227f39f0baab6babbba24729 Mon Sep 17 00:00:00 2001 From: Jose Lorenzo Rodriguez Date: Sun, 31 May 2015 15:12:23 -0400 Subject: [PATCH] Cleaning code and adding another test case --- src/Collection/ExtractTrait.php | 37 +++++++++++++++++--- tests/TestCase/Collection/CollectionTest.php | 2 +- 2 files changed, 33 insertions(+), 6 deletions(-) diff --git a/src/Collection/ExtractTrait.php b/src/Collection/ExtractTrait.php index 1d2aab662e3..6da2fe3a08e 100644 --- a/src/Collection/ExtractTrait.php +++ b/src/Collection/ExtractTrait.php @@ -37,16 +37,22 @@ protected function _propertyExtractor($callback) } $path = explode('.', $callback); - $callback = function ($element) use ($path) { - return $this->_extract($element, $path); - }; - return $callback; + if (strpos($callback, '{n}') !== false) { + return function ($element) use ($path) { + return $this->_extract($element, $path); + }; + } + + return function ($element) use ($path) { + return $this->_simpleExtract($element, $path); + }; } /** * Returns a column from $data that can be extracted - * by iterating over the column names contained in $path + * by iterating over the column names contained in $path. + * It will return arrays for elements in represented with `{n}` * * @param array|\ArrayAccess $data Data. * @param array $path Path to extract from. @@ -83,6 +89,27 @@ protected function _extract($data, $path) return $value; } + /** + * Returns a column from $data that can be extracted + * by iterating over the column names contained in $path + * + * @param array|\ArrayAccess $data Data. + * @param array $path Path to extract from. + * @return mixed + */ + protected function _simpleExtract($data, $path) + { + $value = null; + foreach ($path as $column) { + if (!isset($data[$column])) { + return null; + } + $value = $data[$column]; + $data = $value; + } + return $value; + } + /** * Returns a callable that receives a value and will return whether or not * it matches certain condition. diff --git a/tests/TestCase/Collection/CollectionTest.php b/tests/TestCase/Collection/CollectionTest.php index 5633080770f..64df7c9742d 100644 --- a/tests/TestCase/Collection/CollectionTest.php +++ b/tests/TestCase/Collection/CollectionTest.php @@ -1425,7 +1425,7 @@ public function testUnfoldedExtract() ['not_comments' => []] ]; $extracted = (new Collection($items))->extract('comments.{n}.voters.{n}.id'); - $expected = [1, 2, 3, 4, 5, null]; + $expected = [1, 2, 3, 4, 5, null, 6]; $this->assertEquals($expected, $extracted->toList()); } }