gpt4 book ai didi

php - Symfony 4 自定义反序列化器返回实体中的空属性

转载 作者:行者123 更新时间:2023-12-05 07:17:42 25 4
gpt4 key购买 nike

我有一个自定义的 Symfony 4 解串器

class CardImageDecoder implements EncoderInterface, DecoderInterface
{
public function encode($data, $format, array $context = [])
{
if($format !== 'json') {
throw new EncodingFormatNotSupportedException(sprintf('Format %s is not supported by encoder %s', $format, __CLASS__));
}

$result = json_encode($data);

if(json_last_error() !== JSON_ERROR_NONE) {
// don't bother with a custom error message
throw new \Exception(sprintf('Unable to encode data, got error message: %s', json_last_error_msg()));
}

return $result;
}

public function supportsEncoding($format)
{
return 'json' === $format;
}

public function decode($data, $format, array $context = [])
{
if($format !== 'array') {
throw new DecodingFormatNotSupportedException(sprintf('Format %s is not supported by encoder %s', $format, __CLASS__));
}

if(!is_array($data)) {
throw new \UnexpectedValueException(sprintf('Expected array got %s', gettype($data)));
}

$cardInstance = new CardImages();
$cardInstance->setHeight($data['h'] ?? 0);
$cardInstance->setPath($data['url'] ?? '');
$cardInstance->setWidth($data['w'] ?? 0);

return $cardInstance;
}

public function supportsDecoding($format)
{
return 'array' === $format;
}
}

我反序列化的方式非常简单:

$json = '
{
"url": "some url",
"h": 1004,
"w": 768
}';

$encoders = [new CardImageDecoder()];
$normalizers = [new ObjectNormalizer()];
$serializer = new Serializer($normalizers, $encoders);

$cardImage = $serializer->deserialize(json_decode($json, true), CardImages::class, 'array');

/** @var $cardImage CardImages */
var_dump($cardImage);

但是,我得到了返回的结果:

object(App\Entity\CardImages)#158 (5) {
["id":"App\Entity\CardImages":private]=>
NULL
["path":"App\Entity\CardImages":private]=>
NULL
["height":"App\Entity\CardImages":private]=>
NULL
["width":"App\Entity\CardImages":private]=>
NULL
["movie":"App\Entity\CardImages":private]=>
NULL
}

现在,如果我要进行转储,就在解码器的 decode 部分返回之前,我会得到这个:

...
$cardInstance->setWidth($data['w'] ?? 0);

var_dump($cardInstance);

object(App\Entity\CardImages)#153 (5) {
["id":"App\Entity\CardImages":private]=>
NULL
["path":"App\Entity\CardImages":private]=>
string(8) "some url"
["height":"App\Entity\CardImages":private]=>
int(1004)
["width":"App\Entity\CardImages":private]=>
int(768)
["movie":"App\Entity\CardImages":private]=>
NULL
}

忽略未设置的属性(我很满意),它应该工作得很好,但事实并非如此。

对于我的生活,我无法弄清楚出了什么问题。

感谢任何帮助。

最佳答案

你想的太复杂了。

测试,工作示例:
您的实体 - 仔细看看最后 - 我们需要带有您的数组键名称的 setter :

namespace App\Domain;


class CardImages
{
/** @var int|null */
private $id;
/** @var int|null */
private $height;
/** @var string|null */
private $path;
/** @var int|null */
private $width;
/** @var mixed */
private $movie;

/**
* @return int|null
*/
public function getId(): ?int
{
return $this->id;
}

/**
* @param int|null $id
* @return CardImages
*/
public function setId(?int $id): CardImages
{
$this->id = $id;
return $this;
}

/**
* @return int|null
*/
public function getHeight(): ?int
{
return $this->height;
}

/**
* @param int|null $height
* @return CardImages
*/
public function setHeight(?int $height): CardImages
{
$this->height = $height;
return $this;
}

/**
* @return string|null
*/
public function getPath(): ?string
{
return $this->path;
}

/**
* @param string|null $path
* @return CardImages
*/
public function setPath(?string $path): CardImages
{
$this->path = $path;
return $this;
}

/**
* @return int|null
*/
public function getWidth(): ?int
{
return $this->width;
}

/**
* @param int|null $width
* @return CardImages
*/
public function setWidth(?int $width): CardImages
{
$this->width = $width;
return $this;
}

/**
* @return mixed
*/
public function getMovie()
{
return $this->movie;
}

/**
* @param mixed $movie
* @return CardImages
*/
public function setMovie($movie)
{
$this->movie = $movie;
return $this;
}

public function setH(?int $height): CardImages
{
$this->setHeight($height);

return $this;
}

public function setUrl(?string $url): CardImages
{
$this->setPath($url);
return $this;
}

public function setW(?int $width): CardImages
{
$this->setWidth($width);

return $this;
}
}

用于测试输出的简单 Controller :

<?php       
namespace App\Infrastructure\Web\Controller;

use App\Domain\CardImages;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
use Symfony\Component\Serializer\SerializerInterface;

/**
* Class IndexController.
*
* @Route("/test")
*/
class TestController extends AbstractController
{
private $serializer;

public function __construct(SerializerInterface $serializer)
{
$this->serializer = $serializer;
}

/**
* @Route("")
*
* @return Response
*/
public function indexAction(): Response
{
$data = [
[
'h' => 100,
'w' => 100,
'path' => '/asdf/asdf.png',
],
[
'h' => 50,
'w' => 150,
'path' => '/asdf/foo.png',
],
[
'h' => 100,
'w' => 200,
'path' => '/asdf/bar.png',
],
[
'h' => 300,
'w' => 400,
'path' => '/asdf/baz.png',
],

];

foreach ($data as $row) {
$cardImage = $this->serializer->denormalize($row, CardImages::class, null, [
ObjectNormalizer::DISABLE_TYPE_ENFORCEMENT => false
]);

$json = $this->serializer->serialize($cardImage, 'json');

dump($cardImage, $json);
}

return new Response('<html><head></head></html></body></html>');

}
}

输出: enter image description here

关于php - Symfony 4 自定义反序列化器返回实体中的空属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58651228/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com