Skip to content

Commit 162336b

Browse files
author
ndm2
committed
Fix sorting of DateTimeImmutable instances.
1 parent 4bb343d commit 162336b

File tree

2 files changed

+6
-7
lines changed

2 files changed

+6
-7
lines changed

src/Collection/Iterator/SortIterator.php

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@
1515
namespace Cake\Collection\Iterator;
1616

1717
use Cake\Collection\Collection;
18-
use DateTime;
18+
use DateTimeInterface;
1919

2020
/**
2121
* An iterator that will return the passed items in order. The order is given by
@@ -68,7 +68,7 @@ public function __construct($items, $callback, $dir = SORT_DESC, $type = SORT_NU
6868
$results = [];
6969
foreach ($items as $key => $value) {
7070
$value = $callback($value);
71-
if ($value instanceof DateTime && $type === SORT_NUMERIC) {
71+
if ($value instanceof DateTimeInterface && $type === SORT_NUMERIC) {
7272
$value = $value->format('U');
7373
}
7474
$results[$key] = $value;

tests/TestCase/Collection/Iterator/SortIteratorTest.php

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -203,9 +203,8 @@ public function testSortDateTime()
203203
$items = new ArrayObject([
204204
new \DateTime('2014-07-21'),
205205
new \DateTime('2015-06-30'),
206-
new \DateTime('2013-08-12')
206+
new \DateTimeImmutable('2013-08-12')
207207
]);
208-
$a = new \DateTime();
209208

210209
$callback = function ($a) {
211210
return $a->add(new \DateInterval('P1Y'));
@@ -214,20 +213,20 @@ public function testSortDateTime()
214213
$expected = [
215214
new \DateTime('2016-06-30'),
216215
new \DateTime('2015-07-21'),
217-
new \DateTime('2014-08-12')
216+
new \DateTimeImmutable('2013-08-12')
218217

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

222221
$items = new ArrayObject([
223222
new \DateTime('2014-07-21'),
224223
new \DateTime('2015-06-30'),
225-
new \DateTime('2013-08-12')
224+
new \DateTimeImmutable('2013-08-12')
226225
]);
227226

228227
$sorted = new SortIterator($items, $callback, SORT_ASC);
229228
$expected = [
230-
new \DateTime('2014-08-12'),
229+
new \DateTimeImmutable('2013-08-12'),
231230
new \DateTime('2015-07-21'),
232231
new \DateTime('2016-06-30'),
233232
];

0 commit comments

Comments
 (0)