Security update for Core, with self-updated composer
[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\UnexpectedValueException;
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     private $lastError = JSON_ERROR_NONE;
25
26     public function __construct($bitmask = 0)
27     {
28         $this->options = $bitmask;
29     }
30
31     /**
32      * Encodes PHP data to a JSON string.
33      *
34      * {@inheritdoc}
35      */
36     public function encode($data, $format, array $context = array())
37     {
38         $context = $this->resolveContext($context);
39
40         $encodedJson = json_encode($data, $context['json_encode_options']);
41
42         if (JSON_ERROR_NONE !== $this->lastError = json_last_error()) {
43             throw new UnexpectedValueException(json_last_error_msg());
44         }
45
46         return $encodedJson;
47     }
48
49     /**
50      * {@inheritdoc}
51      */
52     public function supportsEncoding($format)
53     {
54         return JsonEncoder::FORMAT === $format;
55     }
56
57     /**
58      * Merge default json encode options with context.
59      *
60      * @param array $context
61      *
62      * @return array
63      */
64     private function resolveContext(array $context = array())
65     {
66         return array_merge(array('json_encode_options' => $this->options), $context);
67     }
68 }