GenericConnectionProvider   A
last analyzed

Complexity

Total Complexity 4

Size/Duplication

Total Lines 48
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
eloc 14
dl 0
loc 48
ccs 12
cts 12
cp 1
rs 10
c 0
b 0
f 0
wmc 4

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 6 1
A getConnection() 0 7 2
A initializeConnection() 0 3 1
1
<?php
2
3
namespace Simply\Database\Connection\Provider;
4
5
/**
6
 * A generic lazy loading connector that can take any kind of PDO data source name.
7
 * @author Riikka Kalliomäki <[email protected]>
8
 * @copyright Copyright (c) 2018 Riikka Kalliomäki
9
 * @license http://opensource.org/licenses/mit-license.php MIT License
10
 */
11
class GenericConnectionProvider implements ConnectionProvider
12
{
13
    /** @var string The data source name for the PDO connection */
14
    private $dsn;
15
16
    /** @var string The username for the PDO connection */
17
    private $username;
18
19
    /** @var string The password for the PDO connection */
20
    private $password;
21
22
    /** @var array Initial PDO options provided when initializing the connection */
23
    private $options;
24
25
    /** @var \PDO The active PDO connection */
26
    private $pdo;
27
28
    /**
29
     * GenericConnectionProvider constructor.
30
     * @param string $dsn The data source name for the PDO connection
31
     * @param string $username The username for the PDO connection
32
     * @param string $password The password for the PDO connection
33
     * @param array $options Initial PDO options provided when initializing the connection
34
     */
35 25
    public function __construct(string $dsn, string $username, string $password, array $options)
36
    {
37 25
        $this->dsn = $dsn;
38 25
        $this->username = $username;
39 25
        $this->password = $password;
40 25
        $this->options = $options;
41 25
    }
42
43 25
    public function getConnection(): \PDO
44
    {
45 25
        if (!isset($this->pdo)) {
46 25
            $this->pdo = $this->initializeConnection();
47
        }
48
49 25
        return $this->pdo;
50
    }
51
52
    /**
53
     * Initializes the PDO connection when first requested.
54
     * @return \PDO The initialized PDO connection
55
     */
56 25
    protected function initializeConnection(): \PDO
57
    {
58 25
        return new \PDO($this->dsn, $this->username, $this->password, $this->options);
59
    }
60
}
61