0

I look in several places and I didn't found a way to overwrite params that comes in the request using middleware with Slim in PHP.

Use case: I want to scape all the query params that come into all my endpoint but I don't wanna write the same code everywhere, so the idea was to use the middleware that slim provides and clean the param there.

Is this a thing and can be done?

  • Think you need something along the lines of https://stackoverflow.com/questions/45039193/slim-modify-post-request-body-inside-middleware. You can see how they get the request parameters and create a new request with the new data. This new request is then passed onto the next layer. – Nigel Ren May 30 '21 at 07:20
  • Thnks @NigelRen, that actually work – Federico Román Jun 09 '21 at 13:23

1 Answers1

0

Using middleware, you need something like this:

// relevant imports
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;


// middleware after $app has been created
$app->addMiddleware(new class () implements MiddlewareInterface {
    public function process(
        ServerRequestInterface $request,
        RequestHandlerInterface $handler
    ): ResponseInterface {
        $queryParams = $request->getQueryParams();
        // $queryParams is an array of the query parameters.
        // do whatever with them.
        
        // e.g. add a new one:
        $queryParams['foo'] = 'bar;

        // replace the request's ones with our new set:
        $request = $request->withQueryParams($queryParams);
       
        // continue with next middleware all the way through
        // to the handler with our new set of query parameters.
        return $handler->handle($request);
    }
});
Rob Allen
  • 12,643
  • 1
  • 40
  • 49