<?php

declare(strict_types=1);

namespace Drupal\languagewire_translation_provider\api\Libraries\Content;

/**
 * JSON content encoder/decoder.
 */
final class JsonCodec {

  /**
   * Encodes data into JSON format.
   *
   * @param mixed $data
   *   The data to encode.
   *
   * @return string
   *   The JSON encoded data.
   */
  public static function encode(mixed $data): string {
    return json_encode($data);
  }

  /**
   * Decodes JSON string into array.
   *
   * This method takes into account that JSON string provided
   * can be compliant with the RFC 4627 specification
   * (it allows JSON to be embedded into HTML).
   * It means that certain characters can be converted to Unicode characters.
   * For example the quote (`"`) will be converted to `\u0022`,
   * ampersand (`&`) will be converted to `\u0026`, etc.
   *
   * @param string $data
   *   The JSON string to decode.
   *
   * @return array|null
   *   The decoded data.
   */
  public static function decode(string $data): ?array {
    if ($data === '') {
      return NULL;
    }

    do {
      // Decode until there no longer are any Unicode escape
      // sequences left or data was converted to array.
      $data = json_decode($data, TRUE);
    } while (!is_array($data) && preg_match('#\X#u', $data));

    return $data;
  }

}
