Completed
Push — master ( 503b9d...92f54d )
by Frederik
03:38
created

ConnectionNegotiation   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 54
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 6

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 5
lcom 1
cbo 6
dl 0
loc 54
rs 10
c 0
b 0
f 0
ccs 17
cts 17
cp 1

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 6 1
A negotiate() 0 21 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\StartTlsCommand;
11
use Genkgo\Mail\Protocol\Smtp\Response\EhloResponse;
12
13
final class ConnectionNegotiation implements NegotiationInterface
14
{
15
    /**
16
     * @var ConnectionInterface
17
     */
18
    private $connection;
19
    /**
20
     * @var string
21
     */
22
    private $ehlo;
23
    /**
24
     * @var bool
25
     */
26
    private $insecureAllowed;
27
28
    /**
29
     * ConnectionNegotiation constructor.
30
     * @param ConnectionInterface $connection
31
     * @param string $ehlo
32
     * @param bool $insecureAllowed
33
     */
34 9
    public function __construct(ConnectionInterface $connection, string $ehlo, $insecureAllowed)
35
    {
36 9
        $this->connection = $connection;
37 9
        $this->ehlo = $ehlo;
38 9
        $this->insecureAllowed = $insecureAllowed;
39 9
    }
40
41
42
    /**
43
     * @param Client $client
44
     */
45 5
    public function negotiate(Client $client): void
46
    {
47 5
        $this->connection->receive();
48
49 5
        $reply = $client->request(new EhloCommand($this->ehlo));
50 5
        $reply->assertCompleted();
51
52 5
        $ehloResponse = new EhloResponse($reply);
53
54 5
        if ($ehloResponse->isAdvertising('STARTTLS')) {
55
            $client
56 1
                ->request(new StartTlsCommand())
57 1
                ->assertCompleted();
58
59 1
            $this->connection->upgrade(STREAM_CRYPTO_METHOD_TLS_CLIENT);
60
        }
61
62 5
        if (!$this->insecureAllowed && empty($this->connection->getMetadata(['crypto']))) {
63 1
            throw new \RuntimeException('Cannot establish secure connection');
64
        }
65
    }
66
}