Skip to content

Commit

Permalink
Merge pull request #7153 from antograssiot/issue-7095
Browse files Browse the repository at this point in the history
allow Dates to be numerically sorted by SortIterator
  • Loading branch information
lorenzo committed Aug 3, 2015
2 parents a301fec + a718ac7 commit f2bd73d
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 2 deletions.
8 changes: 6 additions & 2 deletions src/Collection/Iterator/SortIterator.php
Expand Up @@ -46,7 +46,7 @@ class SortIterator extends Collection
*
* The callback will receive as first argument each of the elements in $items,
* the value returned in the callback will be used as the value for sorting such
* element. Please not that the callback function could be called more than once
* element. Please note that the callback function could be called more than once
* per element.
*
* @param array|\Traversable $items The values to sort
Expand All @@ -67,7 +67,11 @@ public function __construct($items, $callback, $dir = SORT_DESC, $type = SORT_NU
$callback = $this->_propertyExtractor($callback);
$results = [];
foreach ($items as $key => $value) {
$results[$key] = $callback($value);
$value = $callback($value);
if ($value instanceof \DateTime && $type === SORT_NUMERIC) {
$value = $value->format('U');
}
$results[$key] = $value;
}

$dir === SORT_DESC ? arsort($results, $type) : asort($results, $type);
Expand Down
42 changes: 42 additions & 0 deletions tests/TestCase/Collection/Iterator/SortIteratorTest.php
Expand Up @@ -16,6 +16,7 @@

use ArrayObject;
use Cake\Collection\Iterator\SortIterator;
use Cake\I18n\Time;
use Cake\TestSuite\TestCase;

/**
Expand Down Expand Up @@ -191,4 +192,45 @@ public function testSortComplexDeepPath()
];
$this->assertEquals($expected, $sorted->toList());
}

/**
* Tests sorting datetime
*
* @return void
*/
public function testSortDateTime()
{
$items = new ArrayObject([
new \DateTime('2014-07-21'),
new \DateTime('2015-06-30'),
new \DateTime('2013-08-12')
]);
$a = new \DateTime();

$callback = function ($a) {
return $a->add(new \DateInterval('P1Y'));
};
$sorted = new SortIterator($items, $callback);
$expected = [
new \DateTime('2016-06-30'),
new \DateTime('2015-07-21'),
new \DateTime('2014-08-12')

];
$this->assertEquals($expected, $sorted->toList());

$items = new ArrayObject([
new \DateTime('2014-07-21'),
new \DateTime('2015-06-30'),
new \DateTime('2013-08-12')
]);

$sorted = new SortIterator($items, $callback, SORT_ASC);
$expected = [
new \DateTime('2014-08-12'),
new \DateTime('2015-07-21'),
new \DateTime('2016-06-30'),
];
$this->assertEquals($expected, $sorted->toList());
}
}

0 comments on commit f2bd73d

Please sign in to comment.