Completed
Push — master ( 3c43e5...59d673 )
by James Ekow Abaka
08:14
created

Driver::disconnect()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 1

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 4
ccs 4
cts 4
cp 1
rs 10
cc 1
eloc 3
nc 1
nop 0
crap 1
1
<?php
2
3
namespace ntentan\atiaa;
4
5
use ntentan\config\Config;
6
use ntentan\atiaa\exceptions\DatabaseDriverException;
7
8
/**
9
 * A driver class for connecting to a specific database platform.
10
 * The Driver class is the main wrapper for atiaa. The driver class contains
11
 * an instance of PDO with which it performs its operations. Aside from wrapping
12
 * around PDO it also provides methods which makes it possible to quote strings
13
 * and identifiers in a platform independent fashion. The driver class is
14
 * responsible for loading the descriptors which are used for describing the
15
 * database schemas.
16
 */
17
abstract class Driver {
18
19
    /**
20
     * The internal PDO connection that is wrapped by this driver.
21
     * @var \PDO
22
     */
23
    private $pdo;
24
25
    /**
26
     * The default schema used in the connection.
27
     * @var string
28
     */
29
    protected $defaultSchema;
30
31
    /**
32
     * The connection parameters with which this connection was established.
33
     * @var array
34
     */
35
    protected $config;
36
37
    /**
38
     * An instance of the descriptor used internally.
39
     * @var \ntentan\atiaa\Descriptor
40
     */
41
    private $descriptor;
42
    private static $transactionCount = 0;
43
44
    /**
45
     * Creates a new instance of the Atiaa driver. This class is usually initiated
46
     * through the \ntentan\atiaa\Atiaa::getConnection() method. For example
47
     * to create a new instance of a connection to a mysql database.
48
     * 
49
     * ````php
50
     * use ntentan\atiaa\Driver;
51
     * 
52
     * \\ This automatically insitatiates the driver class
53
     * $driver = Driver::getConnection(
54
     *     array(
55
     *         'driver' => 'mysql',
56
     *         'user' => 'root',
57
     *         'password' => 'rootpassy',
58
     *         'host' => 'localhost',
59
     *         'dbname' => 'somedb'
60
     *     )
61
     * );
62
     * 
63
     * var_dump($driver->query("SELECT * FROM some_table");
64
     * var_dump($driver->describe());
65
     * ````
66
     * 
67
     * @param array<string> $config The configuration with which to connect to the database.
68
     */
69 33
    public function __construct($config = null) {
70 33
        $this->config = $config ? $config : Config::get('ntentan:db');
71 33
        $username = isset($this->config['user']) ? $this->config['user'] : null;
72 33
        $password = isset($this->config['password']) ? $this->config['password'] : null;
73
74
        try {
75 33
            $this->pdo = new \PDO(
76 33
                    $this->getDriverName() . ":" . $this->expand($this->config), $username, $password
77
            );
78 31
            $this->pdo->setAttribute(\PDO::ATTR_STRINGIFY_FETCHES, false);
79 31
            $this->pdo->setAttribute(\PDO::ATTR_EMULATE_PREPARES, false);
80 31
            $this->pdo->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
81 2
        } catch (\PDOException $e) {
82 2
            throw new DatabaseDriverException("PDO failed to connect: {$e->getMessage()}", $e);
83
        }
84 31
    }
85
86 20
    public function __destruct() {
87 20
        $this->disconnect();
88 20
    }
89
90
    /**
91
     * Close a connection to the database server.
92
     */
93 20
    public function disconnect() {
94 20
        $this->pdo = null;
95 20
        $this->pdo = new NullConnection();
96 20
    }
97
98
    /**
99
     * Get the default schema of the current connection.
100
     * @return string
101
     */
102 11
    public function getDefaultSchema() {
103 11
        return $this->defaultSchema;
104
    }
105
106
    /**
107
     * Use the PDO driver to quote a string.
108
     * @param type $string
109
     * @return string
110
     */
111 3
    public function quote($string) {
112 3
        return $this->pdo->quote($string);
113
    }
114
115
    /**
116
     * 
117
     * @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...
118
     * @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...
119
     */
120 25
    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...
121
        try {
122 25
            $rows = $statement->fetchAll(\PDO::FETCH_ASSOC);
123 25
            return $rows;
124
        } catch (\PDOException $e) {
125
            // Skip any exceptions from fetching rows
126
        }
127
    }
