Created
February 17, 2018 12:17
-
-
Save stefanotorresi/beca4e12ba9350601fa65311e60a9478 to your computer and use it in GitHub Desktop.
Barebone example of a PSR-15 middleware stack.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
"require": { | |
"psr/http-server-middleware": "^1.0", | |
"zendframework/zend-diactoros": "^1.7" | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
declare(strict_types=1); | |
use Psr\Http\Message\ResponseInterface as Response; | |
use Psr\Http\Message\ServerRequestInterface as Request; | |
use Psr\Http\Server\MiddlewareInterface as Middleware; | |
use Psr\Http\Server\RequestHandlerInterface as Handler; | |
use Zend\Diactoros\Response\SapiEmitter; | |
use Zend\Diactoros\Response\TextResponse; | |
use Zend\Diactoros\ServerRequestFactory; | |
require 'vendor/autoload.php'; | |
(function(){ | |
$request = ServerRequestFactory::fromGlobals(); | |
$app = new class implements Handler | |
{ | |
public function handle(Request $request): Response | |
{ | |
$greet = $request->getQueryParams()['greet'] ?? "World"; | |
return new TextResponse("Hello $greet"); | |
} | |
}; | |
$middlewareStack = [ | |
new class implements Middleware { | |
public function process(Request $request, Handler $handler): Response | |
{ | |
if (! isset($request->getQueryParams()['greet'])) { | |
throw new Exception('missing greet query param!'); | |
} | |
return $handler->handle($request); | |
} | |
}, | |
new class implements Middleware { | |
public function process(Request $request, Handler $handler): Response | |
{ | |
try { | |
$response = $handler->handle($request); | |
} catch (Exception $exception) { | |
$response = new TextResponse('Error: ' . $exception->getMessage(), 500); | |
} | |
return $response; | |
} | |
}, | |
]; | |
$middlewarePipe = array_reduce( | |
$middlewareStack, | |
function(Handler $next, Middleware $middleware) | |
{ | |
return new class($next, $middleware) implements Handler | |
{ | |
private $next; | |
private $middleware; | |
public function __construct(Handler $next, Middleware $middleware) | |
{ | |
$this->next = $next; | |
$this->middleware = $middleware; | |
} | |
public function handle(Request $request): Response | |
{ | |
return $this->middleware->process($request, $this->next); | |
} | |
}; | |
}, | |
$app | |
); | |
$response = $middlewarePipe->handle($request); | |
(new SapiEmitter())->emit($response); | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment