ef084eeab2b9c2dc13ad6606be533b7dbf9a5588
[yaffs-website] / vendor / symfony / serializer / Encoder / JsonEncode.php
1 <?php
2
3 /*
4  * This file is part of the Symfony package.
5  *
6  * (c) Fabien Potencier <fabien@symfony.com>
7  *
8  * For the full copyright and license information, please view the LICENSE
9  * file that was distributed with this source code.
10  */
11
12 namespace Symfony\Component\Serializer\Encoder;
13
14 use Symfony\Component\Serializer\Exception\NotEncodableValueException;
15
16 /**
17  * Encodes JSON data.
18  *
19  * @author Sander Coolen <sander@jibber.nl>
20  */
21 class JsonEncode implements EncoderInterface
22 {
23     private $options;
24
25     public function __construct($bitmask = 0)
26     {
27         $this->options = $bitmask;
28     }
29
30     /**
31      * Encodes PHP data to a JSON string.
32      *
33      * {@inheritdoc}
34      */
35     public function encode($data, $format, array $context = array())
36     {
37         $context = $this->resolveContext($context);
38
39         $encodedJson = json_encode($data, $context['json_encode_options']);
40
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());
43         }
44
45         return $encodedJson;
46     }
47
48     /**
49      * {@inheritdoc}
50      */
51     public function supportsEncoding($format)
52     {
53         return JsonEncoder::FORMAT === $format;
54     }
55
56     /**
57      * Merge default json encode options with context.
58      *
59      * @return array
60      */
61     private function resolveContext(array $context = array())
62     {
63         return array_merge(array('json_encode_options' => $this->options), $context);
64     }
65 }