如何解决Symfony API-Platform Assert\Choice 在 setter
我的应用有一个非常标准的用户评论功能,任何访问者都可以将评论标记为不当。
在这些标记评论的解决过程中,管理员将决定采取哪些行动,在不采取行动、编辑评论或删除评论之间。
CommentReport 实体包括 Assert\Choice 以仅允许上述 3 个选择。
问题在于它接受任何字符串。
在 Comment 实体上的设置如下:
....
* graphql={
* "withCustomArgsMutation"={
* "security"="is_granted('ROLE_ADMIN')",* "mutation"=CommentReputationTypeResolver::class,* "args"={
* "id"={"type"="ID!"},* "resolutionType"={"type"="String!"},* },* "denormalization_context"={"groups"={"put-resolution"}},* "normalization_context"={"groups"={"get"}}
* },.....
/**
* @ORM\OneToMany(targetEntity=CommentReport::class,mappedBy="comment")
* @Groups({"get","get-admin","get-owner","put-resolution"})
*/
private $commentReports;
然后是 CommentReports 实体:
class CommentReport
{
const RESOLUTION_TYPES = [
'no_action','edit','remove',];
.....
/**
* @ORM\Column(type="string",length=10,nullable=true)
* @Assert\NotBlank(
* message="commentReport.resolutionType.notBlank",* groups={"put-resolution"}
* )
* @Assert\Choice(
* choices=CommentReport::RESOLUTION_TYPES,* message="commentReport.resolutionType.choice",* groups={"put-resolution"}
* )
* @Groups({"get-admin","put-resolution"})
*/
private $resolutionType;
然后在 DeserializeStage 上拦截请求以处理为该评论制作的每个单独的 CommentReport 的设置:
/Stage/DeserializeStage.php
if ($this->isAdmin($user) && $resourceClass === 'App\Entity\Comment' && $operationName === 'withCustomArgsMutation') {
// get all comment reports
$commentReports = $deserializeObject->getCommentReports();
foreach($commentReports as $report) {
$report->setResolutionType($context['args']['input']['resolutionType']);
}
}
所有这些都有效,但我可以输入任何字符串,它会被接受。 当然,预期的结果是 Symfony 会为任何不在 RESOLUTION_TYPES 数组中的字符串抛出异常。
有关信息,这是触发输入的前端突变:
`mutation putCommentReport(
$commentId: ID!
$resolutionType: String!
) {
withCustomArgsMutationComment(input: {
id: $commentId
resolutionType: $resolutionType
}){
comment{
id
}
}
}`;
解决方法
正如@Jeroen van der Laan 指出的,操作中缺少验证组注释,应该如下;
应用\实体\评论
* graphql={
* "withCustomArgsMutation"={
* "security"="is_granted('ROLE_ADMIN')",* "mutation"=CommentReputationTypeResolver::class,* "args"={
* "id"={"type"="ID!"},* "resolutionType"={"type"="String!"},* },* "normalization_context"={"groups"={"get"}},* "validation_groups"={"put-resolution"}
* },
另外,需要在 Comment 上的 CommentReport 关系中添加 Valid() 断言:
/**
* @ORM\OneToMany(targetEntity=CommentReport::class,mappedBy="comment")
* @Assert\Valid()
* @Groups({"get","get-admin","get-owner"})
*/
private $commentReports;
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。