Passed
Branch v0.1 (e1d14a)
by Nestor
01:33
created

SQLiteConfiguration::buildConnection()   A

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
class SQLiteConfiguration implements ConfigurationInterface
11
{
12
    private $dsn;
13
    private $pdo_options;
14
    private $pdo;
15
16
    public function __construct(string $path, array $pdo_options = [])
17
    {
18
        if ($path == 'memory') {
19
            $this->dsn = 'sqlite::memory:';
20
        } else {
21
            $this->dsn = "sqlite:{$path}";
22
        }
23
24
        $this->pdo_options = $pdo_options;
25
    }
26
27
    public function isValid(): bool
28
    {
29
        try {
30
            $this->pdo = new \PDO($this->dsn, null, null, $this->pdo_options);
31
            return true;
32
        } catch (\PDOException $e) {
33
            return false;
34
        }
35
    }
36
37
    public function buildConnection(): Connection
38
    {
39
        try {
40
            if (!isset($this->pdo) || !($this->pdo instanceof \PDO)) {
41
                $this->pdo = new \PDO($this->dsn, null, null, $this->pdo_options);
42
            }
43
44
            return new Connection($this->pdo);
45
        } catch (\PDOException $e) {
46
            throw new Exception($e->getMessage(), $e->getCode(), $e->errorInfo);
47
        }
48
    }
49
}
50