Completed
Pull Request — master (#42)
by Frederik
04:15 queued 01:07
created

TryTlsUpgradeNegotiation   A

Complexity

Total Complexity 4

Size/Duplication

Total Lines 53
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 8

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 4
lcom 1
cbo 8
dl 0
loc 53
ccs 18
cts 18
cp 1
rs 10
c 0
b 0
f 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 7 1
A negotiate() 0 23 3
1
<?php
2
declare(strict_types=1);
3
4
namespace Genkgo\Mail\Protocol\Imap\Negotiation;
5
6
use Genkgo\Mail\Exception\ConnectionInsecureException;
7
use Genkgo\Mail\Protocol\ConnectionInterface;
8
use Genkgo\Mail\Protocol\Imap\Client;
9
use Genkgo\Mail\Protocol\Imap\NegotiationInterface;
10
use Genkgo\Mail\Protocol\Imap\Request\CapabilityCommand;
11
use Genkgo\Mail\Protocol\Imap\Request\StartTlsCommand;
12
use Genkgo\Mail\Protocol\Imap\Response\Command\CapabilityCommandResponse;
13
use Genkgo\Mail\Protocol\Imap\Response\CompletionResult;
14
15
final class TryTlsUpgradeNegotiation implements NegotiationInterface
16
{
17
    /**
18
     * @var ConnectionInterface
19
     */
20
    private $connection;
21
    /**
22
     * @var int
23
     */
24
    private $crypto;
25
26
    /**
27
     * ConnectionNegotiation constructor.
28
     * @param ConnectionInterface $connection
29
     * @param int $crypto
30
     */
31 4
    public function __construct(
32
        ConnectionInterface $connection,
33
        int $crypto
34
    ) {
35 4
        $this->connection = $connection;
36 4
        $this->crypto = $crypto;
37 4
    }
38
39
40
    /**
41
     * @param Client $client
42
     * @throws ConnectionInsecureException
43
     */
44 3
    public function negotiate(Client $client): void
45
    {
46 3
        if (empty($this->connection->getMetaData(['crypto']))) {
47 2
            $responseList = $client->emit(new CapabilityCommand($client->newTag()));
48
49 2
            $capabilities = CapabilityCommandResponse::fromString($responseList->first()->getBody());
50
51
            $responseList
52 2
                ->last()
53 2
                ->assertCompletion(CompletionResult::ok())
54 2
                ->assertTagged();
55
56 2
            if ($capabilities->isAdvertising('STARTTLS')) {
57
                $client
58 1
                    ->emit(new StartTlsCommand($client->newTag()))
59 1
                    ->last()
60 1
                    ->assertCompletion(CompletionResult::ok())
61 1
                    ->assertTagged();
62
63 1
                $this->connection->upgrade($this->crypto);
64
            }
65
        }
66
    }
67
}