我如何将客户端数据访问到自定义 Normalizer (Symfony 4)

How can i access Client data into custom Normalizer (Symfony 4)

我正在尝试创建自定义规范化器,但我无法使用 API 平台访问我的当前用户。

当我尝试加载我的客户端 class 时,这是空的。我尝试使用 API 平台的文档进行处理,但检索到的令牌也是空的。

你有什么技巧可以吸引我的当前用户吗?谢谢

<?php

namespace App\Serializer;

use App\Entity\Stock;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use Symfony\Component\Serializer\Normalizer\ContextAwareNormalizerInterface;
use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;

class StockAttributeNormalizer implements ContextAwareNormalizerInterface
{
    private $router;
    private $normalizer;

    public function __construct(UrlGeneratorInterface $router, ObjectNormalizer $normalizer)
    {
        $this->router = $router;
        $this->normalizer = $normalizer;
    }

public function normalize($topic, $format = null, array $context = [])
{
    $data = $this->normalizer->normalize($topic, $format, $context);

    var_dump($data);

    return $data;
}

public function supportsNormalization($data, $format = null, array $context = [])
{
    return $data instanceof Stock;
}
}

你试过在你的 class 上注入 TokenInterface 吗?

public function __construct(UrlGeneratorInterface $router, ObjectNormalizer $normalizer, TokenInterface $token)
    {
        $this->router = $router;
        $this->normalizer = $normalizer;
        $this->token = $token;
    }

然后您可以使用$token->getUser()检索您当前的用户。

如果您没有用户,那么您就不会使用 API 进行身份验证。参见 https://api-platform.com/docs/core/jwt/