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

ConnectionNegotiation::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 6
rs 9.4285
c 0
b 0
f 0
ccs 5
cts 5
cp 1
cc 1
eloc 4
nc 1
nop 3
crap 1
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
}