Completed
Push — master ( 7433a2...b425fd )
by Frederik
02:10
created

ConnectionNegotiation   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 57
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 7

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 5
lcom 1
cbo 7
dl 0
loc 57
c 0
b 0
f 0
rs 10
ccs 18
cts 18
cp 1

2 Methods

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