Passed
Push — feature/migration ( 43ed9d )
by Mathieu
08:02
created

Database::setConfig()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 2
nc 1
nop 1
dl 0
loc 5
rs 10
c 0
b 0
f 0
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
    public function __construct()
32
    {
33
        parent::__construct();
34
35
        $this->configs = [];
36
        $this->handler = false;
37
    }
38
39
    public function configure($parameters = [])
40
    {
41
        $dbConfs = [];
42
        foreach ($parameters as $name => $value) {
43
            if (is_array($value)) {
44
                $dbConfs[$name] = $value;
45
            } else {
46
                $dbConfs['default'][$name] = $value;
47
            }
48
        }
49
        $parameters = ['configs' => $dbConfs];
50
        parent::configure($parameters);
51
    }
52
53
    /**
54
     * Set Configurations list
55
     *
56
     * @return Database
57
     */
58
    public function setConfigs($configs)
59
    {
60
        $this->configs = $configs;
61
62
        return $this;
63
    }
64
65
    /**
66
     * Get configurations list
67
     *
68
     * @return array
69
     */
70
    public function getConfigs(): array
71
    {
72
        return $this->configs;
73
    }
74
75
    /**
76
     * Set current configuration used
77
     *
78
     * @param string $config configuration name
79
     * @return Database
80
     */
81
    public function setConfig(string $config): Database
82
    {
83
        $this->config = $config;
84
85
        return $this;
86
    }
87
88
    /**
89
     * Get current configuration name used
90
     *
91
     * @return string|null
92
     */
93
    public function getConfig()
94
    {
95
        return $this->config;
96
    }
97
98
    /**
99
     * Return database handler current config parameters
100
     *
101
     * @return array
102
     */
103
    public function getConfigParameters(): array
104
    {
105
        if ($this->config !== null && isset($this->configs[$this->config])) {
106
            $params = $this->configs[$this->config];
107
        } else {
108
            $confs = array_values($this->configs);
109
            $params = array_shift($confs);
110
        }
111
112
        return $params;
113
    }
114
115
    private function connect()
116
    {
117
        if ($this->handler !== false) {
118
            return;
119
        }
120
121
        $params = $this->getConfigParameters();
122
123
        $pdoAttributes = [\PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION];
124
        switch ($params['type']) {
125
            case 'mysql':
126
                $this->configurePDOMySQL(
127
                    $params,
128
                    $pdoDsn,
129
                    $pdoUsername,
130
                    $pdoPassword,
131
                    $pdoAttributes
132
                );
133
                break;
134
            case 'sqlite':
135
                $this->configurePDOSQLite(
136
                    $params,
137
                    $pdoDsn,
138
                    $pdoUsername,
139
                    $pdoPassword
140
                );
141
                break;
142
            default:
143
                throw new Exception('Unsupported PDO DB handler');
144
        }
145
146
        try {
147
            $this->handler = new PDO($pdoDsn, $pdoUsername, $pdoPassword);
148
            foreach ($pdoAttributes as $attributeKey => $attributeValue) {
149
                $this->handler->setAttribute($attributeKey, $attributeValue);
150
            }
151
        } catch (Exception $e) {
152
            throw new Exception("Cannot connect to database");
153
        }
154
    }
155
156
    /**
157
     * Execute a query against database.
158
     * Create a connection if not already alvailable
159
     * @param  string $sql        Query
160
     * @param  array  $parameters Parameters used in query
161
     * @return Database
162
     */
163
    public function query($sql, $parameters = [])
164
    {
165
        $this->connect();
166
167
        $this->statement = $this->handler->prepare($sql);
168
        $this->statement->execute($parameters);
169
170
        return $this;
171
    }
172
173
    public function fetchAll($mode = PDO::FETCH_ASSOC)
174
    {
175
        return $this->statement->fetchAll($mode);
176
    }
177
178
    public function fetch($mode = PDO::FETCH_ASSOC)
179
    {
180
        return $this->statement->fetch($mode);
181
    }
182
183
    public function fetchColumn($colNb = 0)
184
    {
185
        return $this->statement->fetchColumn($colNb);
186
    }
187
188
    public function fetchObject()
189
    {
190
        return $this->statement->fetch(PDO::FETCH_OBJ);
191
    }
192
193
    /**
194
     * Return the last inserted id
195
     *
196
     * @return string
197
     */
198
    public function lastInsertId(): string
199
    {
200
        return $this->handler->lastInsertId();
201
    }
202
203
    public function beginTransaction()
204
    {
205
        return $this->handler->beginTransaction();
206
    }
207
208
    public function commit(): bool
209
    {
210
        return $this->handler->commit();
211
    }
212
213
    public function rollback(): bool
214
    {
215
        return $this->handler->rollback();
216
    }
217
218
    public function inTransaction(): bool
219
    {
220
        return $this->handler->inTransaction();
221
    }
222
223
    public function getColumnCount()
224
    {
225
        return $this->statement->columnCount();
226
    }
227
}
228