Skip to content

PSR 15: Middleware Example

Terry L edited this page Jun 21, 2020 · 6 revisions
Clone this wiki locally

PSR-15 HTTP Server Request Handlers

Namespace

Shieldon\Psr15\Middleware

Middleware

__construct

None

process($request, $handler)

  • param ServerRequestInterface request * The server request.
  • param RequestHandlerInterface handler * The request handler.
  • return ResponseInterface

Example:

class ApiMiddleware extends Middleware
{
    public function process(ServerRequestInterface  $request, RequestHandlerInterface $handler): ResponseInterface
    {
        $contentType = $request->getHeaderLine('Content-Type');
        $key = $request->getHeaderLine('key');
        $secret = $request->getHeaderLine('secret');

        if ($contentType !== 'application/json') {
            return (new Response)->withStatus(406, 'Content type is not accepted.');
        }

        if ($key !== '23492834234') {
            return (new Response)->withStatus(401, 'API key is invalid.');
        }

        if ($secret !== '1a163782ee166156294d173fcf8b8e87') {
            return (new Response)->withStatus(401, 'API secret is invalid.');
        }

        return $handler->handle($request);
    }
}