JsonEncoder.php 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  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. const FORMAT = 'json';
  19. /**
  20. * @var JsonEncode
  21. */
  22. protected $encodingImpl;
  23. /**
  24. * @var JsonDecode
  25. */
  26. protected $decodingImpl;
  27. public function __construct(JsonEncode $encodingImpl = null, JsonDecode $decodingImpl = null)
  28. {
  29. $this->encodingImpl = $encodingImpl ?: new JsonEncode();
  30. $this->decodingImpl = $decodingImpl ?: new JsonDecode(true);
  31. }
  32. /**
  33. * {@inheritdoc}
  34. */
  35. public function encode($data, $format, array $context = array())
  36. {
  37. return $this->encodingImpl->encode($data, self::FORMAT, $context);
  38. }
  39. /**
  40. * {@inheritdoc}
  41. */
  42. public function decode($data, $format, array $context = array())
  43. {
  44. return $this->decodingImpl->decode($data, self::FORMAT, $context);
  45. }
  46. /**
  47. * {@inheritdoc}
  48. */
  49. public function supportsEncoding($format)
  50. {
  51. return self::FORMAT === $format;
  52. }
  53. /**
  54. * {@inheritdoc}
  55. */
  56. public function supportsDecoding($format)
  57. {
  58. return self::FORMAT === $format;
  59. }
  60. }