I have a User entity in API Platform and created a custom operation to return information about the currently logged-in user, using a state provider.
ApiResource tag:
#[ApiResource(
operations: [
new Get(
uriTemplate: '/user',
normalizationContext: ['groups' => ['user:read']],
security: self::SECURITY_GET,
provider: UserStateProvider::class
)
]
UserStateProvider:
class UserStateProvider implements ProviderInterface
{
public function __construct(
private readonly Security $security,
) {}
public function provide(Operation $operation, array $uriVariables = [], array $context = []): object|array|null
{
return $this->security->getUser();
}
}
The problem: This endpoint returns an IRI without an ID, which looks like this:
"@context": "/api/contexts/User",
"@id": "/api/user",
"@type": "User",
I attempted to fetch the user from the repository within UserStateProvider, but it did not resolve the issue:
$user = $this->security->getUser();
return $user ? $this->userRepository->find($user->getId()) : null;