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\NotEncodableValueException;
19 * @author Sander Coolen <sander@jibber.nl>
21 class JsonEncode implements EncoderInterface
25 public function __construct($bitmask = 0)
27 $this->options = $bitmask;
31 * Encodes PHP data to a JSON string.
35 public function encode($data, $format, array $context = array())
37 $context = $this->resolveContext($context);
39 $encodedJson = json_encode($data, $context['json_encode_options']);
41 if (JSON_ERROR_NONE !== json_last_error() && (false === $encodedJson || !($context['json_encode_options'] & JSON_PARTIAL_OUTPUT_ON_ERROR))) {
42 throw new NotEncodableValueException(json_last_error_msg());
51 public function supportsEncoding($format)
53 return JsonEncoder::FORMAT === $format;
57 * Merge default json encode options with context.
61 private function resolveContext(array $context = array())
63 return array_merge(array('json_encode_options' => $this->options), $context);