Skip to content

Commit

Permalink
Merge pull request #101 from Mikulas/patch-arraycollection-sorter-dat…
Browse files Browse the repository at this point in the history
…etime

collection: fix ArrayCollection sort by DateTime
  • Loading branch information
hrach committed Aug 18, 2015
2 parents 3846fd8 + c497f58 commit da1d6e5
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 5 deletions.
19 changes: 15 additions & 4 deletions src/Collection/Helpers/ArrayCollectionHelper.php
Original file line number Diff line number Diff line change
Expand Up @@ -173,10 +173,8 @@ public function createSorter(array $conditions)

return function ($a, $b) use ($getter, $columns) {
foreach ($columns as $pair) {
$_a = $getter($a, $pair[0], $pair[2]);
$_a = $_a instanceof IEntity ? $_a->getValue('id') : $_a;
$_b = $getter($b, $pair[0], $pair[2]);
$_b = $_b instanceof IEntity ? $_b->getValue('id') : $_b;
$_a = $this->simplifyValue($getter, $a, $pair);
$_b = $this->simplifyValue($getter, $b, $pair);
$direction = $pair[1] === ICollection::ASC ? 1 : -1;

if (is_int($_a) || is_float($_a)) {
Expand All @@ -199,4 +197,17 @@ public function createSorter(array $conditions)
};
}

private function simplifyValue($getter, $raw, array $pair)
{
$value = $getter($raw, $pair[0], $pair[2]);
if ($value instanceof IEntity) {
return $value->getValue('id');

} elseif ($value instanceof \DateTime) {
return $value->format('%U.%u');
}

return $value;
}

}
6 changes: 5 additions & 1 deletion tests/cases/unit/Collection/ArrayCollectionTest.phpt
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,10 @@ class ArrayCollectionTest extends TestCase
[$authors[1], $authors[0], $authors[2]],
iterator_to_array($collection->orderBy('this->name', ICollection::DESC))
);
Assert::same(
[$authors[0], $authors[2], $authors[1]],
iterator_to_array($collection->orderBy('this->born', ICollection::DESC))
);
Assert::same(
[$authors[2], $authors[1], $authors[0]],
iterator_to_array($collection->orderBy('this->age', ICollection::DESC)->orderBy('this->name'))
Expand Down Expand Up @@ -143,7 +147,7 @@ class ArrayCollectionTest extends TestCase
$authors = [
$this->e('NextrasTests\Orm\Author', ['name' => 'Jon', 'born' => '2012-01-01']),
$this->e('NextrasTests\Orm\Author', ['name' => 'Sansa', 'born' => '2011-01-01']),
$this->e('NextrasTests\Orm\Author', ['name' => 'Eddard', 'born' => '2011-01-01']),
$this->e('NextrasTests\Orm\Author', ['name' => 'Eddard', 'born' => '2011-06-01']),
];

$books = [
Expand Down

0 comments on commit da1d6e5

Please sign in to comment.