Completed
Pull Request — master (#15)
by Mathieu
16:37 queued 14:28
created

Database::configure()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 12
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 3.0175

Importance

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