Skip to content
This repository
Browse code

Correctly sort pairs

  • Loading branch information...
commit b95b8ea3ced1aaee03c810a1d38b9dde3fe18615 1 parent 0c57069
Dave Marshall davedevelopment authored

Showing 2 changed files with 46 additions and 1 deletion. Show diff stats Hide diff stats

  1. +19 1 lib/GoCardless/Utils.php
  2. +27 0 tests/lib/UtilsTest.php
20 lib/GoCardless/Utils.php
@@ -61,7 +61,7 @@ public static function generate_query_string($params, &$pairs = array(),
61 61 return '';
62 62 }
63 63
64   - sort($pairs);
  64 + usort($pairs, array(__CLASS__, 'sortPairs'));
65 65
66 66 $strs = array();
67 67 foreach ($pairs as $pair) {
@@ -79,6 +79,24 @@ public static function generate_query_string($params, &$pairs = array(),
79 79 }
80 80
81 81 /**
  82 + * Sorts a pair
  83 + *
  84 + * @param array $a
  85 + * @param array $b
  86 + * @return int
  87 + */
  88 + public static function sortPairs($a, $b)
  89 + {
  90 + $keys = strcmp($a[0], $b[0]);
  91 +
  92 + if ($keys !== 0) {
  93 + return $keys;
  94 + }
  95 +
  96 + return strcmp($a[1], $b[1]);
  97 + }
  98 +
  99 + /**
82 100 * Strip underscores and convert to CamelCaps
83 101 *
84 102 * @param string $string The string to process
27 tests/lib/UtilsTest.php
@@ -66,6 +66,33 @@ public function testGenerateQueryStringJoinsPairsWithAmpersands() {
66 66
67 67 }
68 68
  69 +
  70 + /**
  71 + *
  72 + * Test for correct sorting of keys/values
  73 + */
  74 + public function testGenerateQueryStringSortsByKeyThenValue() {
  75 +
  76 + $params = array(
  77 + 'bills' => array(
  78 + array(
  79 + 'amount' => 10.0,
  80 + 'amount_minus_fees' => 9.9,
  81 + ),
  82 + array(
  83 + 'amount' => 19.99,
  84 + 'amount_minus_fees' => 19.79,
  85 + ),
  86 + ),
  87 + );
  88 +
  89 +
  90 + $sig = GoCardless_Utils::generate_query_string($params);
  91 +
  92 + // Check against a pre-built hash
  93 + $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);
  94 + }
  95 +
69 96 /**
70 97 * Check the signature is being generated correctly
71 98 */

0 comments on commit b95b8ea

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