Chris@0: Chris@0: * Chris@0: * For the full copyright and license information, please view the LICENSE Chris@0: * file that was distributed with this source code. Chris@0: */ Chris@0: Chris@0: namespace Symfony\Component\Serializer\Encoder; Chris@0: Chris@14: use Symfony\Component\Serializer\Exception\NotEncodableValueException; Chris@0: Chris@0: /** Chris@0: * Encodes JSON data. Chris@0: * Chris@0: * @author Sander Coolen Chris@0: */ Chris@0: class JsonEncode implements EncoderInterface Chris@0: { Chris@0: private $options; Chris@0: Chris@0: public function __construct($bitmask = 0) Chris@0: { Chris@0: $this->options = $bitmask; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Encodes PHP data to a JSON string. Chris@0: * Chris@0: * {@inheritdoc} Chris@0: */ Chris@17: public function encode($data, $format, array $context = []) Chris@0: { Chris@0: $context = $this->resolveContext($context); Chris@0: Chris@0: $encodedJson = json_encode($data, $context['json_encode_options']); Chris@0: Chris@14: if (JSON_ERROR_NONE !== json_last_error() && (false === $encodedJson || !($context['json_encode_options'] & JSON_PARTIAL_OUTPUT_ON_ERROR))) { Chris@14: throw new NotEncodableValueException(json_last_error_msg()); Chris@0: } Chris@0: Chris@0: return $encodedJson; Chris@0: } Chris@0: Chris@0: /** Chris@0: * {@inheritdoc} Chris@0: */ Chris@0: public function supportsEncoding($format) Chris@0: { Chris@0: return JsonEncoder::FORMAT === $format; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Merge default json encode options with context. Chris@0: * Chris@0: * @return array Chris@0: */ Chris@17: private function resolveContext(array $context = []) Chris@0: { Chris@17: return array_merge(['json_encode_options' => $this->options], $context); Chris@0: } Chris@0: }