Skip to content
Browse files

Correctly sort pairs

  • Loading branch information...
1 parent 0c57069 commit b95b8ea3ced1aaee03c810a1d38b9dde3fe18615 @davedevelopment davedevelopment committed May 13, 2012
Showing with 46 additions and 1 deletion.
  1. +19 −1 lib/GoCardless/Utils.php
  2. +27 −0 tests/lib/UtilsTest.php
View
20 lib/GoCardless/Utils.php
@@ -61,7 +61,7 @@ public static function generate_query_string($params, &$pairs = array(),
return '';
}
- sort($pairs);
+ usort($pairs, array(__CLASS__, 'sortPairs'));
$strs = array();
foreach ($pairs as $pair) {
@@ -79,6 +79,24 @@ public static function generate_query_string($params, &$pairs = array(),
}
/**
+ * Sorts a pair
+ *
+ * @param array $a
+ * @param array $b
+ * @return int
+ */
+ public static function sortPairs($a, $b)
+ {
+ $keys = strcmp($a[0], $b[0]);
+
+ if ($keys !== 0) {
+ return $keys;
+ }
+
+ return strcmp($a[1], $b[1]);
+ }
+
+ /**
* Strip underscores and convert to CamelCaps
*
* @param string $string The string to process
View
27 tests/lib/UtilsTest.php
@@ -66,6 +66,33 @@ public function testGenerateQueryStringJoinsPairsWithAmpersands() {
}
+
+ /**
+ *
+ * Test for correct sorting of keys/values
+ */
+ public function testGenerateQueryStringSortsByKeyThenValue() {
+
+ $params = array(
+ 'bills' => array(
+ array(
+ 'amount' => 10.0,
+ 'amount_minus_fees' => 9.9,
+ ),
+ array(
+ 'amount' => 19.99,
+ 'amount_minus_fees' => 19.79,
+ ),
+ ),
+ );
+
+
+ $sig = GoCardless_Utils::generate_query_string($params);
+
+ // Check against a pre-built hash
+ $this->assertEquals('bills%5B%5D%5Bamount%5D=10&bills%5B%5D%5Bamount%5D=19.99&bills%5B%5D%5Bamount_minus_fees%5D=19.79&bills%5B%5D%5Bamount_minus_fees%5D=9.9', $sig);
+ }
+
/**
* Check the signature is being generated correctly
*/

0 comments on commit b95b8ea

Please sign in to comment.
Something went wrong with that request. Please try again.