首页 > 解决方案 > API 平台 Symfony,在使用 sarbacane 发送短信时无法验证布尔类型的值

问题描述

我创建了一个自定义操作来使用 symfony 和 sarbacane 发送短信:

在我的AppUser实体中,我添加了注释:

 *          "GET",
 *          "PUT",
 *          "PATCH",
 *          "DELETE",
 *          "send_sms"={
 *              "method"="POST",
 *              "path"="/app_users/{id}/sms",
 *              "controller"=SmsController::class,
 *              "normalization_context"={"groups"={"user:read"}},
 *              "put"={"validation_groups"={"Default", "sedValidation"}}
 *          }
 *    }

在我的控制器中,我实现了调用方法:

public function __invoke(AppUser $user, Request $request, SerializerInterface $serializer) : bool
{

    $data = $request->getContent();
    // json decode transforms to object by default
    // add true
    $json_encode = json_decode($data, true);

    $content = $json_encode['content'];

    $currentUser = $this->getUser();

    $currentUserPhone = $currentUser->getPhone();

    $res = $this->sarbacaneApiHelper->call('campaigns/sms', [
        'name' => sprintf("eXpanded n°%s", uniqid()),
        'kind' => 'SMS_NOTIFICATION',
        'smsFrom' => "eXpanded", // entre 3 et 11 caractères alpha-numériques
        'content' => $content, // max 450 caractères
    ]);

    $phone = $currentUserPhone;

    $sarbacaneCampaignId = $res->id;

    // Ajoute des destinataires à la campagne Sarbacane
    $res = $this->sarbacaneApiHelper->call(sprintf('campaigns/%s/recipients', $sarbacaneCampaignId), [
        [
            'phone' => $phone,
        ],
    ]);

    $params = [
        "phone" => $currentUserPhone,
    ];

    $this->sarbacaneApiHelper->call(sprintf('campaigns/%s/send', $sarbacaneCampaignId), $params);

    $sent = true;


    return $sent;
}

我使用邮递员测试了 api,我得到了 500 内部服务器错误:

"hydra:description": "无法自动验证 "boolean" 类型的值。请提供约束。"

在此处输入图像描述

标签: symfonyapi-platform.com

解决方案


为什么会出现此错误消息?

invoke()方法必须返回:

  • 一个Symfony\Component\HttpFoundation\ResponseResponse实例,
  • 目标实体的一个实例(似乎AppUser在这种情况下)。

在您的情况下,该方法返回true; 由于验证是在控制器之后进行的,Api-Platform 尝试验证这个布尔值,这是不可能的。它需要一个实体。

关于问题中显示的代码

我仍然不清楚您要达到的目标:

  • 为什么$user从不使用 arg?
  • 发送电子邮件后,您想保存任何实体吗?
  • 为什么要获取Request内容?

推荐阅读