Completed
Push — master ( 1ba115...baab82 )
by Nico
02:35
created

StrictTransportSecurityHeader::getMaxAge()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 8
ccs 4
cts 4
cp 1
rs 10
c 0
b 0
f 0
cc 2
nc 2
nop 1
crap 2
1
<?php declare(strict_types=1);
2
3
/**
4
 * @license  http://opensource.org/licenses/mit-license.php MIT
5
 * @link     https://github.com/nicoSWD
6
 * @author   Nicolas Oelgart <[email protected]>
7
 */
8
namespace nicoSWD\SecHeaderCheck\Domain\Validator\Header;
9
10
use nicoSWD\SecHeaderCheck\Domain\Result\Result\StrictTransportSecurityHeaderResult;
11
use nicoSWD\SecHeaderCheck\Domain\Validator\AbstractHeaderParser;
12
13
final class StrictTransportSecurityHeader extends AbstractHeaderParser
14
{
15
    private const ONE_YEAR_IN_SECONDS = 31536000;
16
    private const FLAG_INCLUDE_SUB_DOMAINS = 'includesubdomains';
17
18 8
    public function parse(): StrictTransportSecurityHeaderResult
19
    {
20 8
        return (new StrictTransportSecurityHeaderResult($this->getName(), $this->getValue()))
21 8
            ->setHasSecureMaxAge($this->isMinRecommendedMaxAge())
22 8
            ->setHasFlagIncludeSubDomains($this->hasIncludeSubDomainsFlag());
23
    }
24
25 8
    private function hasIncludeSubDomainsFlag(): bool
26
    {
27
        $callback = function (string $option): string {
28 8
            return strtolower(trim($option));
29 8
        };
30
31 8
        $options = array_map($callback, explode(';', $this->getValue()));
32
33 8
        return in_array(self::FLAG_INCLUDE_SUB_DOMAINS, $options, true);
34
    }
35
36 8
    private function isMinRecommendedMaxAge(): bool
37
    {
38 8
        $maxAge = $this->getMaxAge($this->getValue());
39
40 8
        return $maxAge !== false && $maxAge >= self::ONE_YEAR_IN_SECONDS;
41
    }
42
43 8
    private function getMaxAge(string $value)
44
    {
45 8
        if (preg_match('~max-age\s*=\s*([1-9]\d*)~i', $value, $maxAge)) {
46 6
            return (int) $maxAge[1];
47
        }
48
49 2
        return false;
50
    }
51
}
52