Skip to content

Commit

Permalink
Fixing Set::sort() for arrays with out of sequence, or missing keys.
Browse files Browse the repository at this point in the history
Tests added.
Fixes #1312
  • Loading branch information
markstory committed Nov 25, 2010
1 parent 4214242 commit 7d158e8
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 1 deletion.
5 changes: 4 additions & 1 deletion cake/libs/set.php
Expand Up @@ -1092,6 +1092,10 @@ function __flatten($results, $key = null) {
* @static
*/
function sort($data, $path, $dir) {
$originalKeys = array_keys($data);
if (is_numeric(implode('', $originalKeys))) {
$data = array_values($data);
}
$result = Set::__flatten(Set::extract($data, $path));
list($keys, $values) = array(Set::extract($result, '{n}.id'), Set::extract($result, '{n}.value'));

Expand All @@ -1103,7 +1107,6 @@ function sort($data, $path, $dir) {
}
array_multisort($values, $dir, $keys, $dir);
$sorted = array();

$keys = array_unique($keys);

foreach ($keys as $k) {
Expand Down
27 changes: 27 additions & 0 deletions cake/tests/cases/libs/set.test.php
Expand Up @@ -354,6 +354,33 @@ function testSort() {
$this->assertEqual($result, $expected);
}

/**
* test sorting with out of order keys.
*
* @return void
*/
function testSortWithOutOfOrderKeys() {
$data = array(
9 => array('class' => 510, 'test2' => 2),
1 => array('class' => 500, 'test2' => 1),
2 => array('class' => 600, 'test2' => 2),
5 => array('class' => 625, 'test2' => 4),
0 => array('class' => 605, 'test2' => 3),
);
$expected = array(
array('class' => 500, 'test2' => 1),
array('class' => 510, 'test2' => 2),
array('class' => 600, 'test2' => 2),
array('class' => 605, 'test2' => 3),
array('class' => 625, 'test2' => 4),
);
$result = Set::sort($data, '{n}.class', 'asc');
$this->assertEqual($expected, $result);

$result = Set::sort($data, '{n}.test2', 'asc');
$this->assertEqual($expected, $result);
}

/**
* testExtract method
*
Expand Down

0 comments on commit 7d158e8

Please sign in to comment.