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

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. use Symfony\Component\Serializer\NameConverter\AdvancedNameConverterInterface;
  18. /**
  19. * A JSON encoder with appropriate default options to embed the generated document into HTML.
  20. *
  21. * @author Kévin Dunglas <dunglas@gmail.com>
  22. */
  23. final class JsonEncoder implements EncoderInterface, DecoderInterface
  24. {
  25. private $format;
  26. private $jsonEncoder;
  27. public function __construct(string $format, BaseJsonEncoder $jsonEncoder = null)
  28. {
  29. $this->format = $format;
  30. $this->jsonEncoder = $jsonEncoder;
  31. if (null !== $this->jsonEncoder) {
  32. return;
  33. }
  34. // Encode <, >, ', &, and " characters in the JSON, making it also safe to be embedded into HTML.
  35. $jsonEncodeOptions = \JSON_HEX_TAG | \JSON_HEX_APOS | \JSON_HEX_AMP | \JSON_HEX_QUOT | \JSON_UNESCAPED_UNICODE | (\PHP_VERSION_ID >= 70200 ? \JSON_INVALID_UTF8_IGNORE : 0);
  36. if (interface_exists(AdvancedNameConverterInterface::class)) {
  37. $jsonEncode = new JsonEncode(['json_encode_options' => $jsonEncodeOptions]);
  38. $jsonDecode = new JsonDecode(['json_decode_associative' => true]);
  39. } else {
  40. $jsonEncode = new JsonEncode($jsonEncodeOptions);
  41. $jsonDecode = new JsonDecode(true);
  42. }
  43. $this->jsonEncoder = new BaseJsonEncoder($jsonEncode, $jsonDecode);
  44. }
  45. /**
  46. * {@inheritdoc}
  47. */
  48. public function supportsEncoding($format, array $context = []): bool
  49. {
  50. return $this->format === $format;
  51. }
  52. /**
  53. * {@inheritdoc}
  54. */
  55. public function encode($data, $format, array $context = []): string
  56. {
  57. return $this->jsonEncoder->encode($data, $format, $context);
  58. }
  59. /**
  60. * {@inheritdoc}
  61. */
  62. public function supportsDecoding($format, array $context = []): bool
  63. {
  64. return $this->format === $format;
  65. }
  66. /**
  67. * {@inheritdoc}
  68. *
  69. * @return mixed
  70. */
  71. public function decode($data, $format, array $context = [])
  72. {
  73. return $this->jsonEncoder->decode($data, $format, $context);
  74. }
  75. }
  76. class_alias(JsonEncoder::class, \ApiPlatform\Core\Serializer\JsonEncoder::class);