1 | <?php |
||
32 | trait Handler |
||
33 | { |
||
34 | /** @} */ |
||
35 | |||
36 | /** PDO connection to the database. */ |
||
37 | public $pdo; |
||
38 | |||
39 | /** \brief Table contaning bot users data in the SQL database. */ |
||
40 | public $user_table = 'User'; |
||
41 | |||
42 | /** |
||
43 | * \addtogroup Bot Bot |
||
44 | * @{ |
||
45 | */ |
||
46 | |||
47 | /** |
||
48 | * \brief Open a database connection using PDO. |
||
49 | * \details Provides a simple way to initialize a database connection |
||
50 | * and create a PDO instance. |
||
51 | * @param array $params Parameters for initialize connection. |
||
52 | * Index required: |
||
53 | * - <code>username</code> |
||
54 | * - <code>password</code> (can be an empty string) |
||
55 | * Optional index: |
||
56 | * - <code>dbname</code> |
||
57 | * - <code>adapter</code> <b>Default</b>: <code>mysql</code> |
||
58 | * - <code>host</code> <b>Default</b>: <code>localhost</code> |
||
59 | * - <code>options</code> (<i>Array of options passed when creating PDO object</i>) |
||
60 | * @return bool True when the connection is succefully created. |
||
61 | */ |
||
62 | public function connect(array $params) : bool |
||
63 | { |
||
64 | $params = $this->addDefaultValue($params); |
||
65 | $config = $this->getDns($params); |
||
66 | |||
67 | try { |
||
68 | $this->pdo = new \PDO($config, $params['username'], $params['password'], $params['options']); |
||
69 | $this->pdo->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION); |
||
70 | |||
71 | return true; |
||
72 | } catch (\PDOException $e) { |
||
73 | echo 'Unable to connect to database, an error occured:' . $e->getMessage(); |
||
74 | } |
||
75 | |||
76 | return false; |
||
77 | } |
||
78 | |||
79 | /** \brief (<i>Internal</i>) Add default connection value to parameter passed to PDO. |
||
80 | * @param array $params Parameter for PDO connection. |
||
81 | * @return array Parameter with defaults value. |
||
82 | */ |
||
83 | 1 | protected function addDefaultValue(array $params) : array |
|
88 | |||
89 | /** \brief (<i>Internal</i>) Returns a string that can passed to PDO as DNS parameter in order to open connection. |
||
90 | * @param array $params Array containing parameter of the connection |
||
91 | * @return string Parameters contained in array $params sanitized in a string that can be passed as DNS param of PDO object creation. |
||
92 | */ |
||
93 | 2 | protected function getDns($params) : string |
|
115 | |||
116 | /** |
||
117 | * \brief (<i>Internal</i>) Sanitize name of the user table depending on database used. |
||
118 | */ |
||
119 | protected function sanitizeUserTable() |
||
135 | |||
136 | /** @} */ |
||
137 | } |
||
138 |