Drupal investigation

JsonEncode.php 2.1KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  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. * Returns the last encoding error (if any).
  27. *
  28. * @return int
  29. *
  30. * @deprecated since version 2.5, to be removed in 3.0.
  31. * The {@self encode()} throws an exception if error found.
  32. * @see http://php.net/manual/en/function.json-last-error.php json_last_error
  33. */
  34. public function getLastError()
  35. {
  36. @trigger_error('The '.__METHOD__.' method is deprecated since version 2.5 and will be removed in 3.0. Catch the exception raised by the encode() method instead to get the last JSON encoding error.', E_USER_DEPRECATED);
  37. return $this->lastError;
  38. }
  39. /**
  40. * Encodes PHP data to a JSON string.
  41. *
  42. * {@inheritdoc}
  43. */
  44. public function encode($data, $format, array $context = array())
  45. {
  46. $context = $this->resolveContext($context);
  47. $encodedJson = json_encode($data, $context['json_encode_options']);
  48. if (JSON_ERROR_NONE !== $this->lastError = json_last_error()) {
  49. throw new UnexpectedValueException(json_last_error_msg());
  50. }
  51. return $encodedJson;
  52. }
  53. /**
  54. * {@inheritdoc}
  55. */
  56. public function supportsEncoding($format)
  57. {
  58. return JsonEncoder::FORMAT === $format;
  59. }
  60. /**
  61. * Merge default json encode options with context.
  62. *
  63. * @param array $context
  64. *
  65. * @return array
  66. */
  67. private function resolveContext(array $context = array())
  68. {
  69. return array_merge(array('json_encode_options' => $this->options), $context);
  70. }
  71. }