Completed
Push — master ( 4e1c03...e292dd )
by Danilo
03:28
created

Database::getDns()   B

Complexity

Conditions 5
Paths 3

Size

Total Lines 22
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 10
CRAP Score 5

Importance

Changes 0
Metric Value
dl 0
loc 22
ccs 10
cts 10
cp 1
rs 8.6737
c 0
b 0
f 0
cc 5
eloc 10
nc 3
nop 1
crap 5
1
<?php
2
3
/*
4
 * This file is part of the PhpBotFramework.
5
 *
6
 * PhpBotFramework is free software: you can redistribute it and/or modify
7
 * it under the terms of the GNU Lesser General Public License as
8
 * published by the Free Software Foundation, version 3.
9
 *
10
 * PhpBotFramework is distributed in the hope that it will be useful, but
11
 * WITHOUT ANY WARRANTY; without even the implied warranty of
12
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13
 * Lesser General Public License for more details.
14
 *
15
 * You should have received a copy of the GNU Lesser General Public License
16
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
17
 */
18
19
namespace PhpBotFramework\Database;
20
21
use PhpBotFramework\BasicBot;
22
use PhpBotFramework\Exceptions\BotException;
23
24 1
define('PDO_DEFAULT_ADAPTER', 'mysql');
25
26
/** \class Database Database connection handler
27
 */
28
class Database
29
{
30
    use User;
31
32
    /** @} */
33
34
    private $bot;
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 Database
44
     * @{
45
     */
46
47
    /**
48
     * @internal
49
     * \brief Create a Database handler object.
50
     * @param BasicBot $bot Reference to the bot that use this object.
51
     */
52 1
    public function __construct(BasicBot &$bot)
53
    {
54 1
        $this->bot = $bot;
55 1
    }
56
57
    /**
58
     * \brief Open a database connection using PDO.
59
     * \details Provides a simple way to initialize a database connection
60
     * and create a PDO instance.
61
     * @param array $params Parameters for initialize connection.
62
     * Index required:
63
     *     - <code>username</code>
64
     *     - <code>password</code> (can be an empty string)
65
     * Optional index:
66
     *     - <code>dbname</code>
67
     *     - <code>adapter</code> <b>Default</b>: <code>mysql</code>
68
     *     - <code>host</code> <b>Default</b>: <code>localhost</code>
69
     *     - <code>options</code> (<i>Array of options passed when creating PDO object</i>)
70
     * @return bool True when the connection is succefully created.
71
     */
72
    public function connect(array $params) : bool
73
    {
74
        $params = $this->addDefaultValue($params);
75
        $config = $this->getDns($params);
76
77
        try {
78
            $this->pdo = new \PDO($config, $params['username'], $params['password'], $params['options']);
79
            $this->pdo->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
80
81
            return true;
82
        } catch (\PDOException $e) {
83
            echo 'Unable to connect to database, an error occured:' . $e->getMessage();
84
        }
85
86
        return false;
87
    }
88
89
    /**
90
     * @internal
91
     * \brief Add default connection value to parameter passed to PDO.
92
     * @param array $params Parameter for PDO connection.
93
     * @return array Parameter with defaults value.
94
     */
95 1
    public static function addDefaultValue(array $params) : array
96
    {
97 1
        static $defaults = [ 'adapter' => PDO_DEFAULT_ADAPTER, 'host' => 'localhost', 'options' => [] ];
98 1
        return array_merge($defaults, $params);
99
    }
100
101
    /**
102
     * @internal
103
     * \brief Returns a string that can passed to PDO as DNS parameter in order to open connection.
104
     * @param array $params Array containing parameter of the connection
105
     * @return string Parameters contained in array $params sanitized in a string that can be passed as DNS param of PDO object creation.
106
     */
107 2
    public static function getDns($params) : string
108
    {
109 2
        $response = $params['adapter'] . ':';
110 2
        unset($params['adapter']);
111 2
        $fields = [];
112
113 2
        foreach ($params as $field => $value) {
114
            /**
115
             *Check if the current field matches one of the fields
116
             * that are passed to PDO in another way and so don't need
117
             * to be included in the string.
118
             */
119 2
            if ($field === 'username' || $field === 'password' || $field === 'options') {
120 1
                unset($params[$field]);
121 1
                continue;
122
            }
123
124 2
            $fields[] = $field . '=' . $value;
125
        }
126
127 2
        return $response . join(';', $fields);
128
    }
129
130
    /**
131
     * @internal
132
     * \brief Sanitize name of the user table depending on database used.
133
     */
134
    protected function sanitizeUserTable()
135
    {
136
        static $is_sanitized = false;
137
138
        if ($is_sanitized) {
139
            return;
140
        }
141
142
        if ($this->pdo->getAttribute(\PDO::ATTR_DRIVER_NAME) === 'mysql') {
143
            $this->user_table = "`$this->user_table`";
144
        } else {
145
            $this->user_table = '"' . $this->user_table . '"';
146
        }
147
148
        $is_sanitized = true;
149
    }
150
151
    /** @} */
152
}
153