JsonEncode.php 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.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. namespace Symfony\Component\Serializer\Encoder;
  11. use Symfony\Component\Serializer\Exception\NotEncodableValueException;
  12. /**
  13. * Encodes JSON data.
  14. *
  15. * @author Sander Coolen <sander@jibber.nl>
  16. */
  17. class JsonEncode implements EncoderInterface
  18. {
  19. public const OPTIONS = 'json_encode_options';
  20. private $defaultContext = [
  21. self::OPTIONS => 0,
  22. ];
  23. public function __construct(array $defaultContext = [])
  24. {
  25. $this->defaultContext = array_merge($this->defaultContext, $defaultContext);
  26. }
  27. /**
  28. * Encodes PHP data to a JSON string.
  29. *
  30. * {@inheritdoc}
  31. */
  32. public function encode($data, string $format, array $context = [])
  33. {
  34. $options = $context[self::OPTIONS] ?? $this->defaultContext[self::OPTIONS];
  35. try {
  36. $encodedJson = json_encode($data, $options);
  37. } catch (\JsonException $e) {
  38. throw new NotEncodableValueException($e->getMessage(), 0, $e);
  39. }
  40. if (\PHP_VERSION_ID >= 70300 && (\JSON_THROW_ON_ERROR & $options)) {
  41. return $encodedJson;
  42. }
  43. if (\JSON_ERROR_NONE !== json_last_error() && (false === $encodedJson || !($options & \JSON_PARTIAL_OUTPUT_ON_ERROR))) {
  44. throw new NotEncodableValueException(json_last_error_msg());
  45. }
  46. return $encodedJson;
  47. }
  48. /**
  49. * {@inheritdoc}
  50. */
  51. public function supportsEncoding(string $format)
  52. {
  53. return JsonEncoder::FORMAT === $format;
  54. }
  55. }