8000 [Serializer] Add options to JsonDecode and JsonEncode to wrap/unwrap json data by nonanerz · Pull Request #28887 · symfony/symfony · GitHub
[go: up one dir, main page]

Skip to content

[Serializer] Add options to JsonDecode and JsonEncode to wrap/unwrap json data #28887

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 6 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions src/Symfony/Bridge/Doctrine/ContainerAwareEventManager.php
Original file line number Diff line number Diff line change
Expand Up @@ -41,8 +41,8 @@ public function __construct(ContainerInterface $container)
*
* @param string $eventName The name of the event to dispatch. The name of the event is
* the name of the method that is invoked on listeners.
* @param EventArgs $eventArgs The event arguments to pass to the event handlers/listeners.
* If not supplied, the single empty EventArgs instance is used.
* @param EventArgs $eventArgs the event arguments to pass to the event handlers/listeners.
* If not supplied, the single empty EventArgs instance is used
*
* @return bool
*/
Expand Down
18 changes: 17 additions & 1 deletion src/Symfony/Component/Serializer/Encoder/JsonDecode.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@

namespace Symfony\Component\Serializer\Encoder;

use Symfony\Component\PropertyAccess\PropertyAccess;
use Symfony\Component\Serializer\Exception\NotEncodableValueException;

