Passed
Push — master ( 648f26...44b606 )
by Samuel
13:37
created

PhpViewMiddleware::process()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 30
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 17
CRAP Score 3.0015

Importance

Changes 0
Metric Value
eloc 16
dl 0
loc 30
ccs 17
cts 18
cp 0.9444
rs 9.7333
c 0
b 0
f 0
cc 3
nc 4
nop 2
crap 3.0015
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
    /** @var array<string, mixed> */
22
    private array $publicSettings;
23
    /** @var array<string, mixed> */
24
    private array $deploymentSettings;
25
26 179
    public function __construct(
27
        private readonly App $app,
28
        private readonly PhpRenderer $phpRenderer,
29
        private readonly SessionInterface $session,
30
        private readonly JsImportCacheBuster $jsImportCacheBuster,
31
        Settings $settings,
32
        private readonly UserPermissionVerifier $userPermissionVerifier,
33
        private readonly RouteParserInterface $routeParser
34
    ) {
35 179
        $this->publicSettings = $settings->get('public');
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
            'version' => $this->deploymentSettings['version'],
45 179
            'uri' => $request->getUri(),
46 179
            'basePath' => $this->app->getBasePath(),
47 179
            'route' => $this->routeParser,
48 179
            'currRouteName' => RouteContext::fromRequest($request)->getRoute()?->getName(),
49 179
            'flash' => $this->session->getFlash(),
50
            // Used for public values used by view like company email address
51 179
            'config' => $this->publicSettings,
52 179
            'authenticatedUser' => $loggedInUserId,
53 179
        ]);
54
55
        // Check and set user list authorization for "users" nav point
56 179
        if ($loggedInUserId) {
57
            // Check if the authenticated user is allowed to see user list and save the result to the session
58 125
            $this->checkUserListAuthorization($loggedInUserId);
59
            // Add the user list authorization as an attribute to the PhpRenderer
60 125
            $this->phpRenderer->addAttribute('userListAuthorization', $this->session->get('isAllowedToSeeUserList'));
61
        }
62
63
        // Add version number to js imports
64 179
        if ($this->deploymentSettings['update_js_imports_version'] === true) {
65
            $this->jsImportCacheBuster->addVersionToJsImports();
66
        }
67
68 179
        return $handler->handle($request);
69
    }
70
71
    /**
72
     * Check if the user is allowed to see the user list and save the result to the session.
73
     *
74
     * @param int $loggedInUserId
75
     */
76 125
    private function checkUserListAuthorization(int $loggedInUserId): void
77
    {
78
        // If the session already contains the information, the permission check can be skipped
79 125
        if ($this->session->get('isAllowedToSeeUserList') === null) {
80
            try {
81 125
                $isAllowedToSeeUserList = $this->userPermissionVerifier->isGrantedToRead($loggedInUserId + 1, false);
82 125
                $this->session->set('isAllowedToSeeUserList', $isAllowedToSeeUserList);
83
            } catch (DatabaseException $databaseException) {
84
                // Mysql connection not working. Caught here to prevent error page from crashing
85
                return;
86
            }
87
        }
88
    }
89
}
90