在Slim中向路由添加中间件时出错

问题描述 投票:0回答:1

我在Slim中编写了这段代码并且工作正常,但是当我添加中间件时,我收到以下错误!无法弄清楚发生了什么,任何人都可以帮助我。

PHP Catchable fatal error:  Argument 3 passed to fileFilter() must be callable, array given FILENAME in line 90

此中间件过滤不受支持的文件类型

use Slim\Http\Request;
use Slim\Http\Response;
use Api\ErrorList as ErrorList;

function fileFilter(Request $request, Response $response, callable $next){
        $allowedFiles = ['image/jpeg', 'image/png', 'application/pdf'];
        $files = $request->getUploadedFiles();
        $flattened =array_flatten($files);

        foreach ($flattened as $key=> $newFile){
            $newFileType = $newFile->getClientMediaType();

            if(!in_array($newFileType, $allowedFiles)) {
                return ResponseHelper::createfailureResponse($response, HTTPStatusCodes::BAD_REQUEST, ErrorList::UNSUPPORTED_FILE_TYPE);
            }

        }
        return $next($request, $response); // line 90
    }

在这里,我将中间件添加到我的路线中。

 $app->group('/test/api/v1', function () {
        // other routes here
        $this->post('/resume/edit','fileFilter', ResumeController::class. ':edit')->setName('Resume.edit');


    });
php slim middleware
1个回答
0
投票

你应该删除'fileFilter'

$this->post('/resume/edit', ...

并将其改为类似的东西

$this->post(...)->add((Request $request, Response $response, callable $next){
    $allowedFiles = ['image/jpeg', 'image/png', 'application/pdf'];
    $files = $request->getUploadedFiles();
    $flattened =array_flatten($files);

    foreach ($flattened as $key=> $newFile){
        $newFileType = $newFile->getClientMediaType();

        if(!in_array($newFileType, $allowedFiles)) {
            return ResponseHelper::createfailureResponse($response, HTTPStatusCodes::BAD_REQUEST, ErrorList::UNSUPPORTED_FILE_TYPE);
        }

    }
    return $next($request, $response); // line 90
});

或作为可调用的类

class MyMiddleware
{
    public function __invoke(Request $request, Response $response, callable $next){
        $allowedFiles = ['image/jpeg', 'image/png', 'application/pdf'];
        $files = $request->getUploadedFiles();
        $flattened =array_flatten($files);

        foreach ($flattened as $key=> $newFile){
            $newFileType = $newFile->getClientMediaType();

            if(!in_array($newFileType, $allowedFiles)) {
                return ResponseHelper::createfailureResponse($response, HTTPStatusCodes::BAD_REQUEST, ErrorList::UNSUPPORTED_FILE_TYPE);
           }

        }
        return $next($request, $response); // line 90
    }
}

并在途中

$this->post(...)->add(MyMiddleware::class);

Slim Middleware

© www.soinside.com 2019 - 2024. All rights reserved.