refactor: centralize canonical restore json
parent
5d3efb31e5
commit
7e2c344877
@ -0,0 +1,26 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services\Cloud;
|
||||
|
||||
/** Deterministically orders JSON object keys while preserving array order. */
|
||||
final class CloudCanonicalJson
|
||||
{
|
||||
public static function normalize(array $value): array
|
||||
{
|
||||
if (array_is_list($value)) {
|
||||
return array_map(
|
||||
static fn ($item) => is_array($item)
|
||||
? self::normalize($item) : $item,
|
||||
$value
|
||||
);
|
||||
}
|
||||
|
||||
ksort($value, SORT_STRING);
|
||||
foreach ($value as $key => $item) {
|
||||
if (is_array($item)) {
|
||||
$value[$key] = self::normalize($item);
|
||||
}
|
||||
}
|
||||
return $value;
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,43 @@
|
||||
<?php
|
||||
|
||||
require dirname(__DIR__) . '/vendor/autoload.php';
|
||||
|
||||
use App\Services\Cloud\CloudCanonicalJson;
|
||||
|
||||
$assert = static function (bool $condition, string $message): void {
|
||||
if (!$condition) {
|
||||
throw new RuntimeException($message);
|
||||
}
|
||||
};
|
||||
|
||||
$normalized = CloudCanonicalJson::normalize([
|
||||
'z' => [
|
||||
'beta' => '值/one',
|
||||
'alpha' => 2,
|
||||
],
|
||||
'list' => ['z', 'a'],
|
||||
'a' => [
|
||||
['z' => 1, 'a' => 2],
|
||||
['b' => ['y' => 4, 'x' => 3], 'a' => '/路径'],
|
||||
],
|
||||
]);
|
||||
$encoded = json_encode(
|
||||
$normalized,
|
||||
JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE
|
||||
);
|
||||
$expected = '{"a":[{"a":2,"z":1},{"a":"/路径","b":{"x":3,"y":4}}],'
|
||||
. '"list":["z","a"],"z":{"alpha":2,"beta":"值/one"}}';
|
||||
|
||||
$assert($encoded === $expected,
|
||||
'Canonical JSON changed object ordering or list/scalar preservation.');
|
||||
$assert(
|
||||
hash('sha256', $encoded)
|
||||
=== '57378ceb36ac91a5cbeb44235481e9f94e5ddbc7926e0e5e197eca7294706c71',
|
||||
'Canonical JSON changed the persisted digest contract.'
|
||||
);
|
||||
$assert(
|
||||
CloudCanonicalJson::normalize($normalized) === $normalized,
|
||||
'Canonical JSON normalization is not idempotent.'
|
||||
);
|
||||
|
||||
echo "Canonical JSON behavior tests passed.\n";
|
||||
Loading…
Reference in New Issue