Completed
Push — master ( 240a65...f42128 )
by James Ekow Abaka
02:20
created

Driver::__construct()   A

Complexity

Conditions 4
Paths 20

Size

Total Lines 15
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 20

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 15
ccs 0
cts 11
cp 0
rs 9.2
cc 4
eloc 11
nc 20
nop 1
crap 20
1
<?php
2
3
namespace ntentan\atiaa;
4
5
use ntentan\atiaa\exceptions\DatabaseDriverException;
6
use ntentan\panie\Container;
7
use ntentan\panie\exceptions\ResolutionException;
8
9
/**
10
 * A driver class for connecting to a specific database platform.
11
 * The Driver class is the main wrapper for atiaa. The driver class contains
12
 * an instance of PDO with which it performs its operations. Aside from wrapping
13
 * around PDO it also provides methods which makes it possible to quote strings
14
 * and identifiers in a platform independent fashion. The driver class is
15
 * responsible for loading the descriptors which are used for describing the
16
 * database schemas.
17
 */
18
abstract class Driver
19
{
20
21
    /**
22
     * The internal PDO connection that is wrapped by this driver.
23
     * @var \PDO
24
     */
25
    private $pdo;
26
    private $logger;
27
28
    /**
29
     * The default schema used in the connection.
30
     * @var string
31
     */
32
    protected $defaultSchema;
33
34
    /**
35
     * The connection parameters with which this connection was established.
36
     * @var array
37
     */
38
    protected $config;
39
40
    /**
41
     * An instance of the descriptor used internally.
42
     * @var \ntentan\atiaa\Descriptor
43
     */
44
    private $descriptor;
45
    private static $transactionCount = 0;
46
47
    /**
48
     * Creates a new instance of the Atiaa driver. This class is usually initiated
49
     * through the \ntentan\atiaa\Atiaa::getConnection() method. For example
50
     * to create a new instance of a connection to a mysql database.
51
     * 
52
     * ````php
53
     * use ntentan\atiaa\Driver;
54
     * 
55
     * \\ This automatically insitatiates the driver class
56
     * $driver = Driver::getConnection(
57
     *     array(
58
     *         'driver' => 'mysql',
59
     *         'user' => 'root',
60
     *         'password' => 'rootpassy',
61
     *         'host' => 'localhost',
62
     *         'dbname' => 'somedb'
63
     *     )
64
     * );
65
     * 
66
     * var_dump($driver->query("SELECT * FROM some_table");
67
     * var_dump($driver->describe());
68
     * ````
69
     * 
70
     * @param array<string> $config The configuration with which to connect to the database.
71
     */
72
    public function __construct(array $config)
73
    {
74
        $this->config = $config;
75
        $username = isset($this->config['user']) ? $this->config['user'] : null;
76
        $password = isset($this->config['password']) ? $this->config['password'] : null;
77
78
        try {
79
            $this->pdo = new \PDO($this->getDriverName() . ":" . $this->expand($this->config), $username, $password);
80
            $this->pdo->setAttribute(\PDO::ATTR_STRINGIFY_FETCHES, false);
81
            $this->pdo->setAttribute(\PDO::ATTR_EMULATE_PREPARES, false);
82
            $this->pdo->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
83
        } catch (\PDOException $e) {
84
            throw new DatabaseDriverException("PDO failed to connect: {$e->getMessage()}", $e);
85
        }
86
    }
87
88
    public function __destruct()
89
    {
90
        $this->disconnect();
91
    }
92
93
    /**
94
     * Close a connection to the database server.
95
     */
96
    public function disconnect()
97
    {
98
        $this->pdo = null;
99
        $this->pdo = new NullConnection();
100
    }
101
102
    /**
103
     * Get the default schema of the current connection.
104
     * @return string
105
     */
106
    public function getDefaultSchema()
107
    {
108
        return $this->defaultSchema;
109
    }
110
111
    /**
112
     * Use the PDO driver to quote a string.
113
     * @param type $string
114
     * @return string
115
     */
116
    public function quote($string)
117
    {
118
        return $this->pdo->quote($string);
119
    }
120
121
    /**
122
     * 
123
     * @param boolean $status
0 ignored issues
show
Bug introduced by
There is no parameter named $status. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
124
     * @param \PDOStatement  $result 
0 ignored issues
show
Bug introduced by
There is no parameter named $result. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
125
     */
126
    private function fetchRows($statement)
0 ignored issues
show
Documentation introduced by
The return type could not be reliably inferred; please add a @return annotation.

Our type inference engine in quite powerful, but sometimes the code does not provide enough clues to go by. In these cases we request you to add a @return annotation as described here.

Loading history...
127
    {
128
        try {
129
            $rows = $statement->fetchAll(\PDO::FETCH_ASSOC);
130
            return $rows;
131
        } catch (\PDOException $e) {
132
            // Skip any exceptions from fetching rows
133
        }
134
    }
135
136
    private function prepareQuery($query, $bindData)
137
    {
138
        $statement = $this->pdo->prepare($query);
139
        foreach ($bindData as $key => $value) {
140
            switch (gettype($value)) {
141
                case "integer":
142
                    $type = \PDO::PARAM_INT;
143
                    break;
144
                case "boolean":
145
                    $type = \PDO::PARAM_BOOL;
146
                    break;
147
                default:
148
                    $type = \PDO::PARAM_STR;
149
                    break;
150
            }
151
            $statement->bindValue(is_numeric($key) ? $key + 1 : $key, $value, $type);
152
        }
153
        return $statement;
154
    }
155
156
    /**
157
     * Pepare and execute a query, while binding data at the same time. Prevents
158
     * the writing of repetitive prepare and execute statements. This method
159
     * returns an array which contains the results of the query that was
160
     * executed. For queries which do not return any results a null is returned.
161
     * 
162
     * @todo Add a parameter to cache prepared statements so they can be reused easily.
163
     * 
164
     * @param string $query The query to be executed quoted in PDO style
165
     * @param false|array<mixed> $bindData The data to be bound to the query object.
166
     * @return array<mixed>
167
     */
168
    public function query($query, $bindData = [])
169
    {
170
        try {
171
            if (is_array($bindData)) {
172
                $statement = $this->prepareQuery($query, $bindData);
173
                $statement->execute();
174
            } else {
175
                $statement = $this->pdo->query($query);
176
            }
177
        } catch (\PDOException $e) {
178
            $boundData = json_encode($bindData);
179
            throw new DatabaseDriverException("{$e->getMessage()} [$query] [BOUND DATA:$boundData]");
180
        }
181
        if ($this->logger) {
182
            $this->logger->debug($query, $bindData);
183
        }
184
        $rows = $this->fetchRows($statement);
185
        $statement->closeCursor();
186
        return $rows;
187
    }
188
189
    /**
190
     * Runs a query but ensures that all identifiers are properly quoted by calling
191
     * the Driver::quoteQueryIdentifiers method on the query before executing it.
192
     * 
193
     * @param string $query
194
     * @param false|array<mixed> $bindData
195
     * @return array<mixed>
196
     */
197
    public function quotedQuery($query, $bindData = false)
198
    {
199
        return $this->query($this->quoteQueryIdentifiers($query), $bindData);
200
    }
201
202
    /**
203
     * Expands the configuration array into a format that can easily be passed
204
     * to PDO.
205
     * 
206
     * @param array $params The query parameters
207
     * @return string
208
     */
209
    private function expand($params)
210
    {
211
        unset($params['driver']);
212
        if (isset($params['file'])) {
213
            if ($params['file'] != '') {
214
                return $params['file'];
215
            }
216
        }
217
218
        $equated = array();
219
        foreach ($params as $key => $value) {
220
            if ($value == '') {
221
                continue;
222
            } else {
223
                $equated[] = "$key=$value";
224
            }
225
        }
226
        return implode(';', $equated);
227
    }
228
229
    /**
230
     * This method provides a system independent way of quoting identifiers in
231
     * queries. By default all identifiers can be quoted with double quotes (").
232
     * When a query quoted with double quotes is passed through this method the
233
     * output generated has the double quotes replaced with the quoting character
234
     * of the target database platform.
235
     * 
236
     * @param string $query
237
     * @return string
238
     */
239
    public function quoteQueryIdentifiers($query)
240
    {
241
        return preg_replace_callback(
242
                '/\"([a-zA-Z\_ ]*)\"/', function($matches) {
243
            return $this->quoteIdentifier($matches[1]);
244
        }, $query
245
        );
246
    }
247
248
    /**
249
     * Returns an array description of the schema represented by the connection.
250
     * The description returns contains information about `tables`, `columns`, `keys`,
251
     * `constraints`, `views` and `indices`.
252
     * 
253
     * @return array<mixed>
254
     */
255
    public function describe()
256
    {
257
        return $this->getDescriptor()->describe();
258
    }
259
260
    /**
261
     * Returns the description of a database table as an associative array.
262
     * 
263
     * @param string $table
264
     * @return array<mixed>
265
     */
266
    public function describeTable($table)
267
    {
268
        $table = explode('.', $table);
269
        if (count($table) > 1) {
270
            $schema = $table[0];
271
            $table = $table[1];
272
        } else {
273
            $schema = $this->getDefaultSchema();
274
            $table = $table[0];
275
        }
276
        return $this->getDescriptor()->describeTables($schema, array($table), true);
277
    }
278
279
    /**
280
     * A wrapper arround PDO's beginTransaction method which uses a static reference
281
     * counter to implement nested transactions.
282
     */
283
    public function beginTransaction()
284
    {
285
        if (self::$transactionCount++ === 0) {
286
            $this->pdo->beginTransaction();
287
        }
288
    }
289
290
    /**
291
     * A wrapper around PDO's commit transaction method which uses a static reference
292
     * counter to implement nested transactions.
293
     */
294
    public function commit()
295
    {
296
        if (--self::$transactionCount === 0) {
297
            $this->pdo->commit();
298
        }
299
    }
300
301
    /**
302
     * A wrapper around PDO's rollback transaction methd which rolls back all
303
     * activities performed since the first call to begin transaction. 
304
     * Unfortunately, transactions cannot be rolled back in a nested fashion.
305
     */
306
    public function rollback()
307
    {
308
        $this->pdo->rollBack();
309
        self::$transactionCount = 0;
310
    }
311
312
    /**
313
     * Return the underlying PDO object.
314
     * @return \PDO
315
     */
316
    public function getPDO()
317
    {
318
        return $this->pdo;
319
    }
320
321
    /**
322
     * Returns an instance of a descriptor for a given driver.
323
     * @return \atiaa\Descriptor
324
     */
325
    private function getDescriptor()
326
    {
327
        if (!is_object($this->descriptor)) {
328
            $descriptorClass = "\\ntentan\\atiaa\\descriptors\\" . ucfirst($this->config['driver']) . "Descriptor";
329
            $this->descriptor = new $descriptorClass($this);
330
        }
331
        return $this->descriptor;
332
    }
333
334
    /**
335
     * A wrapper around PDO's lastInsertId() method.
336
     * @return mixed
337
     */
338
    public function getLastInsertId()
339
    {
340
        return $this->pdo->lastInsertId();
341
    }
342
343
    /**
344
     * Specify the default schema to use in cases where a schema is not provided
345
     * as part of the table reference.
346
     * @param string $defaultSchema
347
     */
348
    public function setDefaultSchema($defaultSchema)
349
    {
350
        $this->defaultSchema = $defaultSchema;
351
    }
352
353
    abstract protected function getDriverName();
0 ignored issues
show
Documentation introduced by
For interfaces and abstract methods it is generally a good practice to add a @return annotation even if it is just @return void or @return null, so that implementors know what to do in the overridden method.

For interface and abstract methods, it is impossible to infer the return type from the immediate code. In these cases, it is generally advisible to explicitly annotate these methods with a @return doc comment to communicate to implementors of these methods what they are expected to return.

Loading history...
354
355
    abstract public function quoteIdentifier($identifier);
0 ignored issues
show
Documentation introduced by
For interfaces and abstract methods it is generally a good practice to add a @return annotation even if it is just @return void or @return null, so that implementors know what to do in the overridden method.

For interface and abstract methods, it is impossible to infer the return type from the immediate code. In these cases, it is generally advisible to explicitly annotate these methods with a @return doc comment to communicate to implementors of these methods what they are expected to return.

Loading history...
356
357
    public function setCleanDefaults($cleanDefaults)
358
    {
359
        $this->getDescriptor()->setCleanDefaults($cleanDefaults);
360
    }
361
362
}
363