Browse Source

Merge pull request #9335 from hytromo/master

Add 'locale' option to Hash::sort
Mark Story 9 years ago
parent
commit
667cdbb53b
2 changed files with 37 additions and 1 deletions
  1. 4 1
      src/Utility/Hash.php
  2. 33 0
      tests/TestCase/Utility/HashTest.php

+ 4 - 1
src/Utility/Hash.php

@@ -928,7 +928,8 @@ class Hash
      * - `regular` For regular sorting (don't change types)
      * - `numeric` Compare values numerically
      * - `string` Compare values as strings
-     * - `natural` Compare items as strings using "natural ordering" in a human friendly way.
+     * - `locale` Compare items as strings, based on the current locale
+     * - `natural` Compare items as strings using "natural ordering" in a human friendly way
      *   Will sort foo10 below foo2 as an example.
      *
      * To do case insensitive sorting, pass the type as an array as follows:
@@ -998,6 +999,8 @@ class Hash
             $type = SORT_STRING;
         } elseif ($type === 'natural') {
             $type = SORT_NATURAL;
+        } elseif ($type === 'locale') {
+            $type = SORT_LOCALE_STRING;
         } else {
             $type = SORT_REGULAR;
         }

+ 33 - 0
tests/TestCase/Utility/HashTest.php

@@ -1678,6 +1678,39 @@ class HashTest extends TestCase
     }
 
     /**
+     * Test sort() with locale option.
+     *
+     * @return void
+     */
+    public function testSortLocale()
+    {
+        // get the current locale
+        $oldLocale = setlocale(LC_COLLATE, '0');
+
+        // the de_DE.utf8 locale must be installed on the system where the test is performed
+        setlocale(LC_COLLATE, 'de_DE.utf8');
+
+        $items = [
+            ['Item' => ['entry' => 'Übergabe']],
+            ['Item' => ['entry' => 'Ostfriesland']],
+            ['Item' => ['entry' => 'Äpfel']],
+            ['Item' => ['entry' => 'Apfel']],
+        ];
+
+        $result = Hash::sort($items, '{n}.Item.entry', 'asc', 'locale');
+        $expected = [
+            ['Item' => ['entry' => 'Apfel']],
+            ['Item' => ['entry' => 'Äpfel']],
+            ['Item' => ['entry' => 'Ostfriesland']],
+            ['Item' => ['entry' => 'Übergabe']],
+        ];
+        $this->assertEquals($expected, $result);
+
+        // change to the original locale
+        setlocale(LC_COLLATE, $oldLocale);
+    }
+
+    /**
      * Test that sort() with 'natural' type will fallback to 'regular' as SORT_NATURAL is introduced in PHP 5.4
      *
      * @return void