Completed
Pull Request — master (#17)
by Frederik
02:00
created

DataCapability::manifest()   B

Complexity

Conditions 5
Paths 9

Size

Total Lines 29
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 30

Importance

Changes 0
Metric Value
dl 0
loc 29
c 0
b 0
f 0
ccs 0
cts 23
cp 0
rs 8.439
cc 5
eloc 17
nc 9
nop 2
crap 30
1
<?php
2
declare(strict_types=1);
3
4
namespace Genkgo\Mail\Protocol\Smtp\Capability;
5
6
use Genkgo\Mail\GenericMessage;
7
use Genkgo\Mail\Protocol\ConnectionInterface;
8
use Genkgo\Mail\Protocol\Smtp\BackendInterface;
9
use Genkgo\Mail\Protocol\Smtp\CapabilityInterface;
10
use Genkgo\Mail\Protocol\Smtp\Session;
11
12
final class DataCapability implements CapabilityInterface
13
{
14
    /**
15
     * @var BackendInterface
16
     */
17
    private $backend;
18
19
    /**
20
     * DataCapability constructor.
21
     * @param BackendInterface $backend
22
     */
23
    public function __construct(BackendInterface $backend)
24
    {
25
        $this->backend = $backend;
26
    }
27
28
    /**
29
     * @param ConnectionInterface $connection
30
     * @param Session $session
31
     * @return Session
32
     */
33
    public function manifest(ConnectionInterface $connection, Session $session): Session
34
    {
35
        $connection->send('354 Enter message, ending with "." on a line by itself');
36
        $data = [];
37
38
        while (true) {
39
            $line = $connection->receive();
40
41
            if ($line === '.') {
42
                break;
43
            }
44
45
            $data[] = $line;
46
        }
47
48
        try {
49
            $message = GenericMessage::fromString(implode("\r\n", $data));
50
        } catch (\InvalidArgumentException $e) {
51
            $connection->send('500 Malformed message');
52
            return $session;
53
        }
54
55
        foreach ($session->getRecipients() as $recipient) {
56
            $this->backend->store($recipient, $message);
57
        }
58
59
        $connection->send('250 Message received, queue for delivering');
60
        return (clone $session)->withMessage($message);
61
    }
62
63
    /**
64
     * @return string
65
     */
66
    public function advertise(): string
67
    {
68
        return 'DATA';
69
    }
70
}