JsonEncode.php 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  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\UnexpectedValueException;
  12. /**
  13. * Encodes JSON data.
  14. *
  15. * @author Sander Coolen <sander@jibber.nl>
  16. */
  17. class JsonEncode implements EncoderInterface
  18. {
  19. private $options;
  20. private $lastError = JSON_ERROR_NONE;
  21. public function __construct($bitmask = 0)
  22. {
  23. $this->options = $bitmask;
  24. }
  25. /**
  26. * Encodes PHP data to a JSON string.
  27. *
  28. * {@inheritdoc}
  29. */
  30. public function encode($data, $format, array $context = array())
  31. {
  32. $context = $this->resolveContext($context);
  33. $encodedJson = json_encode($data, $context['json_encode_options']);
  34. if (JSON_ERROR_NONE !== $this->lastError = json_last_error()) {
  35. throw new UnexpectedValueException(json_last_error_msg());
  36. }
  37. return $encodedJson;
  38. }
  39. /**
  40. * {@inheritdoc}
  41. */
  42. public function supportsEncoding($format)
  43. {
  44. return JsonEncoder::FORMAT === $format;
  45. }
  46. /**
  47. * Merge default json encode options with context.
  48. *
  49. * @param array $context
  50. *
  51. * @return array
  52. */
  53. private function resolveContext(array $context = array())
  54. {
  55. return array_merge(array('json_encode_options' => $this->options), $context);
  56. }
  57. }