Skip to content
Advertisement

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

I’m trying to create a custom normalizer, but I cannot access to my current user using API Platform.

When I try to load my Client class, this is empty. I tried to method using the API Platform’s documentation, but the retreived token is empty too.

Do you have any tip to get my current user ? Thanks

<?php

namespace AppSerializer;

use AppEntityStock;
use SymfonyComponentRoutingGeneratorUrlGeneratorInterface;
use SymfonyComponentSecurityCoreAuthenticationTokenStorageTokenStorageInterface;
use SymfonyComponentSerializerNormalizerContextAwareNormalizerInterface;
use SymfonyComponentSerializerNormalizerObjectNormalizer;

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;
}
}

Advertisement

Answer

Have you tried to inject TokenInterface on your class ?

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

Then you can use $token->getUser() to retrieve your current user.

if you don’t have a user then you don’t use your API with authentication. See https://api-platform.com/docs/core/jwt/

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement