根据配置文件中的值验证文件大小约束

validation File size constraint from value in configuration file

我正在使用默认断言文件:

/**
     * @Assert\NotBlank()
     * @Assert\File(
     *  mimeTypes={
     *          "application/pdf",
     *          "image/jpeg",
     *          "image/pjpeg",
     *          
     *  },
     *  mimeTypesMessage="The file format is not correct",
     *  maxSize="1M",
     * )

     * @var File $file
     */
    private $file;

我验证文件大小是否小于 1M。但是如果我想在配置文件中创建一个配置,比如:

//yml file
max_size_file : 1

并在断言中使用该值。

我知道需要创建自定义验证作为服务并注入容器以从参数或配置文件中获取配置值。它看起来像:

/**
  *
  *@Assert\myConstraint()
  */
private $file 

请帮忙。

提前致谢。

解决方法如下:

首先让我们在参数文件中设置一个配置值:

//parameters.yml

max_file_size_upload: 2 // the unit is MEGABYTE

the unit value is MB , so check the factorizeSize methd in FileSizeValidator if you wanna custom your own logic

为了实现自定义验证器,symfony 为您提供了为约束创建一个 class 和另一个用于约束验证的方法,因此让我们首先创建约束 class:

<?php

namespace Acme\AppBundleBundle\Service\Validation;


use Symfony\Component\Validator\Constraint;

    /**
     * the Max file size upload constraint
     *
     * @Annotation
     * Class FileSize
     * @package Acme\AppBundle\Service\Validation

     */
    class FileSize extends Constraint
    {
        /**
         * @var string the message error if the file {{size}} uploaded is greater than {{limit}}
         *
         * {{size}} the file upload size
         * {{limit}} max_file_size_upload in the parameters.(env).yml
         *
         * in case of custom the error message, add the maxSizeMessage attribute the the assertion :
         * @example :
         *
         *           maxSizeMessage= "you custom message ({{ size }} ). you custom message  {{ limit }} ."
         *
         */
        public $maxSizeMessage = 'The file is too large ({{ size }} M). Allowed maximum size is {{ limit }} M.';


    }

约束的验证器class:

<?php


namespace Acme\AppBundle\Service\Validation;


use Symfony\Component\HttpFoundation\File\UploadedFile;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
use Symfony\Component\Validator\Exception\UnexpectedTypeException;

    /** 
     *
     * Class FileSizeValidator
     * @package Acme\AppBundle\Service\Validation
     */
    class FileSizeValidator extends ConstraintValidator
    {

        const CONVERT_MB_TO_B = "MBTOB";
        const CONVERT_B_TO_MB = "BTOMB";


        private $_maxFileSizeUpload;


        public function __construct($maxFileSizeUpload)
        {
            $this->_maxFileSizeUpload = $maxFileSizeUpload;
        }

        /**
         * @param mixed $value
         * @param Constraint $constraint
         */
        public function validate($value, Constraint $constraint)
        {

            if (!$constraint instanceof FileSize) {

                throw new UnexpectedTypeException($constraint, __NAMESPACE__.'\FileSize');
            }

            if($value instanceof UploadedFile){

                if($this->_maxFileSizeUpload < $this->factorizeSize($value->getClientSize())){

                    $this->context->buildViolation($constraint->maxSizeMessage)
                        ->setParameter('{{ size }}', $this->factorizeSize($value->getClientSize(),self::CONVERT_B_TO_MB))
                        ->setParameter('{{ limit }}', $this->_maxFileSizeUpload)
                        ->addViolation();

                }

            }

            return;

        }


        /**
         * @param $size
         * @param string $convert
         * @return float|int
         */
        protected function factorizeSize($size,$convert =self::CONVERT_MB_TO_B){

            $size = intval($size);

            if($convert == self::CONVERT_MB_TO_B){

                return $size*pow(10,6);

            }
            else{

                return intval($size/pow(10,6));

            }


        }




    }

验证器应该声明为注入参数值的服务,所以我们需要在service.yml中添加它:

  fileSizeValidator.service:
    class: Acme\AppBundle\Service\Validation\FileSizeValidator
    arguments: [%max_file_size_upload%]
    tags:
      - name: validator.constraint_validator
        alias: file_size_correct

The alias : file_size_correct is the value tha your method validateBy sould return in the FileSize Class , because your Validator is now service , if not , your constraint can't find the Validator class . see the official doc [here][1]

[1]: https://symfony.com/doc/2.8/validation/custom_constraint.html#constraint-validators-with-dependencies

使用约束:

   /**
     * @MyAssert\FileSize()
     *
     * @var File $file
     */
    protected $file;

希望对您有所帮助。