Created
January 27, 2020 23:45
-
-
Save BenMorel/e588ad976a92ccd46ed4081fc2c1ef6e to your computer and use it in GitHub Desktop.
Simple canonicalization of a JSON string.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Simple canonicalization of a JSON string. | |
* | |
* - removes formatting | |
* - sorts object properties | |
*/ | |
class JsonCanonicalizer | |
{ | |
/** | |
* @param string $json | |
* | |
* @return string | |
* | |
* @throws \JsonException | |
*/ | |
public static function canonicalize(string $json) : string | |
{ | |
$data = json_decode($json, false, 512, JSON_THROW_ON_ERROR); | |
$data = self::doCanonicalize($data); | |
return json_encode($data, JSON_THROW_ON_ERROR); | |
} | |
/** | |
* @param mixed $data | |
* | |
* @return mixed | |
*/ | |
private static function doCanonicalize($data) | |
{ | |
if (is_object($data)) { | |
$data = (array) $data; | |
ksort($data); | |
foreach ($data as $key => $value) { | |
$data[$key] = self::doCanonicalize($value); | |
} | |
return (object) $data; | |
} | |
if (is_array($data)) { | |
foreach ($data as $key => $value) { | |
$data[$key] = self::doCanonicalize($value); | |
} | |
} | |
return $data; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment