Skip to content

Commit

Permalink
Consolidating common code
Browse files Browse the repository at this point in the history
  • Loading branch information
lorenzo committed Jan 6, 2015
1 parent a9aff86 commit 2db5ae4
Showing 1 changed file with 20 additions and 14 deletions.
34 changes: 20 additions & 14 deletions src/Collection/CollectionTrait.php
Expand Up @@ -46,11 +46,7 @@ trait CollectionTrait
*/
public function each(callable $c)
{
$iterator = $this;
while (get_class($iterator) === 'Cake\Collection\Collection') {
$iterator = $iterator->getInnerIterator();
}
foreach ($iterator as $k => $v) {
foreach ($this->_unwrap() as $k => $v) {
$c($v, $k);
}
return $this;
Expand Down Expand Up @@ -414,15 +410,10 @@ public function insert($path, $values)
*/
public function toArray($preserveKeys = true)
{
if (get_class($this) === 'Cake\Collection\Collection') {
$inner = $this->getInnerIterator();
if ($inner instanceof ArrayIterator) {
$items = $this->getInnerIterator()->getArrayCopy();
return $preserveKeys ? $items : array_values($items);
}
if ($inner instanceof CollectionInterface) {
return $inner->toArray($preserveKeys);
}
$iterator = $this->_unwrap();
if ($iterator instanceof ArrayIterator) {
$items = $iterator->getArrayCopy();
return $preserveKeys ? $items : array_values($items);
}
return iterator_to_array($this, $preserveKeys);
}
Expand Down Expand Up @@ -515,4 +506,19 @@ public function unfold(callable $transformer = null)
)
);
}

/**
* Returns the closest nested iterator that can be safely traversed without
* losing any possible transformations.
*
* @return \Iterator
*/
protected function _unwrap() {
$iterator = $this;
while (get_class($iterator) === 'Cake\Collection\Collection') {
$iterator = $iterator->getInnerIterator();
}
return $iterator;
}

}

0 comments on commit 2db5ae4

Please sign in to comment.