JsonEncoder.php 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  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. /**
  12. * Encodes JSON data.
  13. *
  14. * @author Jordi Boggiano <j.boggiano@seld.be>
  15. */
  16. class JsonEncoder implements EncoderInterface, DecoderInterface
  17. {
  18. public const FORMAT = 'json';
  19. protected $encodingImpl;
  20. protected $decodingImpl;
  21. public function __construct(JsonEncode $encodingImpl = null, JsonDecode $decodingImpl = null)
  22. {
  23. $this->encodingImpl = $encodingImpl ?: new JsonEncode();
  24. $this->decodingImpl = $decodingImpl ?: new JsonDecode([JsonDecode::ASSOCIATIVE => true]);
  25. }
  26. /**
  27. * {@inheritdoc}
  28. */
  29. public function encode($data, string $format, array $context = [])
  30. {
  31. return $this->encodingImpl->encode($data, self::FORMAT, $context);
  32. }
  33. /**
  34. * {@inheritdoc}
  35. */
  36. public function decode(string $data, string $format, array $context = [])
  37. {
  38. return $this->decodingImpl->decode($data, self::FORMAT, $context);
  39. }
  40. /**
  41. * {@inheritdoc}
  42. */
  43. public function supportsEncoding(string $format)
  44. {
  45. return self::FORMAT === $format;
  46. }
  47. /**
  48. * {@inheritdoc}
  49. */
  50. public function supportsDecoding(string $format)
  51. {
  52. return self::FORMAT === $format;
  53. }
  54. }