Laravel:添加视频维度验证

时间:2018-03-13 15:13:00

标签: php validation laravel-5 laravel-5.5

我知道我们可以通过

为laravel中的图像添加尺寸验证
$validator = Validator::make($request->all(), 
        [
            'banner' => 'bail
                        |image
                        |mimes:jpeg,png,jpg,gif,svg
                        |max:7000
                        |dimensions:ratio=170/63
                        |dimensions:min_width=510,min_height=189'
        ]
    );

我已尝试过视频的这些尺寸规则,但它似乎无法正常工作。

视频可以达到相同的效果吗?

1 个答案:

答案 0 :(得分:1)

如何制定自己的规则?通过编辑器存在一个库,该编辑器读取名为getID3的视频文件的元数据。

安装它:

composer require james-heinrich/getid3

创建自定义规则类:

php artisan make:rule VideoDimension

借助getid3创建规则的逻辑:

<?php

namespace App\Rules;

use Illuminate\Contracts\Validation\Rule;

class VideoDimension implements Rule
{
    protected $maxWidth;
    protected $maxHeight;

    public function __construct($maxWidth, $maxHeight)
    {
        $this->maxWidth = $maxWidth;
        $this->maxHeight = $maxHeight;
    }
    /**
     * Determine if the validation rule passes.
     *
     * @param  string  $attribute
     * @param  mixed  $value
     * @return bool
     */
    public function passes($attribute, $value)
    {
        $getID3 = new getID3;

        // the value is an instance of UploadedFile
        $file = $getID3->analyze($value->getRealPath());

        $passes = true;

        if ($this->maxWidth < $file['video']['resolution_x']
            || $this->maxHeight < $file['video']['resolution_y']){
            $passes = false;
        }

        return $passes;
    }

    /**
     * Get the validation error message.
     *
     * @return string
     */
    public function message()
    {
        return 'The :attribute excess the dimensions.';
    }
}

最后,应用规则:

$validator = Validator::make($request->all(), 
    [
        'video' => ['bail',
                    'file',
                    'max:7000',
                    new VideoDimension(400, 600)]
    ]
);

希望这个例子可以帮助您弄清楚如何完成任务。