128
129
    /**
130
     * Pepare and execute a query, while binding data at the same time. Prevents
131
     * the writing of repetitive prepare and execute statements. This method
132
     * returns an array which contains the results of the query that was
133
     * executed. For queries which do not return any results a null is returned.
134
     * 
135
     * @todo Add a parameter to cache prepared statements so they can be reused easily.
136
     * 
137
     * @param string $query The query to be executed quoted in PDO style
138
     * @param false|array<mixed> $bindData The data to be bound to the query object.
139
     * @return array<mixed>
140
     */
141 29
    public function query($query, $bindData = false) {
142
        try {
143 29
            if (is_array($bindData)) {
144 22
                $statement = $this->pdo->prepare($query);
145 22
                $statement->execute($bindData);
146
            } else {
147 29
                $statement = $this->pdo->query($query);
148
            }
149 6
        } catch (\PDOException $e) {
150 3
            $boundData = json_encode($bindData);
151 3
            throw new DatabaseDriverException("{$e->getMessage()} [$query] [BOUND DATA:$boundData]");
152
        }
153 25
        $rows = $this->fetchRows($statement);
154 25
        $statement->closeCursor();
155 25
        return $rows;
156
    }
157
158
    /**
159
     * Runs a query but ensures that all identifiers are properly quoted by calling
160
     * the Driver::quoteQueryIdentifiers method on the query before executing it.
161
     * 
162
     * @param string $query
163
     * @param false|array<mixed> $bindData
164
     * @return array<mixed>
165
     */
166 16
    public function quotedQuery($query, $bindData = false) {
167 16
        return $this->query($this->quoteQueryIdentifiers($query), $bindData);
168
    }
169
170
    /**
171
     * Expands the configuration array into a format that can easily be passed
172
     * to PDO.
173
     * 
174
     * @param array $params The query parameters
175
     * @return string
176
     */
177 33
    private function expand($params) {
178 33
        unset($params['driver']);
179 33
        if (isset($params['file'])) {
180 33
            if ($params['file'] != '') {
181 10
                return $params['file'];
182
            }
183
        }
184
185 23
        $equated = array();
186 23
        foreach ($params as $key => $value) {
187 23
            if ($value == '') {
188 23
                continue;
189
            } else {
190 23
                $equated[] = "$key=$value";
191
            }
192
        }
193 23
        return implode(';', $equated);
194
    }
195
196
    /**
197
     * This method provides a system independent way of quoting identifiers in
198
     * queries. By default all identifiers can be quoted with double quotes (").
199
     * When a query quoted with double quotes is passed through this method the
200
     * output generated has the double quotes replaced with the quoting character
201
     * of the target database platform.
202
     * 
203
     * @param string $query
204
     * @return string
205
     */
206 19
    public function quoteQueryIdentifiers($query) {
207 19
        return preg_replace_callback(
208 19
                '/\"([a-zA-Z\_ ]*)\"/', function($matches) {
209 19
            return $this->quoteIdentifier($matches[1]);
210 19
        }, $query
211
        );
212
    }
213
214
    /**
215
     * Returns an array description of the schema represented by the connection.
216
     * The description returns contains information about `tables`, `columns`, `keys`,
217
     * `constraints`, `views` and `indices`.
218
     * 
219
     * @return array<mixed>
220
     */
221 6
    public function describe() {
222 6
        return $this->getDescriptor()->describe();
223
    }
224
225
    /**
226
     * Returns the description of a database table as an associative array.
227
     * 
228
     * @param string $table
229
     * @return array<mixed>
230
     */
231 7
    public function describeTable($table) {
232 7
        $table = explode('.', $table);
233 7
        if (count($table) > 1) {
234 1
            $schema = $table[0];
235 1
            $table = $table[1];
236
        } else {
237 6
            $schema = $this->getDefaultSchema();
238 6
            $table = $table[0];
239
        }
240 7
        return $this->getDescriptor()->describeTables($schema, array($table), true);
241
    }
