Created
May 19, 2020 12:08
-
-
Save 1ma/a5b167c605c6713f9e9b3a54666a9c93 to your computer and use it in GitHub Desktop.
middleware outgoing data flow
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); | |
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'); | |
} | |
} |
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); | |
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