我用api- User创建了一个经典的平台类,我希望我的GET /users/{id}端点具有不同的行为,这取决于经过身份验证的用户是否等于{id}用户。
如果我是同一个用户(显示电子邮件)
{
"@context": "/contexts/User",
"@id": "/users/1",
"@type": "User",
"email": "peter@test.com",
"username": "peter"
}如果不是(隐藏电子邮件)
{
"@context": "/contexts/User",
"@id": "/users/1",
"@type": "User",
"username": "peter"
}我尝试在电子邮件字段中添加自定义组,就像我可以在此处阅读https://api-platform.com/docs/core/serialization/#changing-the-serialization-context-dynamically一样
但是我不知道如何在SerializerContextBuilderInterface中检索user对象的信息
/**
* @ORM\Column(type="string", length=180, unique=true)
* @Groups({"owner:read", "user:write"})
* @Assert\NotBlank()
* @Assert\Email()
*/
private $email;发布于 2020-07-06 23:44:13
在实现SerializerContextBuilderInterface的类中,可以通过将TokenStorageInterface $tokenStorage传递给构造函数来检索当前用户。和对象请求(序列化所需的),可以使用$user:$this->userRepository->find($request->get('id'));获取,示例如下:
public function createFromRequest(Request $request, bool $normalization, array $extractedAttributes = null) : array
{
$context = $this->decorated->createFromRequest($request, $normalization, $extractedAttributes);
$route = $request->get('_route');
if ($route === 'api_users_get_item') {
$currentUser = $this->token->getToken()->getUser();
$userToSerialize = $this->userRepository->find($request->get('id'));
if ($currentUser->getId() === $userToSerialize->getId()) {
$context['groups'][] = 'owner:read';
}
}
return $context;
}https://stackoverflow.com/questions/62678357
复制相似问题