242
243
    /**
244
     * A wrapper arround PDO's beginTransaction method which uses a static reference
245
     * counter to implement nested transactions.
246
     */
247 6
    public function beginTransaction() {
248 6
        if (self::$transactionCount++ === 0) {
249 6
            $this->pdo->beginTransaction();
250
        }
251 6
    }
252
253
    /**
254
     * A wrapper around PDO's commit transaction method which uses a static reference
255
     * counter to implement nested transactions.
256
     */
257 3
    public function commit() {
258 3
        if (--self::$transactionCount === 0) {
259 3
            $this->pdo->commit();
260
        }
261 3
    }
262
263
    /**
264
     * A wrapper around PDO's rollback transaction methd which rolls back all
265
     * activities performed since the first call to begin transaction. 
266
     * Unfortunately, transactions cannot be rolled back in a nested fashion.
267
     */
268 3
    public function rollback() {
269 3
        $this->pdo->rollBack();
270 3
        self::$transactionCount = 0;
271 3
    }
272
273
    /**
274
     * Return the underlying PDO object.
275
     * @return \PDO
276
     */
277 3
    public function getPDO() {
278 3
        return $this->pdo;
279
    }
280
281
    /**
282
     * Returns an instance of a descriptor for a given driver.
283
     * @return \atiaa\Descriptor
284
     */
285 13
    private function getDescriptor() {
286 13
        if (!is_object($this->descriptor)) {
287 13
            $descriptorClass = "\\ntentan\\atiaa\\descriptors\\" . ucfirst($this->config['driver']) . "Descriptor";
288 13
            $this->descriptor = new $descriptorClass($this);
289
        }
290 13
        return $this->descriptor;
291
    }
292
293
    /**
294
     * A wrapper around PDO's lastInsertId() method.
295
     * @return mixed
296
     */
297
    public function getLastInsertId() {
298
        return $this->pdo->lastInsertId();
299
    }
300
301
    /**
302
     * Specify the default schema to use in cases where a schema is not provided
303
     * as part of the table reference.
304
     * @param string $defaultSchema
305
     */
306
    public function setDefaultSchema($defaultSchema) {
307
        $this->defaultSchema = $defaultSchema;
308
    }
309
310
    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...
311
312
    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...
313
314
    /**
315
     * Returns a new instance of a driver based on the connection parameters 
316
     * passed to the method. The connection parameters are passed through an
317
     * associative array with the following keys.
318
     * 
319
     * driver 
320
     * : The name of the driver to use for the database connection. Supported
321
     *   drivers are `mysql` and `postgresql`. This parameter is required for
322
     *   all connections.
323
     * 
324
     * user
325
     * : The username to use for the database connection on platforms that 
326
     *   support it.
327
     * 
328
     * password
329
     * : The password associated to the user specified in the connection.
330
     * 
331
     * host
332
     * : The host name of the database server.
333
     * 
334
     * dbname
335
     * : The name of the default database to use after the connection to the 
336
     *   database is established.
337
     * 
338
     * @param array $config 
339
     * @return \ntentan\atiaa\Driver
340
     */
341
    /* public static function getConnection($config)
0 ignored issues
show
Unused Code Comprehensibility introduced by
57% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
342
      {
343
      if (is_string($config) && file_exists($config)) {
344
      require $config;
345
      } else if ($config['driver'] == '') {
346
      throw new DatabaseDriverException("Please specify a name for your database driver.");
347
      }
348
      try {
349
      $class = "\\ntentan\\atiaa\\drivers\\" . ucfirst($config['driver']) . "Driver";
350
      return new $class($config);
351
      } catch (\PDOException $e) {
352
      throw new DatabaseDriverException("PDO failed to connect: {$e->getMessage()}", $e);
353
      }
354
      } */
355
356 3
    public function setCleanDefaults($cleanDefaults) {
357 3
        $this->getDescriptor()->setCleanDefaults($cleanDefaults);
358 3
    }
359
360
}
361