Skip to content

Instantly share code, notes, and snippets.

@stefanotorresi
Last active February 7, 2018 09:28
Show Gist options
  • Save stefanotorresi/81fe3847926456a51768ef8262affd7e to your computer and use it in GitHub Desktop.
Save stefanotorresi/81fe3847926456a51768ef8262affd7e to your computer and use it in GitHub Desktop.
How to use old style single pass anonymous function middleware with the PSR-15 spec.
<?php
use Psr\Http\Message\ServerRequestInterface as Request;
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Server\RequestHandlerInterface as Handler;
use Psr\Http\Server\MiddlewareInterface as Middleware;
$middleware = function(Request $req, callable $next): Response {
$res = $next($req);
return $res->withHeader('X-Foo', 'Bar');
}
$psr15Middleware = new class ($middeware) implements Middleware {
private $wrapped;
public function __construct(callable $mw)
{
$this->wrapped = $mw;
}
public function process(Request $req, Handler $handler): Response
{
return ($this->wrapped)($req, [ $handler, 'handle' ]);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment