SMTPDotStuffingFilter   A
last analyzed

Complexity

Total Complexity 2

Size/Duplication

Total Lines 40
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 1
Bugs 0 Features 1
Metric Value
eloc 16
dl 0
loc 40
ccs 17
cts 17
cp 1
rs 10
c 1
b 0
f 1
wmc 2

1 Method

Rating   Name   Duplication   Size   Complexity  
A filter() 0 23 2
1
<?php
2
3
namespace Kodus\Mail\SMTP;
4
5
use php_user_filter as Filter;
6
7 1
stream_filter_register(SMTPDotStuffingFilter::FILTER_NAME, SMTPDotStuffingFilter::class);
8
9
/**
10
 * This class implements a PHP stream filter that applies "dot-stuffing" to the stream contents.
11
 *
12
 * The transmission of the body of a mail message under the SMTP protocol is initiated with a `DATA` command
13
 * after which it is transmitted verbatim line by line and is terminated with an end-of-data sequence.
14
 *
15
 * This sequence consists of a new-line (`<CR><LF>`), a single full stop (`"."`), followed by another new-line.
16
 *
17
 * Since a message body can contain a line with just a period as part of the text, the client sends two periods
18
 * every time a line starts with a period; correspondingly, the server replaces every sequence of two periods
19
 * at the beginning of a line with a single one.
20
 */
21
class SMTPDotStuffingFilter extends Filter
22
{
23
    const FILTER_NAME = "smtp.dot_stuffing";
24
25
    /**
26
     * @var string
27
     */
28
    private $last_two_bytes = "";
29
30
    /**
31
     * @param resource $in
32
     * @param resource $out
33
     * @param int      &$consumed
34
     * @param bool     $closing
35
     *
36
     * @return int
37
     */
38 3
    public function filter($in, $out, &$consumed, $closing): int
39
    {
40 3
        while ($bucket = stream_bucket_make_writeable($in)) {
41 3
            $data = substr(
42 3
                str_replace(
43 3
                    "\r\n.",
44 3
                    "\r\n..",
45 3
                    $this->last_two_bytes . $bucket->data
46 3
                ),
47 3
                strlen($this->last_two_bytes)
48 3
            );
49
50 3
            $this->last_two_bytes = substr($this->last_two_bytes . $bucket->data, -2);
51
52 3
            $consumed += $bucket->datalen;
53
54 3
            $bucket->data = $data;
55 3
            $bucket->datalen = strlen($data);
56
57 3
            stream_bucket_append($out, $bucket);
58 3
        }
59
60 3
        return PSFS_PASS_ON;
61
    }
62
}
63