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@0: use Symfony\Component\Serializer\Exception\UnexpectedValueException; 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: private $lastError = JSON_ERROR_NONE; 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@0: public function encode($data, $format, array $context = array()) Chris@0: { Chris@0: $context = $this->resolveContext($context); Chris@0: Chris@0: $encodedJson = json_encode($data, $context['json_encode_options']); Chris@0: Chris@0: if (JSON_ERROR_NONE !== $this->lastError = json_last_error()) { Chris@0: throw new UnexpectedValueException(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: * @param array $context Chris@0: * Chris@0: * @return array Chris@0: */ Chris@0: private function resolveContext(array $context = array()) Chris@0: { Chris@0: return array_merge(array('json_encode_options' => $this->options), $context); Chris@0: } Chris@0: }