Skip to content

Commit

Permalink
Port most recent changes in Set to Hash.
Browse files Browse the repository at this point in the history
See [68eeee8] and
[af57502]
  • Loading branch information
markstory committed Mar 27, 2012
1 parent e55927c commit 9015d78
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 2 deletions.
37 changes: 37 additions & 0 deletions lib/Cake/Test/Case/Utility/HashTest.php
Expand Up @@ -1033,6 +1033,43 @@ public function testSortWithOutOfOrderKeys() {
$this->assertEquals($expected, $result);
}

/**
* test sorting with string keys.
*
* @return void
*/
public function testSortString() {
$to_sort = array(
'four' => array('number' => 4, 'some' => 'foursome'),
'six' => array('number' => 6, 'some' => 'sixsome'),
'five' => array('number' => 5, 'some' => 'fivesome'),
'two' => array('number' => 2, 'some' => 'twosome'),
'three' => array('number' => 3, 'some' => 'threesome')
);
$sorted = Hash::sort($to_sort, '{s}.number', 'asc');
$expected = array(
'two' => array('number' => 2, 'some' => 'twosome'),
'three' => array('number' => 3, 'some' => 'threesome'),
'four' => array('number' => 4, 'some' => 'foursome'),
'five' => array('number' => 5, 'some' => 'fivesome'),
'six' => array('number' => 6, 'some' => 'sixsome')
);
$this->assertEquals($expected, $sorted);

$menus = array(
'blogs' => array('title' => 'Blogs', 'weight' => 3),
'comments' => array('title' => 'Comments', 'weight' => 2),
'users' => array('title' => 'Users', 'weight' => 1),
);
$expected = array(
'users' => array('title' => 'Users', 'weight' => 1),
'comments' => array('title' => 'Comments', 'weight' => 2),
'blogs' => array('title' => 'Blogs', 'weight' => 3),
);
$result = Hash::sort($menus, '{s}.weight', 'ASC');
$this->assertEquals($expected, $result);
}

/**
* Test insert()
*
Expand Down
13 changes: 11 additions & 2 deletions lib/Cake/Utility/Hash.php
Expand Up @@ -695,7 +695,8 @@ public static function apply(array $data, $path, $function) {
*/
public static function sort(array $data, $path, $dir) {
$originalKeys = array_keys($data);
if (is_numeric(implode('', $originalKeys))) {
$numeric = is_numeric(implode('', $originalKeys));
if ($numeric) {
$data = array_values($data);
}
$sortValues = self::extract($data, $path);
Expand All @@ -722,7 +723,15 @@ public static function sort(array $data, $path, $dir) {
$keys = array_unique($keys);

foreach ($keys as $k) {
$sorted[] = $data[$k];
if ($numeric) {
$sorted[] = $data[$k];
continue;
}
if (isset($originalKeys[$k])) {
$sorted[$originalKeys[$k]] = $data[$originalKeys[$k]];
} else {
$sorted[$k] = $data[$k];
}
}
return $sorted;
}
Expand Down

0 comments on commit 9015d78

Please sign in to comment.