Skip to content
Permalink
Browse files

Refactored duplicated code that was used for extracting properties from

an array into a trait
  • Loading branch information...
lorenzo committed Dec 27, 2013
1 parent 86cbdba commit 2ed6f921d810ce4416abbf12e88a12607210cbf1
Showing with 6 additions and 57 deletions.
  1. +2 −40 Cake/Collection/CollectionTrait.php
  2. +4 −17 Cake/Collection/Iterator/SortIterator.php
@@ -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.
@@ -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;
}
}
@@ -14,6 +14,7 @@
*/
namespace Cake\Collection\Iterator;
use Cake\Collection\ExtractTrait;
use SplHeap;
/**
@@ -38,6 +39,8 @@
*/
class SortIterator extends SplHeap {
use ExtractTrait;
/**
* Original items passed to this iterator
*
@@ -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);
}
/**

0 comments on commit 2ed6f92

Please sign in to comment.
You can’t perform that action at this time.