Completed
Pull Request — master (#18)
by Frederik
03:05
created

CanonicalizeBodyRelaxed   A

Complexity

Total Complexity 12

Size/Duplication

Total Lines 78
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 0

Importance

Changes 0
Metric Value
dl 0
loc 78
c 0
b 0
f 0
wmc 12
lcom 0
cbo 0
rs 10

2 Methods

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