PhpViewMiddleware   A
last analyzed

Complexity

Total Complexity 3

Size/Duplication

Total Lines 38
Duplicated Lines 0 %

Test Coverage

Coverage 93.33%

Importance

Changes 0
Metric Value
eloc 15
dl 0
loc 38
ccs 14
cts 15
cp 0.9333
rs 10
c 0
b 0
f 0
wmc 3

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 9 1
A process() 0 20 2
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