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 JsonDecode implements DecoderInterface
23 protected $serializer;
26 private $recursionDepth;
29 * Constructs a new JsonDecode instance.
31 * @param bool $associative True to return the result associative array, false for a nested stdClass hierarchy
32 * @param int $depth Specifies the recursion depth
34 public function __construct($associative = false, $depth = 512)
36 $this->associative = $associative;
37 $this->recursionDepth = (int) $depth;
43 * @param string $data The encoded JSON string to decode
44 * @param string $format Must be set to JsonEncoder::FORMAT
45 * @param array $context An optional set of options for the JSON decoder; see below
47 * The $context array is a simple key=>value array, with the following supported keys:
49 * json_decode_associative: boolean
50 * If true, returns the object as associative array.
51 * If false, returns the object as nested stdClass
52 * If not specified, this method will use the default set in JsonDecode::__construct
54 * json_decode_recursion_depth: integer
55 * Specifies the maximum recursion depth
56 * If not specified, this method will use the default set in JsonDecode::__construct
58 * json_decode_options: integer
59 * Specifies additional options as per documentation for json_decode. Only supported with PHP 5.4.0 and higher
63 * @throws NotEncodableValueException
65 * @see http://php.net/json_decode json_decode
67 public function decode($data, $format, array $context = array())
69 $context = $this->resolveContext($context);
71 $associative = $context['json_decode_associative'];
72 $recursionDepth = $context['json_decode_recursion_depth'];
73 $options = $context['json_decode_options'];
75 $decodedData = json_decode($data, $associative, $recursionDepth, $options);
77 if (JSON_ERROR_NONE !== json_last_error()) {
78 throw new NotEncodableValueException(json_last_error_msg());
87 public function supportsDecoding($format)
89 return JsonEncoder::FORMAT === $format;
93 * Merges the default options of the Json Decoder with the passed context.
97 private function resolveContext(array $context)
99 $defaultOptions = array(
100 'json_decode_associative' => $this->associative,
101 'json_decode_recursion_depth' => $this->recursionDepth,
102 'json_decode_options' => 0,
105 return array_merge($defaultOptions, $context);