Subversion Repositories oidplus

Rev

Rev 868 | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
868 daniel-mar 1
<?php
2
 
3
declare(strict_types=1);
4
 
5
namespace aywan\JsonCanonicalization;
6
 
7
/**
8
 * @internal
9
 */
10
class Utils
11
{
12
    public static function isAssoc(array $a): bool
13
    {
14
        return [] !== $a && array_keys($a) !== range(0, count($a) - 1);
15
    }
16
 
17
    public static function asHex(string $data): string
18
    {
19
        return rtrim(chunk_split(bin2hex($data), 2, ' '));
20
    }
21
 
22
    public static function es6NumberFormat(float $number): string
23
    {
24
        if (is_nan($number) || is_infinite($number)) {
25
            throw new \RuntimeException("can't use Nan or Infinity in json");
26
        }
27
 
28
        if (0.0 === $number) {
29
            return '0';
30
        }
31
 
32
        $sign = '';
33
        if ($number < 0) {
34
            $sign = '-';
35
            $number = -$number;
36
        }
37
 
38
        if ($number < 1e+21 && $number >= 1e-6) {
39
            $formatted = sprintf('%F', $number);
1319 daniel-mar 40
            $formatted = rtrim($formatted, '0');$formatted = rtrim($formatted, '.'); //Hotfix: https://github.com/aywan/php-json-canonicalization/issues/1
868 daniel-mar 41
        } else {
42
            $formatted = sprintf('%e', $number);
43
            $parts = explode('e', $formatted);
1319 daniel-mar 44
            $parts[0] = rtrim($parts[0], '0');$parts[0] = rtrim($parts[0], '.'); //Hotfix: https://github.com/aywan/php-json-canonicalization/issues/1
868 daniel-mar 45
            $formatted = implode('e', $parts);
46
        }
47
 
48
        return $sign . $formatted;
49
    }
50
}