Passed
Push — master ( c48dc4...38cb10 )
by Samuel
12:56
created

PhpViewMiddleware::process()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 20
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 11
CRAP Score 2.0023

Importance

Changes 0
Metric Value
cc 2
eloc 10
nc 2
nop 2
dl 0
loc 20
ccs 11
cts 12
cp 0.9167
crap 2.0023
rs 9.9332
c 0
b 0
f 0
1
<?php
2
3
namespace App\Application\Middleware;
4
5
use App\Infrastructure\Utility\JsImportCacheBuster;
6
use App\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