You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PHP项目独立使用Symfony Validator验证文件时路径错误求助

问题描述

在PHP项目中独立使用Symfony Validator组件验证文件时,虽能返回文件格式错误等提示,但会抛出致命错误:

Fatal error: Uncaught Symfony\Component\PropertyAccess\Exception\InvalidPropertyPathException: The property path should not be empty.

相关代码如下:

function processFile()
{
    global $request;
    
    $file = $request->files->get('file');
    $validateFile = [
        'file' => new Assert\File([
            'maxSize' => '64M',
            'maxSizeMessage' => 'The file is too big',
            'mimeTypes' => ['pdf' => 'application/pdf'],
            'mimeTypesMessage' => 'The format is incorrect, only PDF allowed',
            'uploadNoFileErrorMessage' => 'No file was selected'
        ]),
    ];
       
    
    $validator = Validation::createValidator();
    $violations = $validator->validate($arrayData, $validateFile);
    if (0 !== count($violations)) {
        $errorMessages = getErrorMessage($violations);
    
        require_once(TEMPLATES . 'processFileForm.php');
        die();
    }
   

    /**
      * @param $violations
      * @return array
      */
    function getErrorMessage($violations): array
    {
        $accessor = PropertyAccess::createPropertyAccessor();
        $errorMessages = array();
        foreach ($violations as $violation) {
            $accessor->setValue($errorMessages, ($violation->getPropertyPath()), $violation->getMessage());
        
        }
        
        return $errorMessages;
    }
解决方案
  1. 修复未定义的$arrayData变量
    调用$validator->validate($arrayData, $validateFile)时,$arrayData未定义。需将获取到的文件包装成与验证约束键名匹配的数组:

    $arrayData = ['file' => $file];
    $violations = $validator->validate($arrayData, $validateFile);
    
  2. 处理空属性路径的异常
    触发uploadNoFileErrorMessage(未选择文件)时,可能返回空属性路径,导致PropertyAccess组件报错。需在getErrorMessage方法中先判断属性路径是否为空,再执行赋值:

    function getErrorMessage($violations): array
    {
        $accessor = PropertyAccess::createPropertyAccessor();
        $errorMessages = array();
        foreach ($violations as $violation) {
            $propertyPath = $violation->getPropertyPath();
            // 为空时指定默认键,可根据需求调整为'_global'等
            if (empty($propertyPath)) {
                $propertyPath = 'file';
            }
            $accessor->setValue($errorMessages, $propertyPath, $violation->getMessage());
        }
        
        return $errorMessages;
    }
    

内容的提问来源于stack exchange,提问作者Olga

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.28 12:03:38