Skip to content

Commit

Permalink
Cleaning code and adding another test case
Browse files Browse the repository at this point in the history
  • Loading branch information
lorenzo committed May 31, 2015
1 parent 4761d41 commit 74bf9f0
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 6 deletions.
37 changes: 32 additions & 5 deletions src/Collection/ExtractTrait.php
Expand Up @@ -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.
Expand Down Expand Up @@ -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.
Expand Down
2 changes: 1 addition & 1 deletion tests/TestCase/Collection/CollectionTest.php
Expand Up @@ -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());
}
}

0 comments on commit 74bf9f0

Please sign in to comment.