Skip to content

Commit 2ed6f92

Browse files
committed
Refactored duplicated code that was used for extracting properties from
an array into a trait
1 parent 86cbdba commit 2ed6f92

File tree

2 files changed

+6
-57
lines changed

2 files changed

+6
-57
lines changed

Cake/Collection/CollectionTrait.php

Lines changed: 2 additions & 40 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,8 @@
2727
*/
2828
trait CollectionTrait {
2929

30+
use ExtractTrait;
31+
3032
/**
3133
* Executes the passed callable for each of the elements in this collection
3234
* and passes both the value and key for them on each step.
@@ -624,44 +626,4 @@ public function jsonSerialize() {
624626
return $this->toArray();
625627
}
626628

627-
/**
628-
* Returns a callable that can be used to extract a property or column from
629-
* an array or object based on a dot separated path.
630-
*
631-
* @param string|callable $callback A dot separated path of column to follow
632-
* so that the final one can be returned or a callable that will take care
633-
* of doing that.
634-
* @return callable
635-
*/
636-
protected function _propertyExtractor($callback) {
637-
if (is_string($callback)) {
638-
$path = $path = explode('.', $callback);
639-
$callback = function($element) use ($path) {
640-
return $this->_extract($element, $path);
641-
};
642-
}
643-
644-
return $callback;
645-
}
646-
647-
/**
648-
* Returns a column from $data that can be extracted
649-
* by iterating over the column names contained in $path
650-
*
651-
* @param array|\ArrayAccess $data
652-
* @param array $path
653-
* @return mixed
654-
*/
655-
protected function _extract($data, $path) {
656-
$value = null;
657-
foreach ($path as $column) {
658-
if (!isset($data[$column])) {
659-
return null;
660-
}
661-
$value = $data[$column];
662-
$data = $value;
663-
}
664-
return $value;
665-
}
666-
667629
}

Cake/Collection/Iterator/SortIterator.php

Lines changed: 4 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414
*/
1515
namespace Cake\Collection\Iterator;
1616

17+
use Cake\Collection\ExtractTrait;
1718
use SplHeap;
1819

1920
/**
@@ -38,6 +39,8 @@
3839
*/
3940
class SortIterator extends SplHeap {
4041

42+
use ExtractTrait;
43+
4144
/**
4245
* Original items passed to this iterator
4346
*
@@ -89,23 +92,7 @@ public function __construct($items, $c, $dir = SORT_DESC, $type = SORT_NUMERIC)
8992
$this->_items = $items;
9093
$this->_dir = $dir;
9194
$this->_type = $type;
92-
93-
if (is_string($c)) {
94-
$path = explode('.', $c);
95-
$c = function($current) use ($path) {
96-
$value = null;
97-
foreach ($path as $column) {
98-
if (!isset($current[$column])) {
99-
return null;
100-
}
101-
$value = $current[$column];
102-
$current = $value;
103-
}
104-
return $value;
105-
};
106-
}
107-
108-
$this->_callback = $c;
95+
$this->_callback = $this->_propertyExtractor($c);
10996
}
11097

11198
/**

0 commit comments

Comments
 (0)