我需要帮助以注释形式编写正确的约束语法以验证对象数组

问题描述 投票:0回答:1

我正在使用Symfony5。在我的应用程序中,我有一个React应用程序,可将实体数据发布到服务器。然后在服务器端,我将数据json_decode到一个对象中,然后验证并将其持久保存到数据库中。我使用DTO对象而不是实体类来处理约束。编写约束以处理对象数组时出现问题。

我的数据对象结构

{
    id: 1,
    name: "john",
    images: [
      { id: 1,   img_name: "hello" },
      { id: 2,   img_name: "world" }
    ]
}

DTO文件

class PersonDTO {

    /**
     * @Assert\NotBlank
     * @Assert\Type("integer")
     */
    public $id    

    /**
     * @Assert\All({
     *     @Assert\Collection(
     *         fields = {
     *             "id" = @Assert\Type("integer")
     *         }
     */
    public $images
}

控制器

public function index(Request $request, ValidatorInterface $validator) 
{
    $jsonData = $request->getContent();
    $dataObject = json_decode($jsonData);

    $personDTO = new PersonDTO();
    $personDTO->id = $dataObject->id;
    $personDTO->images = $dataObject->images

    $errors = $validator->validate($personDTO);
}

我已经按照Symfony文档的说明处理对象数组,但是它不起作用。验证失败,消息为images

Object(App\DTO\PersonDTO).images[0]: This value should be of type array|(Traversable&ArrayAccess).阵列

我做错了什么?

php symfony validation constraints assert
1个回答
0
投票

好的,我发现了问题。 Symfony验证只能验证数组,而不能验证对象。因此,要验证对象数组,我需要将其转换为数组数组。

public function index(Request $request, ValidatorInterface $validator) 
{
    // converting from json string
    $dataArray = json_decode($json, true);

    // converting from object
    $dataArray = json_decode(json_encode(dataObject), true);
}

之后,只需将值传递给DTO对象以进行验证

$personDTO = new PersonDTO();
$personDTO->id= $dataArray['id']
$personDTO->images = $dataArray['images']

$errors = $validator->validate($personDTO);

最终,我将其设置为DTO类中的静态函数,以使控制器更整洁。

// PersonDTO class
public static function fromJson(string $json): self
    {
        $PersonDTO = new self();
        $dataArray = json_decode($json, true);

        $PersonDTO ->id = $dataArray['id'];
        $PersonDTO ->images = $dataArray['images'];        
        return $PersonDTO ;
    }

// controller
$personDTO = PersonDTO::fromJson($jsonData);
$errors = $validator->validate($PersonDTO );
© www.soinside.com 2019 - 2024. All rights reserved.