aboutsummaryrefslogtreecommitdiffstats
path: root/vendor/mmccook/php-json-canonicalization-scheme/src/JsonCanonicalizator.php
blob: 6a3c82959b11147b8181e3422f7fc176d9d06e76 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
<?php

namespace Mmccook\JsonCanonicalizator;

class JsonCanonicalizator implements JsonCanonicalizatorInterface
{
    public const JSON_FLAGS = \JSON_UNESCAPED_UNICODE | \JSON_UNESCAPED_SLASHES;

    /**
     * @param $data
     * @param bool $asHex
     * @return string
     */
    public function canonicalize($data, bool $asHex = false): string
    {
        ob_start();

        $this->serialize($data);

        $result = ob_get_clean();

        return $asHex ? Utils::asHex($result) : $result;
    }

    private function serialize($item)
    {
        if (is_float($item)) {
            echo Utils::es6NumberFormat($item);

            return;
        }

        if (null === $item || is_scalar($item)) {
            echo json_encode($item, self::JSON_FLAGS);

            return;
        }

        if (is_array($item) && ! Utils::isAssoc($item)) {
            echo '[';
            $next = false;
            foreach ($item as $element) {
                if ($next) {
                    echo ',';
                }
                $next = true;
                $this->serialize($element);
            }
            echo ']';

            return;
        }

        if (is_object($item)) {
            $item = (array)$item;
        }

        uksort($item, function (string $a, string $b) {
            $a = mb_convert_encoding($a, 'UTF-16BE');
            $b = mb_convert_encoding($b, 'UTF-16BE');

            return strcmp($a, $b);
        });

        echo '{';
        $next = false;
        foreach ($item as $key => $value) {
            //var_dump($key, $value);
            if ($next) {
                echo ',';
            }
            $next = true;
            $outKey = json_encode((string)$key, self::JSON_FLAGS);
            echo $outKey, ':', $this->serialize($value);
        }
        echo '}';

    }
}