Completed
Pull Request — master (#31)
by Gawain
01:46
created

CanonicalizeBodyRelaxed   A

Complexity

Total Complexity 12

Size/Duplication

Total Lines 77
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 0

Test Coverage

Coverage 80.48%

Importance

Changes 0
Metric Value
wmc 12
lcom 0
cbo 0
dl 0
loc 77
ccs 33
cts 41
cp 0.8048
rs 10
c 0
b 0
f 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
A name() 0 4 1
C canonicalize() 0 61 11
1
<?php
2
declare(strict_types=1);
3
4
namespace Genkgo\Mail\Dkim;
5
6
use Genkgo\Mail\StreamInterface;
7
8
final class CanonicalizeBodyRelaxed implements CanonicalizeBodyInterface
9
{
10
11
    /**
12
     * @param StreamInterface $body
13
     * @return string
14
     */
15 2
    public function canonicalize(StreamInterface $body): string
16
    {
17 2
        $string = (string)$body;
18 2
        if ($string === '') {
19
            return $string;
20
        }
21
22 2
        $length = strlen($string);
23 2
        $canon = '';
24 2
        $lastChar = null;
25 2
        $space = false;
26 2
        $line = '';
27 2
        $emptyCounter = 0;
28
29 2
        for ($i = 0; $i < $length; ++$i) {
30 2
            switch ($string[$i]) {
31
                case "\r":
32 1
                    $lastChar = "\r";
33 1
                    break;
34
35
                case "\n":
36 1
                    if ($lastChar === "\r") {
37 1
                        $space = false;
38
39 1
                        if ($line === '') {
40 1
                            ++$emptyCounter;
41
                        } else {
42 1
                            $line = '';
43 1
                            $canon .= "\r\n";
44
                        }
45
                    } else {
46
                        throw new \RuntimeException('This should never happen');
47
                    }
48
49 1
                    break;
50
51
                case ' ':
52
                case "\t":
53 2
                    $space = true;
54 2
                    break;
55
56
                default:
57 2
                    if ($emptyCounter > 0) {
58
                        $canon .= str_repeat("\r\n", $emptyCounter);
59
                        $emptyCounter = 0;
60
                    }
61
62 2
                    if ($space) {
63 2
                        $line .= ' ';
64 2
                        $canon .= ' ';
65 2
                        $space = false;
66
                    }
67
68 2
                    $line .= $string[$i];
69 2
                    $canon .= $string[$i];
70 2
                    break;
71
            }
72
        }
73
74 2
        return rtrim($canon, "\r\n") . "\r\n";
75
    }
76
77
    /**
78
     * @return string
79
     */
80 3
    public function name(): string
81
    {
82 3
        return 'relaxed';
83
    }
84
}