1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace App\Core\Application\Middleware; |
4
|
|
|
|
5
|
|
|
use App\Core\Infrastructure\Utility\JsImportCacheBuster; |
6
|
|
|
use App\Core\Infrastructure\Utility\Settings; |
7
|
|
|
use Psr\Http\Message\ResponseInterface; |
8
|
|
|
use Psr\Http\Message\ServerRequestInterface; |
9
|
|
|
use Psr\Http\Server\MiddlewareInterface; |
10
|
|
|
use Psr\Http\Server\RequestHandlerInterface; |
11
|
|
|
use Slim\App; |
12
|
|
|
use Slim\Interfaces\RouteParserInterface; |
13
|
|
|
use Slim\Routing\RouteContext; |
14
|
|
|
use Slim\Views\PhpRenderer; |
15
|
|
|
|
16
|
|
|
/** |
17
|
|
|
* Adds attributes to the PhpRenderer and updates js imports with version number. |
18
|
|
|
* Documentation: https://samuel-gfeller.ch/docs/Template-Rendering. |
19
|
|
|
*/ |
20
|
|
|
final class PhpViewMiddleware implements MiddlewareInterface |
21
|
|
|
{ |
22
|
|
|
/** @var array<string, mixed> */ |
23
|
|
|
private array $publicSettings; |
24
|
|
|
/** @var array<string, mixed> */ |
25
|
|
|
private array $deploymentSettings; |
26
|
|
|
|
27
|
17 |
|
public function __construct( |
28
|
|
|
private readonly App $app, |
29
|
|
|
private readonly PhpRenderer $phpRenderer, |
30
|
|
|
private readonly JsImportCacheBuster $jsImportCacheBuster, |
31
|
|
|
Settings $settings, |
32
|
|
|
private readonly RouteParserInterface $routeParser |
33
|
|
|
) { |
34
|
17 |
|
$this->publicSettings = $settings->get('public'); |
35
|
17 |
|
$this->deploymentSettings = $settings->get('deployment'); |
36
|
|
|
} |
37
|
|
|
|
38
|
17 |
|
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface |
39
|
|
|
{ |
40
|
|
|
// The following has to work even with no connection to mysql to display the error page (layout needs those attr) |
41
|
17 |
|
$this->phpRenderer->setAttributes([ |
42
|
17 |
|
'version' => $this->deploymentSettings['version'], |
43
|
17 |
|
'uri' => $request->getUri(), |
44
|
17 |
|
'basePath' => $this->app->getBasePath(), |
45
|
17 |
|
'route' => $this->routeParser, |
46
|
17 |
|
'currRouteName' => RouteContext::fromRequest($request)->getRoute()?->getName(), |
47
|
|
|
// Used for public values (e.g. app name) used by templates or layout |
48
|
17 |
|
'config' => $this->publicSettings, |
49
|
17 |
|
]); |
50
|
|
|
|
51
|
|
|
// Add version number to js imports in development mode |
52
|
|
|
// https://samuel-gfeller.ch/docs/Template-Rendering#js-import-cache-busting |
53
|
17 |
|
if ($this->deploymentSettings['update_js_imports_version'] === true) { |
54
|
|
|
$this->jsImportCacheBuster->addVersionToJsImports(); |
55
|
|
|
} |
56
|
|
|
|
57
|
17 |
|
return $handler->handle($request); |
58
|
|
|
} |
59
|
|
|
} |
60
|
|
|
|