CRM_Utils_JS - Improve encode handling of strings
[civicrm-core.git] / tests / phpunit / CRM / Utils / JSTest.php
index 8517f568b914fbc7e7d809ccc9810f301210ab21..42ca9e20e99dc613804a7fa7e711cef57bd0ca0d 100644 (file)
@@ -237,6 +237,39 @@ class CRM_Utils_JSTest extends CiviUnitTestCase {
     $this->assertEquals($expectedOutput, CRM_Utils_JS::decode($input));
   }
 
+  public static function encodeExamples() {
+    return [
+      [
+        ['a' => 'Apple', 'b' => 'Banana', 'c' => [0, -2, 3.15]],
+        "{a: 'Apple', b: 'Banana', c: [0, -2, 3.15]}",
+      ],
+      [
+        ['a' => ['foo', 'bar'], 'b' => ["'a'" => ['foo/bar&', 'bar(foo)'], 'b' => ['a' => ["fo'oo", '"bar"'], 'b' => []]]],
+        "{a: ['foo', 'bar'], b: {\"'a'\": ['foo/bar&', 'bar(foo)'], b: {a: ['fo\\'oo', '\"bar\"'], b: {}}}}",
+      ],
+      [TRUE, 'true'],
+      [' ', "' '"],
+      [FALSE, 'false'],
+      [NULL, 'null'],
+      ['true', "'true'"],
+      ['"false"', "'\"false\"'"],
+      ['0.5', "'0.5'"],
+      [0.5, '0.5'],
+      [[], "{}"],
+    ];
+  }
+
+  /**
+   * @param string $input
+   * @param string $expectedOutput
+   * @dataProvider encodeExamples
+   */
+  public function testEncode($input, $expectedOutput) {
+    $result = CRM_Utils_JS::encode($input);
+    $this->assertEquals($expectedOutput, $result);
+    $this->assertEquals($input, CRM_Utils_JS::decode($result));
+  }
+
   /**
    * @return array
    */