Symfony 4,无法规范化DateTime类型的对象,找不到支持的规范化器

时间:2019-07-19 09:09:00

标签: symfony serialization symfony4

我试图规范化我的控制器的响应,并且除此控制器外,大多数控制器都可以工作,因为它具有DateTime对象。这是Touch类:

<?php

namespace App\Entity;

use DateTime;
use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Entity(repositoryClass="App\Repository\TouchRepository")
 */
class Touch implements \JsonSerializable
{
    /**
     * @ORM\Id()
     * @ORM\GeneratedValue()
     * @ORM\Column(type="integer")
     */
    private $id;

    /**
     * @ORM\Column(type="datetime")
     */
    private $time;

    /**
     * @ORM\Column(type="string", length=255)
     */
    private $toucher;

    private $accountId;

    /**
     * @ORM\ManyToOne(targetEntity="Cabinet")
     */
    private $cabinet;

    /**
     * Touch constructor.
     * @param DateTime $time
     * @param string $toucher
     * @param Cabinet $cabinet
     * @param int $id
     */
    public function __construct(DateTime $time, string $toucher, Cabinet $cabinet = null, int $id = null)
    {
        $this->time = $time;
        $this->toucher = $toucher;
        $this->cabinet = $cabinet;
        $this->id = $id;
    }

    public function getId(): int
    {
        return $this->id;
    }

    public function setId(int $id): self
    {
        $this->id = $id;

        return $this;
    }

    public function getTime(): DateTime
    {
        return $this->time;
    }

    public function getToucher(): string
    {
        return $this->toucher;
    }

    public function getCabinet(): Cabinet
    {
        return $this->cabinet;
    }

    public function setCabinet(Cabinet $cabinet): self
    {
        $this->cabinet = $cabinet;
        $this->accountId = $cabinet->getId();
        return $this;
    }

    public function getAccountId(): int
    {
        return $this->accountId;
    }

    public function setAccountId(int $accountId): self
    {
        $this->accountId = $accountId;

        return $this;
    }

    public function jsonSerialize()
    {
        return get_object_vars($this);
    }
}

我为此做了一个标准化器TouchNormalizer.php

<?php

namespace App\Normalizer;

use App\Entity\Touch;
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;

class TouchNormalizer implements NormalizerInterface
{

    /**
     * Normalizes an object into a set of arrays/scalars.
     *
     * @param Touch $object Object to normalize
     * @param string $format Format the normalization result will be encoded as
     * @param array $context Context options for the normalizer
     *
     * @return array|string|int|float|bool
     */

    public function normalize($object, $format = null, array $context = []): array
    {
        return [
            'id' => $object->getId(),
            'time' => $object->getTime(),
            'toucher' => $object->getToucher(),
            'cabinet' => $object->getCabinet(),
            'accountId' => $object->getAccountId()
        ];
    }


    /**
     * Checks whether the given class is supported for normalization by this normalizer.
     *
     * @param mixed $data Data to normalize
     * @param string $format The format being (de-)serialized from or into
     *
     * @return bool
     */
    public function supportsNormalization($data, $format = null)
    {
        return $data instanceof Touch && $format === 'json';
    }

}

然后在控制器TouchController中,我有这个:

<?php

namespace App\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Annotation\Route;
use App\Repository\TouchRepository;
use App\Entity\Bedroom;
use Symfony\Component\Serializer\Serializer;
use App\Http\SerializedJsonResponse;
use App\Normalizer\TouchNormalizer;
use Symfony\Component\Serializer\Encoder\JsonEncoder;

class TouchController extends AbstractController
{
    /**
     * @Route("/Bedroom/{bedroomId}/touchs", methods={"GET"})
     * @param \App\Controller\AuthenticationController $apiKeyAuthenticator
     * @param Request $request
     * @param Bedroom $bedroomId
     * @param TouchRepository $touchRepository
     * @return SerializedJsonResponse
     */
    public function AuthenticateAPI(AuthenticationController $apiKeyAuthenticator, Request $request, Bedroom $bedroomId, TouchRepository $touchRepository)
    {
        $AuthenticatorObject = $apiKeyAuthenticator->checkAuthentication($request);
        if (isset($AuthenticatorObject['success'])) {
            return new SerializedJsonResponse(new Serializer([new TouchNormalizer()], [new JsonEncoder()]), $touchRepository->findTouchsByAccount($bedroomId));
        }
        return new SerializedJsonResponse(new Serializer([new TouchNormalizer()], [new JsonEncoder()]), $AuthenticatorObject, 401);
    }
}

这将返回上述错误:

  

无法规范化DateTime类型的对象,找不到支持的规范化器。

我尝试通过将TouchNormalizer替换为DateTimeNormalizer来使用DateTimeNormalizer,但这会以奇数形式返回时间,即:

"time": "2019-06-12T09:51:22+00:00,"

代替原始

        "time": {
            "date": "2019-06-12 09:51:22.000000",
            "timezone_type": 3,
            "timezone": "UTC"
        },

如何保持原始的DateTime格式并正确规范化DateTime对象?

0 个答案:

没有答案