Debian Codegraph @

lib/3rdParty/composer/symfony/serializer/Encoder/JsonEncode.php

raw symbols SCIP
1 <?php
2
3 /*
4 * This file is part of the Symfony package.
5 *
6 * (c) Fabien Potencier <[email protected]>
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 <[email protected]>
20 */
21 class JsonEncode implements EncoderInterface
22 {
23 /**
24 * Configure the JSON flags bitmask.
25 */
26 public const OPTIONS = 'json_encode_options';
27
28 private array $defaultContext = [
29 self::OPTIONS => \JSON_PRESERVE_ZERO_FRACTION,
30 ];
31
32 public function __construct(array $defaultContext = [])
33 {
34 $this->defaultContext = array_merge($this->defaultContext, $defaultContext);
35 }
36
37 public function encode(mixed $data, string $format, array $context = []): string
38 {
39 $options = $context[self::OPTIONS] ?? $this->defaultContext[self::OPTIONS];
40
41 try {
42 $encodedJson = json_encode($data, $options);
43 } catch (\JsonException $e) {
44 throw new NotEncodableValueException($e->getMessage(), 0, $e);
45 }
46
47 if (\JSON_THROW_ON_ERROR & $options) {
48 return $encodedJson;
49 }
50
51 if (\JSON_ERROR_NONE !== json_last_error() && (false === $encodedJson || !($options & \JSON_PARTIAL_OUTPUT_ON_ERROR))) {
52 throw new NotEncodableValueException(json_last_error_msg());
53 }
54
55 return $encodedJson;
56 }
57
58 public function supportsEncoding(string $format): bool
59 {
60 return JsonEncoder::FORMAT === $format;
61 }
62 }