Passed
Push — master ( fdcaa7...4335a1 )
by SignpostMarv
02:45
created

CookieMiddleware::DaftRouterMiddlewareHandler()   C

Complexity

Conditions 8
Paths 4

Size

Total Lines 46
Code Lines 29

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 29
CRAP Score 8.0023

Importance

Changes 0
Metric Value
cc 8
eloc 29
nc 4
nop 2
dl 0
loc 46
ccs 29
cts 30
cp 0.9667
crap 8.0023
rs 5.5555
c 0
b 0
f 0
1
<?php
2
/**
3
* @author SignpostMarv
4
*/
5
declare(strict_types=1);
6
7
namespace SignpostMarv\DaftFramework\Http;
8
9
use SignpostMarv\DaftFramework\Framework;
10
use SignpostMarv\DaftRouter\DaftMiddleware;
11
use Symfony\Component\HttpFoundation\Cookie;
12
use Symfony\Component\HttpFoundation\Request;
13
use Symfony\Component\HttpFoundation\Response;
14
15
class CookieMiddleware implements DaftMiddleware
16
{
17 16
    public static function DaftRouterMiddlewareHandler(
18
        Request $request,
19
        ? Response $response
20
    ) : ? Response {
21 16
        if ( ! is_null($response)) {
22 16
            $framework = Framework::ObtainFrameworkForRequest($request);
23
24 16
            $config = $framework->ObtainConfig();
25
26 16
            if ( ! isset($config[self::class])) {
27
                return $response;
28
            }
29
30 16
            $config = $config[self::class];
31
32 16
            $configSecure = (bool) ($config['secure'] ?? null);
33 16
            $configHttpOnly = (bool) ($config['httpOnly'] ?? null);
34 16
            $configSameSite = is_string($config['sameSite'] ?? null) ? $config['sameSite'] : null;
35
36 16
            foreach ($response->headers->getCookies() as $cookie) {
37 16
                $updateSecure = $cookie->isSecure() !== $configSecure;
38 16
                $updateHttpOnly = $cookie->isHttpOnly() !== $configHttpOnly;
39 16
                $updateSameSite = $cookie->getSameSite() !== $configSameSite;
40
41 16
                if ($updateSecure || $updateHttpOnly || $updateSameSite) {
42 16
                    $response->headers->removeCookie(
43 16
                        $cookie->getName(),
44 16
                        $cookie->getPath(),
45 16
                        $cookie->getDomain()
46
                    );
47 16
                    $response->headers->setCookie(new Cookie(
48 16
                        $cookie->getName(),
49 16
                        $cookie->getValue(),
50 16
                        $cookie->getExpiresTime(),
51 16
                        $cookie->getPath(),
52 16
                        $cookie->getDomain(),
53 16
                        $configSecure,
54 16
                        $configHttpOnly,
55 16
                        $cookie->isRaw(),
56 16
                        $configSameSite
57
                    ));
58
                }
59
            }
60
        }
61
62 16
        return $response;
63
    }
64
65 2
    public static function DaftRouterRoutePrefixExceptions() : array
66
    {
67 2
        return [];
68
    }
69
}
70