4 * This file is part of the Symfony package.
6 * (c) Fabien Potencier <fabien@symfony.com>
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
12 namespace Symfony\Component\Serializer\Encoder;
14 use Symfony\Component\Serializer\Exception\UnexpectedValueException;
19 * @author Sander Coolen <sander@jibber.nl>
21 class JsonEncode implements EncoderInterface
24 private $lastError = JSON_ERROR_NONE;
26 public function __construct($bitmask = 0)
28 $this->options = $bitmask;
32 * Returns the last encoding error (if any).
36 * @deprecated since version 2.5, to be removed in 3.0.
37 * The {@self encode()} throws an exception if error found.
38 * @see http://php.net/manual/en/function.json-last-error.php json_last_error
40 public function getLastError()
42 @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);
44 return $this->lastError;
48 * Encodes PHP data to a JSON string.
52 public function encode($data, $format, array $context = array())
54 $context = $this->resolveContext($context);
56 $encodedJson = json_encode($data, $context['json_encode_options']);
58 if (JSON_ERROR_NONE !== $this->lastError = json_last_error()) {
59 throw new UnexpectedValueException(json_last_error_msg());
68 public function supportsEncoding($format)
70 return JsonEncoder::FORMAT === $format;
74 * Merge default json encode options with context.
76 * @param array $context
80 private function resolveContext(array $context = array())
82 return array_merge(array('json_encode_options' => $this->options), $context);