Completed
Pull Request — master (#32)
by Gawain
01:35
created

TryRfc821UpgradeNegotiation::negotiate()   A

Complexity

Conditions 4
Paths 5

Size

Total Lines 20
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 12
CRAP Score 4

Importance

Changes 0
Metric Value
dl 0
loc 20
ccs 12
cts 12
cp 1
rs 9.2
c 0
b 0
f 0
cc 4
eloc 12
nc 5
nop 1
crap 4
1
<?php
2
declare(strict_types=1);
3
4
namespace Genkgo\Mail\Protocol\Smtp\Negotiation;
5
6
use Genkgo\Mail\Protocol\ConnectionInterface;
7
use Genkgo\Mail\Protocol\Smtp\Client;
8
use Genkgo\Mail\Protocol\Smtp\NegotiationInterface;
9
use Genkgo\Mail\Protocol\Smtp\Request\EhloCommand;
10
use Genkgo\Mail\Protocol\Smtp\Request\HeloCommand;
11
use Genkgo\Mail\Protocol\Smtp\Request\StartTlsCommand;
12
use Genkgo\Mail\Protocol\Smtp\Response\EhloResponse;
13
14
final class TryRfc821UpgradeNegotiation implements NegotiationInterface
15
{
16
    /**
17
     * @var ConnectionInterface
18
     */
19
    private $connection;
20
    /**
21
     * @var string
22
     */
23
    private $ehlo;
24
    /**
25
     * @var int
26
     */
27
    private $crypto;
28
29
    /**
30
     * @param ConnectionInterface $connection
31
     * @param string $ehlo
32
     * @param int $crypto
33
     */
34 4
    public function __construct(
35
        ConnectionInterface $connection,
36
        string $ehlo,
37
        int $crypto
38
    ) {
39 4
        $this->connection = $connection;
40 4
        $this->ehlo = $ehlo;
41 4
        $this->crypto = $crypto;
42 4
    }
43
44 3
    public function negotiate(Client $client): void
45
    {
46 3
        if (empty($this->connection->getMetaData(['crypto']))) {
47 3
            $reply = $client->request(new EhloCommand($this->ehlo));
48 3
            if ($reply->isCommandNotImplemented()) {
49 1
                $reply = $client->request(new HeloCommand($this->ehlo));
50
            }
51 3
            $reply->assertCompleted();
52
53 3
            $ehloResponse = new EhloResponse($reply);
54
55 3
            if ($ehloResponse->isAdvertising('STARTTLS')) {
56
                $client
57 1
                    ->request(new StartTlsCommand())
58 1
                    ->assertCompleted();
59
60 1
                $this->connection->upgrade($this->crypto);
61
            }
62
        }
63 3
    }
64
}
65