TCPConfigurationTrait::buildConnection()   A
last analyzed

Complexity

Conditions 4
Paths 5

Size

Total Lines 10
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 6
dl 0
loc 10
rs 10
c 0
b 0
f 0
cc 4
nc 5
nop 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Cozy\Database\Relational\Configuration;
6
7
use Cozy\Database\Relational\Connection;
8
use Cozy\Database\Relational\Exception;
9
10
trait TCPConfigurationTrait
11
{
12
    /** @var \PDO */
13
    private $pdo;
14
    private $dsn;
15
    private $host;
16
    private $port;
17
    private $username;
18
    private $password;
19
    private $options = [
20
        \PDO::ATTR_TIMEOUT => 1,
21
    ];
22
23
    public function isValid(): bool
24
    {
25
        $op = @fsockopen($this->host, $this->port, $errno, $errstr, 0.5);
26
27
        if (!$op) {
0 ignored issues
show
introduced by
$op is of type resource, thus it always evaluated to false.
Loading history...
28
            return false;
29
        }
30
31
        fclose($op);
32
33
        try {
34
            $this->pdo = new \PDO($this->dsn, $this->username, $this->password, $this->options);
35
            return true;
36
        } catch (\PDOException $e) {
37
            return false;
38
        }
39
    }
40
41
    public function buildConnection(): Connection
42
    {
43
        try {
44
            if (!isset($this->pdo) || !($this->pdo instanceof \PDO)) {
45
                $this->pdo = new \PDO($this->dsn, $this->username, $this->password, $this->options);
46
            }
47
48
            return new Connection($this->pdo);
49
        } catch (\PDOException $e) {
50
            throw new Exception($e->getMessage(), $e->getCode(), $e->errorInfo);
51
        }
52
    }
53
}
54