aboutsummaryrefslogtreecommitdiffstats
path: root/vendor/mmccook/php-json-canonicalization-scheme/src/Utils.php
blob: 755ba33202d7509a29d40d967a72f22fada25eea (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
<?php

namespace Mmccook\JsonCanonicalizator;

class Utils
{
    /**
     * @param array $array
     * @return bool
     */
    public static function isAssoc(array $array): bool
    {
        $keys = array_keys($array);

        return array_keys($keys) !== $keys;
    }

    public static function asHex(string $data): string
    {
        return rtrim(chunk_split(bin2hex($data), 2, ' '));
    }

    public static function es6NumberFormat(float $number): string
    {

        if (is_nan($number) || is_infinite($number)) {
            throw new \RuntimeException("can't use Nan or Infinity in json");
        }

        if (0.0 === $number) {
            return '0';
        }

        $sign = '';
        if ($number < 0) {
            $sign = '-';
            $number = -$number;
        }

        if ($number < 1e+21 && $number >= 1e-6) {
            $formatted = sprintf('%F', $number);
            $formatted = rtrim($formatted, '0'); // first remove all zeros at the end
            $formatted = rtrim($formatted, '.'); // If the string now ends with a decimal point, then remove it, too.
        } else {
            $formatted = sprintf('%e', $number);
            $parts = explode('e', $formatted);
            $parts[0] = rtrim($parts[0], '0');
            $parts[0] = rtrim($parts[0], '.');
            $formatted = implode('e', $parts);
        }

        return $sign . $formatted;
    }
}