Laravel: 添加视频维度验证

Laravel: Adding video dimension validation

我知道我们可以通过

在 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'
        ]
    );

我已经为视频尝试了这些尺寸规则,但它似乎不起作用。

视频有没有可能达到同样的效果?

如何制定自己的规则?存在一个通过 composer 读取名为 getID3.

的视频文件元数据的库

安装它:

composer require james-heinrich/getid3

创建自定义规则class:

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)]
    ]
);

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