Completed
Push — master ( cf00e0...a6178b )
by Frederik
02:20
created

SecureConnection::connect()   B

Complexity

Conditions 2
Paths 2

Size

Total Lines 27
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 27
rs 8.8571
c 0
b 0
f 0
cc 2
eloc 17
nc 2
nop 0
1
<?php
2
declare(strict_types=1);
3
4
namespace Genkgo\Mail\Protocol;
5
6
use Genkgo\Mail\Exception\ConnectionRefusedException;
7
8
/**
9
 * Class SecureConnection
10
 * @package Genkgo\Mail\Protocol
11
 * @codeCoverageIgnore
12
 */
13
final class SecureConnection extends AbstractConnection
14
{
15
    /**
16
     * @var string
17
     */
18
    private $host;
19
    /**
20
     * @var int
21
     */
22
    private $port;
23
    /**
24
     * @var SecureConnectionOptions
25
     */
26
    private $options;
27
28
    /**
29
     * PlainTcpConnection constructor.
30
     * @param string $host
31
     * @param int $port
32
     * @param SecureConnectionOptions $options
33
     */
34
    public function __construct(string $host, int $port, SecureConnectionOptions $options)
35
    {
36
        $this->host = $host;
37
        $this->port = $port;
38
        $this->options = $options;
39
    }
40
41
    /**
42
     * @param int $type
43
     */
44
    public function upgrade(int $type): void
45
    {
46
        throw new \InvalidArgumentException('Cannot connection, already secure');
47
    }
48
49
    /**
50
     *
51
     */
52
    public function connect(): void
53
    {
54
        $context = stream_context_create([
55
            'ssl' => [
56
                'crypto_method' => $this->options->getMethod(),
57
            ]
58
        ]);
59
60
        $resource = @stream_socket_client(
61
            'tls://' . $this->host . ':' . $this->port,
62
            $errorCode,
63
            $errorMessage,
64
            $this->options->getTimeout(),
65
            STREAM_CLIENT_CONNECT,
66
            $context
67
        );
68
69
        if ($resource === false) {
70
            throw new ConnectionRefusedException(
71
                sprintf('Could not create secure connection. %s.', $errorMessage),
72
                $errorCode
73
            );
74
        }
75
76
        $this->resource = $resource;
77
        $this->fireEvent('connect');
78
    }
79
}