/**
Expand All @@ -21,6 +22,7 @@
class JsonDecode implements DecoderInterface
{
protected $serializer;
private $propertyAccessor;

/**
* True to return the result as an associative array, false for a nested stdClass hierarchy.
Expand All @@ -38,6 +40,7 @@ class JsonDecode implements DecoderInterface
self::ASSOCIATIVE => false,
self::OPTIONS => 0,
self::RECURSION_DEPTH => 512,
JsonEncoder::JSON_PROPERTY_PATH => null,
];

/**
Expand All @@ -57,14 +60,15 @@ public function __construct($defaultContext = [], int $depth = 512)
}

$this->defaultContext = array_merge($this->defaultContext, $defaultContext);
$this->propertyAccessor = PropertyAccess::createPropertyAccessor();
}

/**
* Decodes data.
*
* @param string $data The encoded JSON string to decode
* @param string $format Must be set to JsonEncoder::FORMAT
* @param array $context An optional set of options for the JSON decoder; see below
* @param array $context an optional set of options for the JSON decoder; see below
*
* The $context array is a simple key=>value array, with the following supported keys:
*
Expand All @@ -80,6 +84,9 @@ public function __construct($defaultContext = [], int $depth = 512)
* json_decode_options: integer
* Specifies additional options as per documentation for json_decode
*
* JSON_PROPERTY_PATH: string
* Specifies property path and allow to unwrap data
*
* @return mixed
*
* @throws NotEncodableValueException
Expand All @@ -91,13 +98,22 @@ public function decode($data, $format, array $context = [])
$associative = $context[self::ASSOCIATIVE] ?? $this->defaultContext[self::ASSOCIATIVE];
$recursionDepth = $context[self::RECURSION_DEPTH] ?? $this->defaultContext[self::RECURSION_DEPTH];
$options = $context[self::OPTIONS] ?? $this->defaultContext[self::OPTIONS];
$propertyPath = $context[JsonEncoder::JSON_PROPERTY_PATH] ?? $this->defaultContext[JsonEncoder::JSON_PROPERTY_PATH];

$decodedData = json_decode($data, $associative, $recursionDepth, $options);

if (JSON_ERROR_NONE !== json_last_error()) {
throw new NotEncodableValueException(json_last_error_msg());
}

if ($propertyPath) {
if ($this->propertyAccessor->isReadable($decodedData, $propertyPath)) {
$decodedData = $this->propertyAccessor->getValue($decodedData, $propertyPath);
} else {
$decodedData = null;
}
}

return $decodedData;
}

Expand Down
26 changes: 26 additions & 0 deletions src/Symfony/Component/Serializer/Encoder/JsonEncode.php
< 10000 td id="diff-a42770d6f72c3f6f04a8245df02252745f16042b73a55103fdc4a22e0558f341R15" data-line-number="15" class="blob-num blob-num-context js-linkable-line-number js-blob-rnum">
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@

namespace Symfony\Component\Serializer\Encoder;

use Symfony\Component\PropertyAccess\PropertyAccess;
use Symfony\Component\Serializer\Exception\NotEncodableValueException;

/**
Expand All @@ -22,15 +23,18 @@ class JsonEncode implements EncoderInterface
{
const OPTIONS = 'json_encode_options';

private $propertyAccessor;
private $defaultContext = [
self::OPTIONS => 0,
JsonEncoder::JSON_PROPERTY_PATH => null,
];

/**
* @param array $defaultContext
*/
public function __construct($defaultContext = [])
{
$this->propertyAccessor = PropertyAccess::createPropertyAccessor();
if (!\is_array($defaultContext)) {
@trigger_error(sprintf('Passing an integer as first parameter of the "%s()" method is deprecated since Symfony 4.2, use the "json_encode_options" key of the context instead.', __METHOD__), E_USER_DEPRECATED);

Expand All @@ -48,6 +52,12 @@ public function __construct($defaultContext = [])
public function encode($data, $format, array $context = [])
{
$jsonEncodeOptions = $context[self::OPTIONS] ?? $this->defaultContext[self::OPTIONS];
$propertyPath = $context[JsonEncoder::JSON_PROPERTY_PATH] ?? $this->defaultContext[JsonEncoder::JSON_PROPERTY_PATH];

if ($propertyPath) {
$data = $this->wrapEncodableData($propertyPath, $data);
}

$encodedJson = json_encode($data, $jsonEncodeOptions);

if (JSON_ERROR_NONE !== json_last_error() && (false === $encodedJson || !($jsonEncodeOptions & JSON_PARTIAL_OUTPUT_ON_ERROR))) {
Expand All @@ -57,6 +67,22 @@ public function encode($data, $format, array $context = [])
return $encodedJson;
}

/**
* Wrap data before encoding.
*
* @param string $propertyPath
* @param mixed $data
*
* @return array
*/
private function wrapEncodableData($propertyPath, $data)
{
$wrappedData = [];
$this->propertyAccessor->setValue($wrappedData, $propertyPath, $data);

return $wrappedData;
}

/**
* {@inheritdoc}
*/
Expand Down
3 changes: 2 additions & 1 deletion src/Symfony/Component/Serializer/Encoder/JsonEncoder.php
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,8 @@
*/
class JsonEncoder implements EncoderInterface, DecoderInterface
{
const FORMAT = 'json';
public const FORMAT = 'json';
public const JSON_PROPERTY_PATH = 'json_property_path';

protected $encodingImpl;
protected $decodingImpl;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,11 @@ public function decodeProvider()
return [
['{"foo": "bar"}', $stdClass, []],
['{"foo": "bar"}', $assoc, ['json_decode_associative' => true]],
['{"baz": {"foo": "bar"}}', $stdClass, [JsonEncoder::JSON_PROPERTY_PATH => 'baz']],
['{"baz": {"foo": "bar"}}', null, [JsonEncoder::JSON_PROPERTY_PATH => 'baz.inner']],
['{"baz": {"foo": "bar"}}', $assoc, [JsonEncoder::JSON_PROPERTY_PATH => '[baz]', 'json_decode_associative' => true]],
['{"baz": {"foo": "bar"}}', $assoc, [JsonEncoder::JSON_PROPERTY_PATH => '[baz]', 'json_decode_associative' => true]],
['{"baz": {"foo": "bar", "inner": {"key": "value"}}}', ['key' => 'value'], [JsonEncoder::JSON_PROPERTY_PATH => '[baz][inner]', 'json_decode_associative' => true]],
];
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ public function encodeProvider()
return [
[[], '[]', []],
[[], '{}', ['json_encode_options' => JSON_FORCE_OBJECT]],
[['bar' => 'foo'], '{"baz":{"bar":"foo"}}', [JsonEncoder::JSON_PROPERTY_PATH => '[baz]']],
];
}

Expand Down
0