Yaffs site version 1.1
[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      * Returns the last encoding error (if any).
33      *
34      * @return int
35      *
36      * @deprecated since version 2.5, to be removed in 3.0.
37      *             The {@self encode()} throws an exception if error found.
38      * @see http://php.net/manual/en/function.json-last-error.php json_last_error
39      */
40     public function getLastError()
41     {
42         @trigger_error('The '.__METHOD__.' method is deprecated since version 2.5 and will be removed in 3.0. Catch the exception raised by the encode() method instead to get the last JSON encoding error.', E_USER_DEPRECATED);
43
44         return $this->lastError;
45     }
46
47     /**
48      * Encodes PHP data to a JSON string.
49      *
50      * {@inheritdoc}
51      */
52     public function encode($data, $format, array $context = array())
53     {
54         $context = $this->resolveContext($context);
55
56         $encodedJson = json_encode($data, $context['json_encode_options']);
57
58         if (JSON_ERROR_NONE !== $this->lastError = json_last_error()) {
59             throw new UnexpectedValueException(json_last_error_msg());
60         }
61
62         return $encodedJson;
63     }
64
65     /**
66      * {@inheritdoc}
67      */
68     public function supportsEncoding($format)
69     {
70         return JsonEncoder::FORMAT === $format;
71     }
72
73     /**
74      * Merge default json encode options with context.
75      *
76      * @param array $context
77      *
78      * @return array
79      */
80     private function resolveContext(array $context = array())
81     {
82         return array_merge(array('json_encode_options' => $this->options), $context);
83     }
84 }