Skip to content

Commit

Permalink
Refactored duplicated code that was used for extracting properties from
Browse files Browse the repository at this point in the history
an array into a trait
  • Loading branch information
lorenzo committed Dec 27, 2013
1 parent 86cbdba commit 2ed6f92
Show file tree
Hide file tree
Showing 2 changed files with 6 additions and 57 deletions.
42 changes: 2 additions & 40 deletions Cake/Collection/CollectionTrait.php
Expand Up @@ -27,6 +27,8 @@
*/
trait CollectionTrait {

use ExtractTrait;

/**
* Executes the passed callable for each of the elements in this collection
* and passes both the value and key for them on each step.
Expand Down Expand Up @@ -624,44 +626,4 @@ public function jsonSerialize() {
return $this->toArray();
}

/**
* Returns a callable that can be used to extract a property or column from
* an array or object based on a dot separated path.
*
* @param string|callable $callback A dot separated path of column to follow
* so that the final one can be returned or a callable that will take care
* of doing that.
* @return callable
*/
protected function _propertyExtractor($callback) {
if (is_string($callback)) {
$path = $path = explode('.', $callback);
$callback = function($element) use ($path) {
return $this->_extract($element, $path);
};
}

return $callback;
}

/**
* Returns a column from $data that can be extracted
* by iterating over the column names contained in $path
*
* @param array|\ArrayAccess $data
* @param array $path
* @return mixed
*/
protected function _extract($data, $path) {
$value = null;
foreach ($path as $column) {
if (!isset($data[$column])) {
return null;
}
$value = $data[$column];
$data = $value;
}
return $value;
}

}
21 changes: 4 additions & 17 deletions Cake/Collection/Iterator/SortIterator.php
Expand Up @@ -14,6 +14,7 @@
*/
namespace Cake\Collection\Iterator;

use Cake\Collection\ExtractTrait;
use SplHeap;

/**
Expand All @@ -38,6 +39,8 @@
*/
class SortIterator extends SplHeap {

use ExtractTrait;

/**
* Original items passed to this iterator
*
Expand Down Expand Up @@ -89,23 +92,7 @@ public function __construct($items, $c, $dir = SORT_DESC, $type = SORT_NUMERIC)
$this->_items = $items;
$this->_dir = $dir;
$this->_type = $type;

if (is_string($c)) {
$path = explode('.', $c);
$c = function($current) use ($path) {
$value = null;
foreach ($path as $column) {
if (!isset($current[$column])) {
return null;
}
$value = $current[$column];
$current = $value;
}
return $value;
};
}

$this->_callback = $c;
$this->_callback = $this->_propertyExtractor($c);
}

/**
Expand Down

0 comments on commit 2ed6f92

Please sign in to comment.