Skip to content

Commit

Permalink
allow Dates to be numerically sorted.
Browse files Browse the repository at this point in the history
Solves #7095 by converting automatically Datetime to seconds when SORT_NUMERIC is used.
  • Loading branch information
antograssiot committed Jul 31, 2015
1 parent 0572b6c commit abf342f
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 0 deletions.
3 changes: 3 additions & 0 deletions src/Collection/Iterator/SortIterator.php
Expand Up @@ -67,6 +67,9 @@ public function __construct($items, $callback, $dir = SORT_DESC, $type = SORT_NU
$callback = $this->_propertyExtractor($callback);
$results = [];
foreach ($items as $key => $value) {
if ($value instanceof \DateTime && $type === SORT_NUMERIC) {

This comment has been minimized.

Copy link
@Oxicode

Oxicode Aug 1, 2015

Contributor

Check equals in foreach?
Comparar igualdad de tipo en un bucle ?

$value = $value->format('U');
}
$results[$key] = $callback($value);
}

Expand Down
33 changes: 33 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,36 @@ public function testSortComplexDeepPath()
];
$this->assertEquals($expected, $sorted->toList());
}

/**
* Tests sorting datetime
*
* @return void
*/
public function testSortDateTime()
{
$items = new ArrayObject([
new Time('2014-07-21'),
new Time('2015-06-30'),
new Time('2013-08-12')
]);
$identity = function ($a) {
return $a;
};
$sorted = new SortIterator($items, $identity);
$expected = [
new Time('2015-06-30'),
new Time('2014-07-21'),
new Time('2013-08-12')
];
$this->assertEquals($expected, $sorted->toList());

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

0 comments on commit abf342f

Please sign in to comment.