1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace PhpBotFramework\Database; |
4
|
|
|
|
5
|
|
|
use PDOException; |
6
|
|
|
|
7
|
|
|
trait Handler { |
8
|
|
|
|
9
|
|
|
/** |
10
|
|
|
* \addtogroup Bot Bot |
11
|
|
|
* @{ |
12
|
|
|
*/ |
13
|
|
|
|
14
|
|
|
/** Pdo connection to the database. */ |
15
|
|
|
public $pdo; |
16
|
|
|
|
17
|
|
|
/** |
18
|
|
|
* \brief Open a database connection using PDO. |
19
|
|
|
* \details Provides a simpler way to initialize a database connection |
20
|
|
|
* and create a PDO instance. |
21
|
|
|
* @param $params Parameters for initialize connection. |
22
|
|
|
* @return True on success. |
23
|
|
|
*/ |
24
|
|
|
public function connect($params) { |
25
|
|
|
try { |
26
|
|
|
$config = $this->stringify($this->mergeWithDefaults($params)); |
27
|
|
|
|
28
|
|
|
$this->pdo = new \PDO($config, $params['username'], $params['password']); |
29
|
|
|
$this->pdo->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION); |
30
|
|
|
|
31
|
|
|
return true; |
32
|
|
|
} catch (PDOException $e) { |
33
|
|
|
echo 'Unable to connect to database, an error occured:' . $e->getMessage(); |
34
|
|
|
} |
35
|
|
|
|
36
|
|
|
return false; |
37
|
|
|
} |
38
|
|
|
|
39
|
|
|
protected function mergeWithDefaults($params) { |
40
|
|
|
$DEFAULTS = [ 'adapter' => 'mysql', 'host' => 'localhost' ]; |
41
|
|
|
return array_merge($DEFAULTS, $params); |
42
|
|
|
} |
43
|
|
|
|
44
|
|
|
/** \brief Returns a string that can passed to PDO in order to open connection. */ |
45
|
|
|
protected function stringify($params) : string { |
46
|
|
|
$response = $params['adapter'] . ':'; |
47
|
|
|
$fields = []; |
48
|
|
|
|
49
|
|
|
foreach ($params as $field => $value) { |
50
|
|
|
/** |
51
|
|
|
*Check if the current field matches one of the fields |
52
|
|
|
* that are passed to PDO in another way and so don't need |
53
|
|
|
* to be included in the string. |
54
|
|
|
*/ |
55
|
|
|
if (in_array($field, ['adapter', 'username', 'password'])) { |
56
|
|
|
unset($params[$field]); |
57
|
|
|
continue; |
58
|
|
|
} |
59
|
|
|
|
60
|
|
|
array_push($fields, $field . '=' . $value); |
61
|
|
|
} |
62
|
|
|
|
63
|
|
|
return $response . join(';', $fields); |
64
|
|
|
} |
65
|
|
|
|
66
|
|
|
/** @} */ |
67
|
|
|
|
68
|
|
|
} |
69
|
|
|
|