Unverified Commit 4d5b85cf authored by Eileen McNaughton's avatar Eileen McNaughton Committed by GitHub

Merge pull request #14537 from colemanw/jsDecode

Add CRM_Utils_JS::decode function for decoding js objects
parents 29e2e3c1 a49c5ad6
......@@ -126,4 +126,22 @@ class CRM_Utils_JS {
return preg_replace(":^\\s*//[^\n]+$:m", "", $script);
}
/**
* Decodes a js object (not necessarily strict json but valid js) into an array or primitive type
*
* ex. {a: 'Apple', 'b': "Banana", c: [1, 2, 3]}
*
* @param string $js
* @return mixed
*/
public static function decode($js) {
if (!class_exists('Services_JSON')) {
require_once 'packages/OpenFlashChart/php-ofc-library/JSON.php';
}
$codec = new Services_JSON();
$result = $codec->decode($js);
// Converts stdClass to array
return json_decode(json_encode($result), TRUE);
}
}
......@@ -199,4 +199,26 @@ class CRM_Utils_JSTest extends CiviUnitTestCase {
$this->assertEquals($expectedOutput, CRM_Utils_JS::stripComments($input));
}
public static function decodeExamples() {
return [
['{a: \'Apple\', \'b\': "Banana", c: [1, 2, 3]}', ['a' => 'Apple', 'b' => 'Banana', 'c' => [1, 2, 3]]],
['true', TRUE],
['false', FALSE],
['null', NULL],
['0.5', 0.5],
["{}", []],
["[]", []],
['{a: ["foo", "bar"], b: {a: ["foo", "bar"], b: {a: ["foo", "bar"], b: {}}}}', ['a' => ['foo', 'bar'], 'b' => ['a' => ['foo', 'bar'], 'b' => ['a' => ['foo', 'bar'], 'b' => []]]]],
];
}
/**
* @param string $input
* @param string $expectedOutput
* @dataProvider decodeExamples
*/
public function testDecode($input, $expectedOutput) {
$this->assertEquals($expectedOutput, CRM_Utils_JS::decode($input));
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment