Completed
Pull Request — master (#32)
by Gawain
02:27
created

TryTlsUpgradeNegotiation::negotiate()   A

Complexity

Conditions 4
Paths 5

Size

Total Lines 20
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 11
CRAP Score 4.0092

Importance

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