【问题标题】:I need help writing the right constraint syntax in annotation form for validating array of objects我需要帮助以注释形式编写正确的约束语法以验证对象数组
【发布时间】:2019-12-22 08:03:30
【问题描述】:

我正在使用 Symfony 5。在我的应用程序中,我有一个将实体数据发布到服务器的反应应用程序。然后在服务器端,我会将数据 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】:

    好的,我发现了问题。 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 );
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-03-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多