Symfony NotBlank constraint allow blank string

荒凉一梦 提交于 2020-12-13 03:20:29

问题


I'm working with Symfony5 and ApiPlatform with phpunit for the tests

I'm running tests on field validation.

My issue comes from the fact that I want to restrain the user's possiblity to enter a blank string in a property named name as follow :

/**
 * @ApiResource(
 *     attributes={
 *          "normalization_context"={"groups"={"cons:read", "cons:list"}},
 *          "denormalization_context"={"groups"={"cons:write"}}
 *     },
 *     collectionOperations={
 *          "get"={
 *              "mehtod"="GET",
 *              "normalization_context"={"groups"={"cons:list"}},
 *          },
 *          "post"={
 *              "method"="POST"
 *              "normalizationContext"={"groups"={"cons:write"}},
 *              "validationGroups"={"create"}
 *          }
 *     }
 * )
 * @ORM\Entity(repositoryClass=ConsultationTypeRepository::class)
 */
class ClassName
{
    /**
     * @ORM\Id
     * @ORM\GeneratedValue
     * @ORM\Column(type="integer")
     * @Groups({"cons:read", "cons:list", "some:read", "thing:read"})
     */
    private $id;

    /**
     * @ORM\Column(type="string", length=255, nullable=false)
     * @Groups({"cons:read", "cons:write", "cons:list", "some:read", "thing:read", "availability:read"})
     * @Assert\NotBlank (
     *     groups={"create"},
     *     message="Le nom ne peut pas être vide."
     * )
     * @Assert\Length(
     *     max = 255,
     *     maxMessage = "Le nom ne peut pas excéder 255 charactères",
     *     allowEmptyString = false
     * )
     * @Assert\Regex(
     *     pattern="/\d/",
     *     match=false,
     *     message="Le nom ne peut pas contenir de nombre"
     * )
     */
    private $name;

Here is my test :

public function testRoleAdminCanNotPostConsultationWithBlankName(): void
    {
        $body = '{ "name": ""}';
        $res = $this->buildPostPutRequest(
            Actions::POST,
            self::TYPE_CONSULTATION_ROUTE,
            $body,
            self::ADMIN_CREDENTIALS
        );
        $this->assertResponseStatusCodeSame(400);
    }

Now I receive a 201 instead of the expected 400.

While other tests concerning the regex or the length of the string return 400 as expected.

I don't understand why the NotBlank() seem to not trigger on this test.

Any idea ?


回答1:


I think this is because you've declared your post operations attributes using camel case instead of snake case. Camel case must be used at the top-level of the ApiResource annotation only.

Currently, you've only declared the method of your operation. This is useless here.

  • normalizationContext => normalization_context
  • validationGroups => validation_groups

Also you've declared a mehtod property instead of method within you GET operation.



来源:https://stackoverflow.com/questions/64804334/symfony-notblank-constraint-allow-blank-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!