Skip to content

Instantly share code, notes, and snippets.

@1ma
Created May 19, 2020 12:08
Show Gist options
  • Save 1ma/a5b167c605c6713f9e9b3a54666a9c93 to your computer and use it in GitHub Desktop.
Save 1ma/a5b167c605c6713f9e9b3a54666a9c93 to your computer and use it in GitHub Desktop.
middleware outgoing data flow
<?php
declare(strict_types=1);
namespace Project\Infrastrucuture\Middleware;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;
final class RenderingMiddleware implements MiddlewareInterface
{
/** @var \Twig\Environment */
private $twig;
public function __construct(\Twig\Environment $twig)
{
$this->twig = $twig;
}
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
{
$response = $handler->handle($request);
$template = $response->getAttribute('Twig-Template', null);
$variables = $response->getAttribute('Twig-Variables', []);
if (null === $template) {
return $response;
}
$response->getBody()->write($this->twig->render($template, $variables));
return $response->withHeader('Content-Type', 'text/html');
}
}
<?php
declare(strict_types=1);
namespace Project\Infrastructure\Action;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\RequestHandlerInterface;
use Slim\Psr7\Response;
final class SampleRequestHandler implements RequestHandlerInterface
{
public function handle(ServerRequestInterface $request): ResponseInterface
{
return new Response(200)
->withAttribute('Twig-Template', 'foo.twig')
->withAttribute('Twig-Variables', ['bar' => 'baz']);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment