Passed
Push — master ( 705452...770324 )
by Mathieu
35:33 queued 25:29
created

Database   A

Complexity

Total Complexity 29

Size/Duplication

Total Lines 214
Duplicated Lines 0 %

Test Coverage

Coverage 79.45%

Importance

Changes 7
Bugs 1 Features 0
Metric Value
eloc 73
c 7
b 1
f 0
dl 0
loc 214
ccs 58
cts 73
cp 0.7945
rs 10
wmc 29

20 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 6 1
B connect() 0 38 6
A rollback() 0 3 1
A setConfigs() 0 5 1
A getConfig() 0 3 1
A getConfigParameters() 0 10 3
A configure() 0 12 3
A setConfig() 0 5 1
A fetch() 0 3 1
A beginTransaction() 0 3 1
A query() 0 8 1
A fetchColumn() 0 3 1
A __clone() 0 3 1
A getConfigs() 0 3 1
A fetchAll() 0 3 1
A fetchObject() 0 3 1
A commit() 0 3 1
A inTransaction() 0 3 1
A lastInsertId() 0 3 1
A getColumnCount() 0 3 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Suricate;
6
7
use Exception;
8
use PDO;
9
10
/**
11
 * Database extension for Suricate
12
 *
13
 * @package Suricate
14
 * @author  Mathieu LESNIAK <[email protected]>
15
 *
16
 * @property array $configs array of predefined DB configurations
17
 */
18
19
class Database extends Service
20
{
21
    use Traits\DatabaseMySQL;
22
    use Traits\DatabaseSQLite;
23
24
    protected $parametersList = ['configs'];
25
26
    /** @var string current configuration name */
27
    private $config;
28
    private $handler;
29
    private $statement;
30
31 32
    public function __construct()
32
    {
33 32
        parent::__construct();
34
35 32
        $this->configs = [];
36 32
        $this->handler = false;
37 32
    }
38
39 29
    // Force disconnect in case of cloning
40
    // (eg: `Suricate::Database(true)`)
41 29
    public function __clone()
42 29
    {
43 29
        $this->handler = false;
44
    }
45
46 29
    public function configure($parameters = [])
47
    {
48
        $dbConfs = [];
49 29
        foreach ($parameters as $name => $value) {
50 29
            if (is_array($value)) {
51 29
                $dbConfs[$name] = $value;
52
            } else {
53
                $dbConfs['default'][$name] = $value;
54
            }
55
        }
56
        $parameters = ['configs' => $dbConfs];
57
        parent::configure($parameters);
58 1
    }
59
60 1
    /**
61
     * Set Configurations list
62 1
     *
63
     * @return Database
64
     */
65
    public function setConfigs($configs)
66
    {
67
        $this->configs = $configs;
68
69
        return $this;
70 1
    }
71
72 1
    /**
73
     * Get configurations list
74
     *
75
     * @return array
76
     */
77
    public function getConfigs(): array
78
    {
79
        return $this->configs;
80
    }
81 1
82
    /**
83 1
     * Set current configuration used
84
     *
85 1
     * @param string $config configuration name
86
     * @return Database
87
     */
88
    public function setConfig(string $config): Database
89
    {
90
        $this->config = $config;
91
92
        return $this;
93 2
    }
94
95 2
    /**
96
     * Get current configuration name used
97
     *
98 23
     * @return string|null
99
     */
100 23
    public function getConfig()
101 7
    {
102
        return $this->config;
103
    }
104 23
105
    /**
106
     * Return database handler current config parameters
107 23
     *
108 23
     * @return array
109
     */
110
    public function getConfigParameters(): array
111 23
    {
112 23
        if ($this->config !== null && isset($this->configs[$this->config])) {
113 23
            $params = $this->configs[$this->config];
114
        } else {
115
            $confs = array_values($this->configs);
116
            $params = array_shift($confs);
117
        }
118
119
        return $params;
120
    }
121
122 23
    private function connect()
123 22
    {
124 22
        if ($this->handler !== false) {
125
            return;
126
        }
127
128
        $params = $this->getConfigParameters();
129 22
130
        $pdoAttributes = [\PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION];
131 1
        switch ($params['type']) {
132
            case 'mysql':
133
                $this->configurePDOMySQL(
134
                    $params,
135 22
                    $pdoDsn,
136 22
                    $pdoUsername,
137 22
                    $pdoPassword,
138
                    $pdoAttributes
139
                );
140
                break;
141
            case 'sqlite':
142 22
                $this->configurePDOSQLite(
143
                    $params,
144
                    $pdoDsn,
145
                    $pdoUsername,
146
                    $pdoPassword
147
                );
148
                break;
149
            default:
150
                throw new Exception('Unsupported PDO DB handler');
151 23
        }
152
153 23
        try {
154
            $this->handler = new PDO($pdoDsn, $pdoUsername, $pdoPassword);
155 22
            foreach ($pdoAttributes as $attributeKey => $attributeValue) {
156 22
                $this->handler->setAttribute($attributeKey, $attributeValue);
157
            }
158 22
        } catch (Exception $e) {
159
            throw new Exception("Cannot connect to database: " . $e->getMessage());
160
        }
161 4
    }
162
163 4
    /**
164
     * Execute a query against database.
165
     * Create a connection if not already alvailable
166 13
     * @param  string $sql        Query
167
     * @param  array  $parameters Parameters used in query
168 13
     * @return Database
169
     */
170
    public function query($sql, $parameters = [])
171 1
    {
172
        $this->connect();
173 1
174
        $this->statement = $this->handler->prepare($sql);
175
        $this->statement->execute($parameters);
176 1
177
        return $this;
178 1
    }
179
180
    public function fetchAll($mode = PDO::FETCH_ASSOC)
181
    {
182
        return $this->statement->fetchAll($mode);
183
    }
184
185
    public function fetch($mode = PDO::FETCH_ASSOC)
186 5
    {
187
        return $this->statement->fetch($mode);
188 5
    }
189
190
    public function fetchColumn($colNb = 0)
191
    {
192
        return $this->statement->fetchColumn($colNb);
193
    }
194
195
    public function fetchObject()
196
    {
197
        return $this->statement->fetch(PDO::FETCH_OBJ);
198
    }
199
200
    /**
201
     * Return the last inserted id
202
     *
203
     * @return string
204
     */
205
    public function lastInsertId(): string
206
    {
207
        return $this->handler->lastInsertId();
208
    }
209
210
    public function beginTransaction()
211 1
    {
212
        return $this->handler->beginTransaction();
213 1
    }
214
215
    public function commit(): bool
216
    {
217
        return $this->handler->commit();
218
    }
219
220
    public function rollback(): bool
221
    {
222
        return $this->handler->rollback();
223
    }
224
225
    public function inTransaction(): bool
226
    {
227
        return $this->handler->inTransaction();
228
    }
229
230
    public function getColumnCount()
231
    {
232
        return $this->statement->columnCount();
233
    }
234
}
235