Files
archived-FOSRestBundle/Decoder/JsonToFormDecoder.php
Christian Flothmann e287a8e97b Merge branch '2.x'
* 2.x:
  do not iterate non-array data
2020-03-27 16:42:53 +01:00

56 lines
1.7 KiB
PHP

<?php
/*
* This file is part of the FOSRestBundle package.
*
* (c) FriendsOfSymfony <http://friendsofsymfony.github.com/>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace FOS\RestBundle\Decoder;
/**
* Decodes JSON data and make it compliant with application/x-www-form-encoded style.
*
* @author Kévin Dunglas <dunglas@gmail.com>
*/
final class JsonToFormDecoder implements DecoderInterface
{
/**
* Makes data decoded from JSON application/x-www-form-encoded compliant.
*/
private function xWwwFormEncodedLike(array &$data): void
{
foreach ($data as $key => &$value) {
if (is_array($value)) {
// Encode recursively
$this->xWwwFormEncodedLike($value);
} elseif (false === $value) {
// Checkbox-like behavior removes false data but PATCH HTTP method with just checkboxes does not work
// To fix this issue we prefer transform false data to null
// See https://github.com/FriendsOfSymfony/FOSRestBundle/pull/883
$value = null;
} elseif (!is_string($value)) {
// Convert everything to string
// true values will be converted to '1', this is the default checkbox behavior
$value = strval($value);
}
}
}
/**
* {@inheritdoc}
*/
public function decode(string $data)
{
$decodedData = @json_decode($data, true);
if (is_array($decodedData)) {
$this->xWwwFormEncodedLike($decodedData);
}
return $decodedData;
}
}