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 * Encodes PHP data to a JSON string.
36 public function encode($data, $format, array $context = array())
38 $context = $this->resolveContext($context);
40 $encodedJson = json_encode($data, $context['json_encode_options']);
42 if (JSON_ERROR_NONE !== $this->lastError = json_last_error()) {
43 throw new UnexpectedValueException(json_last_error_msg());
52 public function supportsEncoding($format)
54 return JsonEncoder::FORMAT === $format;
58 * Merge default json encode options with context.
60 * @param array $context
64 private function resolveContext(array $context = array())
66 return array_merge(array('json_encode_options' => $this->options), $context);