/
TemplatingMiddleware.php
50 lines (40 loc) · 1.44 KB
/
TemplatingMiddleware.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
<?php
declare(strict_types=1);
namespace Snicco\Bundle\Templating;
use Psr\Http\Message\ResponseInterface;
use Snicco\Component\HttpRouting\Http\Psr7\Request;
use Snicco\Component\HttpRouting\Http\Psr7\Response;
use Snicco\Component\HttpRouting\Http\Response\ViewResponse;
use Snicco\Component\HttpRouting\Middleware\Middleware;
use Snicco\Component\HttpRouting\Middleware\NextMiddleware;
use Snicco\Component\Templating\TemplateEngine;
final class TemplatingMiddleware extends Middleware
{
/**
* @var callable():TemplateEngine
*/
private $view_engine;
/**
* @param callable():TemplateEngine $view_engine
*/
public function __construct(callable $view_engine)
{
// We make this a callable because the process of resolving the ViewEngine involves invoking several classes and
// we might only ever need this for some requests.
$this->view_engine = $view_engine;
}
protected function handle(Request $request, NextMiddleware $next): ResponseInterface
{
$response = $next($request);
if (! $response instanceof ViewResponse) {
return $response;
}
$body = $this->getViewEngine()
->render($response->view(), $response->viewData());
return (new Response($response))->withBody($this->responseFactory()->createStream($body));
}
private function getViewEngine(): TemplateEngine
{
return ($this->view_engine)();
}
}