Subversion Repositories oidplus

Rev

Go to most recent revision | Blame | Compare with Previous | Last modification | View Log | RSS feed

  1. <?php
  2.  
  3. declare(strict_types=1);
  4.  
  5. namespace aywan\JsonCanonicalization;
  6.  
  7. class Canonicalizator implements JsonCanonicalizationInterface
  8. {
  9.     const JSON_FLAGS = \JSON_UNESCAPED_UNICODE | \JSON_UNESCAPED_SLASHES;
  10.  
  11.     public function canonicalize($data, bool $asHex = false): string
  12.     {
  13.         ob_start();
  14.  
  15.         $this->serialize($data);
  16.  
  17.         $result = ob_get_clean();
  18.  
  19.         return $asHex ? Utils::asHex($result) :  $result;
  20.     }
  21.  
  22.     private function serialize($item)/*: void*/  // ViaThinkSoft: Removed ": void" for PHP 7.0 compatibility
  23.     {
  24.         if (is_float($item)) {
  25.             echo Utils::es6NumberFormat($item);
  26.             return;
  27.         }
  28.  
  29.         if (null === $item || is_scalar($item)) {
  30.             echo json_encode($item, self::JSON_FLAGS);
  31.             return;
  32.         }
  33.  
  34.         if (is_array($item) && ! Utils::isAssoc($item)) {
  35.             echo '[';
  36.             $next = false;
  37.             foreach ($item as $element) {
  38.                 if ($next) {
  39.                     echo ',';
  40.                 }
  41.                 $next = true;
  42.                 $this->serialize($element);
  43.             }
  44.             echo ']';
  45.             return;
  46.         }
  47.  
  48.         if (is_object($item)) {
  49.             $item = (array)$item;
  50.         }
  51.  
  52.         uksort($item, function (string $a, string $b) {
  53.             $a = mb_convert_encoding($a, 'UTF-16BE');
  54.             $b = mb_convert_encoding($b, 'UTF-16BE');
  55.             return strcmp($a, $b);
  56.         });
  57.  
  58.         echo '{';
  59.         $next = false;
  60.         foreach ($item as $key => $value) {
  61.             if ($next) {
  62.                 echo ',';
  63.             }
  64.             $next = true;
  65.             $outKey = json_encode((string)$key, self::JSON_FLAGS);
  66.             echo $outKey, ':', $this->serialize($value);
  67.         }
  68.         echo '}';
  69.     }
  70. }
  71.