Fixed SymfonySerializer not support scalar.

This commit is contained in:
李铭昕 2019-08-04 13:21:57 +08:00
parent e202a2eedc
commit fbdcd35c82
4 changed files with 74 additions and 1 deletions

View File

@ -25,7 +25,9 @@
"friendsofphp/php-cs-fixer": "^2.9"
},
"suggest": {
"symfony/var-dumper": "Required to use the dd function (^4.1)."
"symfony/var-dumper": "Required to use the dd function (^4.1).",
"symfony/serializer": "Required to use SymfonyNormalizer (^4.3)",
"symfony/property-access": "Required to use SymfonyNormalizer (^4.3)"
},
"autoload": {
"files": [

View File

@ -0,0 +1,61 @@
<?php
declare(strict_types=1);
/**
* This file is part of Hyperf.
*
* @link https://www.hyperf.io
* @document https://doc.hyperf.io
* @contact group@hyperf.io
* @license https://github.com/hyperf-cloud/hyperf/blob/master/LICENSE
*/
namespace Hyperf\Utils\Serializer;
use Symfony\Component\Serializer\Normalizer\CacheableSupportsMethodInterface;
use Symfony\Component\Serializer\Normalizer\DenormalizerInterface;
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;
class ScalarNormalizer implements NormalizerInterface, DenormalizerInterface, CacheableSupportsMethodInterface
{
public function hasCacheableSupportsMethod(): bool
{
return \get_class($this) === __CLASS__;
}
public function denormalize($data, $class, $format = null, array $context = [])
{
switch ($class) {
case 'int':
return (int) $data;
case 'string':
return (string) $data;
case 'float':
return (float) $data;
case 'bool':
return (bool) $data;
default:
return $data;
}
}
public function supportsDenormalization($data, $type, $format = null)
{
return in_array($type, [
'int',
'string',
'float',
'bool',
]);
}
public function normalize($object, $format = null, array $context = [])
{
return $object;
}
public function supportsNormalization($data, $format = null)
{
return is_scalar($data);
}
}

View File

@ -24,6 +24,7 @@ class SerializerFactory
new ExceptionNormalizer(),
new ObjectNormalizer(),
new ArrayDenormalizer(),
new ScalarNormalizer(),
]);
}
}

View File

@ -33,6 +33,9 @@ class SymfonySerializerTest extends TestCase
'int' => 10,
'string' => null,
]], $ret);
$ret = $serializer->normalize([1, '2']);
$this->assertEquals([1, '2'], $ret);
}
public function testDenormalize()
@ -44,6 +47,12 @@ class SymfonySerializerTest extends TestCase
]], Foo::class . '[]');
$this->assertInstanceOf(Foo::class, $ret[0]);
$this->assertEquals(10, $ret[0]->int);
$ret = $serializer->denormalize('1', 'int');
$this->assertSame(1, $ret);
$ret = $serializer->denormalize(['1', 2, '03'], 'int[]');
$this->assertSame([1, 2, 3], $ret);
}
public function testException()