Passed
Push — master ( c1383e...afe6aa )
by Samuel
02:23
created

PhpViewMiddleware   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 68
Duplicated Lines 0 %

Test Coverage

Coverage 93.1%

Importance

Changes 0
Metric Value
wmc 7
eloc 30
dl 0
loc 68
ccs 27
cts 29
cp 0.931
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A checkUserListAuthorization() 0 10 3
A __construct() 0 12 1
A process() 0 31 3
1
<?php
2
3
namespace App\Application\Middleware;
4
5
use App\Domain\User\Service\Authorization\UserPermissionVerifier;
6
use App\Infrastructure\Utility\JsImportCacheBuster;
7
use App\Infrastructure\Utility\Settings;
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
final class PhpViewMiddleware implements MiddlewareInterface
20
{
21
    private array $publicSettings;
22
    private bool $devSetting;
23
    private array $deploymentSettings;
24
25 179
    public function __construct(
26
        private readonly App $app,
27
        private readonly PhpRenderer $phpRenderer,
28
        private readonly SessionInterface $session,
29
        private readonly JsImportCacheBuster $jsImportCacheBuster,
30
        Settings $settings,
31
        private readonly UserPermissionVerifier $userPermissionVerifier,
32
        private readonly RouteParserInterface $routeParser
33
    ) {
34 179
        $this->publicSettings = $settings->get('public');
35 179
        $this->devSetting = $settings->get('dev');
36 179
        $this->deploymentSettings = $settings->get('deployment');
37
    }
38
39 179
    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
40
    {
41 179
        $loggedInUserId = $this->session->get('user_id');
42
        // The following has to work even with no connection to mysql to display the error page (layout needs those attr)
43 179
        $this->phpRenderer->setAttributes([
44 179
            'dev' => $this->devSetting,
45 179
            'version' => $this->deploymentSettings['version'],
46 179
            'uri' => $request->getUri(),
47 179
            'basePath' => $this->app->getBasePath(),
48 179
            'route' => $this->routeParser,
49 179
            'currRouteName' => RouteContext::fromRequest($request)->getRoute()?->getName(),
50 179
            'flash' => $this->session->getFlash(),
51
            // Used for public values used by view like company email address
52 179
            'config' => $this->publicSettings,
53 179
            'authenticatedUser' => $loggedInUserId,
54 179
        ]);
55
56
        // Check and set user list authorization for "users" nav point
57 179
        if ($loggedInUserId) {
58
            // Check if the authenticated user is allowed to see user list and save the result to the session
59 125
            $this->checkUserListAuthorization($loggedInUserId);
60
            // Add the user list authorization as an attribute to the PhpRenderer
61 125
            $this->phpRenderer->addAttribute('userListAuthorization', $this->session->get('isAllowedToSeeUserList'));
62
        }
63
64
        // Add version number to js imports
65 179
        if ($this->deploymentSettings['update_js_imports_version'] === true) {
66 179
            $this->jsImportCacheBuster->addVersionToJsImports();
67
        }
68
69 179
        return $handler->handle($request);
70
    }
71
72
    /**
73
     * Check if the user is allowed to see the user list and save the result to the session.
74
     *
75
     * @param int $loggedInUserId
76
     */
77 125
    private function checkUserListAuthorization(int $loggedInUserId): void
78
    {
79
        // If the session already contains the information, the permission check can be skipped
80 125
        if ($this->session->get('isAllowedToSeeUserList') === null) {
81
            try {
82 125
                $isAllowedToSeeUserList = $this->userPermissionVerifier->isGrantedToRead($loggedInUserId + 1, false);
83 125
                $this->session->set('isAllowedToSeeUserList', $isAllowedToSeeUserList);
84
            } catch (DatabaseException $databaseException) {
85
                // Mysql connection not working. Caught here to prevent error page from crashing
86
                return;
87
            }
88
        }
89
    }
90
}
91