Completed
Pull Request — master (#18)
by Frederik
01:29
created

RelaxedCanonicalizeBody   A

Complexity

Total Complexity 11

Size/Duplication

Total Lines 68
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 0

Test Coverage

Coverage 0%

Importance

Changes 0
Metric Value
dl 0
loc 68
c 0
b 0
f 0
wmc 11
lcom 0
cbo 0
ccs 0
cts 50
cp 0
rs 10

1 Method

Rating   Name   Duplication   Size   Complexity  
C canonicalize() 0 60 11
1
<?php
2
declare(strict_types=1);
3
4
namespace Genkgo\Mail\Header\Dkim;
5
6
final class RelaxedCanonicalizeBody implements CanonicalizeBodyInterface
0 ignored issues
show
Bug introduced by
There is one abstract method getName in this class; you could implement it, or declare this class as abstract.
Loading history...
7
{
8
9
    /**
10
     * @param string $string
11
     * @return string
12
     */
13
    public function canonicalize(string $string): string
14
    {
15
        $length = strlen($string);
16
        $canon = '';
17
        $lastChar = null;
18
        $space = false;
19
        $line = '';
20
        $emptyCounter = 0;
21
22
        for ($i = 0; $i < $length; ++$i) {
23
            switch ($string[$i]) {
24
                case "\r":
25
                    $lastChar = "\r";
26
                    break;
27
28
                case "\n":
29
                    if ($lastChar === "\r") {
30
                        $space = false;
31
32
                        if ($line === '') {
33
                            ++$emptyCounter;
34
                        } else {
35
                            $line = '';
36
                            $canon .= "\r\n";
37
                        }
38
                    } else {
39
                        throw new \RuntimeException('This should never happen');
40
                    }
41
42
                    break;
43
44
                case ' ':
45
                case "\t":
46
                    $space = true;
47
                    break;
48
49
                default:
50
                    if ($emptyCounter > 0) {
51
                        $canon .= str_repeat("\r\n", $emptyCounter);
52
                        $emptyCounter = 0;
53
                    }
54
55
                    if ($space) {
56
                        $line .= ' ';
57
                        $canon .= ' ';
58
                        $space = false;
59
                    }
60
61
                    $line .= $string[$i];
62
                    $canon .= $string[$i];
63
                    break;
64
            }
65
        }
66
67
        if ($line === '') {
68
            $canon .= "\r\n";
69
        }
70
71
        return $canon;
72
    }
73
}