PhpViewMiddleware::process()   A
last analyzed

Complexity

Conditions 3
Paths 4

Size

Total Lines 32
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 19
CRAP Score 3.0011

Importance

Changes 0
Metric Value
eloc 17
dl 0
loc 32
ccs 19
cts 20
cp 0.95
rs 9.7
c 0
b 0
f 0
cc 3
nc 4
nop 2
crap 3.0011
1
<?php
2
3
namespace App\Application\Middleware;
4
5
use App\Infrastructure\JsCacheBusting\JsImportCacheBuster;
6
use App\Infrastructure\Settings\Settings;
7
use App\Module\User\Read\Service\UserReadAuthorizationChecker;
8
use Cake\Database\Exception\DatabaseException;
9
use Odan\Session\SessionInterface;
10
use Psr\Http\Message\ResponseInterface;
11
use Psr\Http\Message\ServerRequestInterface;
12
use Psr\Http\Server\MiddlewareInterface;
13
use Psr\Http\Server\RequestHandlerInterface;
14
use Slim\App;
15
use Slim\Interfaces\RouteParserInterface;
16
use Slim\Routing\RouteContext;
17
use Slim\Views\PhpRenderer;
18
19
/**
20
 * Adds attributes to the PhpRenderer and updates js imports with version number.
21
 * Documentation: https://samuel-gfeller.ch/docs/Template-Rendering.
22
 */
23
final class PhpViewMiddleware implements MiddlewareInterface
24
{
25
    /** @var array<string, mixed> */
26
    private array $publicSettings;
27
    /** @var array<string, mixed> */
28
    private array $deploymentSettings;
29
30 203
    public function __construct(
31
        /** @var App<\Psr\Container\ContainerInterface> $app */
32
        private readonly App $app,
33
        private readonly PhpRenderer $phpRenderer,
34
        private readonly SessionInterface $session,
35
        private readonly JsImportCacheBuster $jsImportCacheBuster,
36
        Settings $settings,
37
        private readonly UserReadAuthorizationChecker $userReadAuthorizationChecker,
38
        private readonly RouteParserInterface $routeParser,
39
    ) {
40 203
        $this->publicSettings = $settings->get('public');
41 203
        $this->deploymentSettings = $settings->get('deployment');
42
    }
43
44 203
    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
45
    {
46 203
        $loggedInUserId = $this->session->get('user_id');
47
        // The following has to work even with no connection to mysql to display the error page (layout needs those attr)
48 203
        $this->phpRenderer->setAttributes([
49 203
            'version' => $this->deploymentSettings['version'],
50 203
            'uri' => $request->getUri(),
51 203
            'basePath' => $this->app->getBasePath(),
52 203
            'route' => $this->routeParser,
53 203
            'currRouteName' => RouteContext::fromRequest($request)->getRoute()?->getName(),
54 203
            'flash' => $this->session->getFlash(),
55
            // Used for public values used by view like company email address
56 203
            'config' => $this->publicSettings,
57 203
            'authenticatedUser' => $loggedInUserId,
58 203
        ]);
59
60
        // Check and set user list authorization for "users" nav point
61 203
        if ($loggedInUserId) {
62
            // Check if the authenticated user is allowed to see user list
63
            // Add the user list authorization as an attribute to the PhpRenderer
64 149
            $this->phpRenderer->addAttribute(
65 149
                'userListAuthorization',
66 149
                $this->checkUserListAuthorization($loggedInUserId)
67 149
            );
68
        }
69
70
        // Add version number to js imports
71 203
        if ($this->deploymentSettings['update_js_imports_version'] === true) {
72
            $this->jsImportCacheBuster->addVersionToJsImports();
73
        }
74
75 203
        return $handler->handle($request);
76
    }
77
78
    /**
79
     * Check if the user is allowed to see the user list.
80
     *
81
     * @param int $loggedInUserId
82
     *
83
     * @return bool
84
     */
85 149
    private function checkUserListAuthorization(int $loggedInUserId): bool
86
    {
87
        try {
88
            // If the authenticated user is allowed to read another user (id + 1), the user list can be displayed
89 149
            return $this->userReadAuthorizationChecker->isGrantedToRead($loggedInUserId + 1, false);
90
        } catch (DatabaseException $databaseException) {
91
            // Mysql connection not working. Caught here to prevent error page from crashing
92
            return false;
93
        }
94
    }
95
}
96