vendor/api-platform/core/src/Serializer/JsonEncoder.php line 54

Open in your IDE?
  1. <?php
  2. /*
  3.  * This file is part of the API Platform project.
  4.  *
  5.  * (c) Kévin Dunglas <dunglas@gmail.com>
  6.  *
  7.  * For the full copyright and license information, please view the LICENSE
  8.  * file that was distributed with this source code.
  9.  */
  10. declare(strict_types=1);
  11. namespace ApiPlatform\Serializer;
  12. use Symfony\Component\Serializer\Encoder\DecoderInterface;
  13. use Symfony\Component\Serializer\Encoder\EncoderInterface;
  14. use Symfony\Component\Serializer\Encoder\JsonDecode;
  15. use Symfony\Component\Serializer\Encoder\JsonEncode;
  16. use Symfony\Component\Serializer\Encoder\JsonEncoder as BaseJsonEncoder;
  17. /**
  18.  * A JSON encoder with appropriate default options to embed the generated document into HTML.
  19.  *
  20.  * @author Kévin Dunglas <dunglas@gmail.com>
  21.  */
  22. final class JsonEncoder implements EncoderInterfaceDecoderInterface
  23. {
  24.     // @noRector \Rector\Php81\Rector\Property\ReadOnlyPropertyRector
  25.     public function __construct(private readonly string $format, private ?BaseJsonEncoder $jsonEncoder null)
  26.     {
  27.         if (null !== $this->jsonEncoder) {
  28.             return;
  29.         }
  30.         $this->jsonEncoder = new BaseJsonEncoder(
  31.             // Encode <, >, ', &, and " characters in the JSON, making it also safe to be embedded into HTML.
  32.             new JsonEncode(['json_encode_options' => \JSON_HEX_TAG \JSON_HEX_APOS \JSON_HEX_AMP \JSON_HEX_QUOT \JSON_UNESCAPED_UNICODE \JSON_INVALID_UTF8_IGNORE]),
  33.             new JsonDecode(['json_decode_associative' => true])
  34.         );
  35.     }
  36.     /**
  37.      * {@inheritdoc}
  38.      */
  39.     public function supportsEncoding($format, array $context = []): bool
  40.     {
  41.         return $this->format === $format;
  42.     }
  43.     /**
  44.      * {@inheritdoc}
  45.      */
  46.     public function encode($data$format, array $context = []): string
  47.     {
  48.         return $this->jsonEncoder->encode($data$format$context);
  49.     }
  50.     /**
  51.      * {@inheritdoc}
  52.      */
  53.     public function supportsDecoding($format, array $context = []): bool
  54.     {
  55.         return $this->format === $format;
  56.     }
  57.     /**
  58.      * {@inheritdoc}
  59.      */
  60.     public function decode($data$format, array $context = []): mixed
  61.     {
  62.         return $this->jsonEncoder->decode($data$format$context);
  63.     }
  64. }