Completed
Push — master ( 5dd80a...d7f7fe )
by Danilo
45:43
created

Handler::sanitizeUserTable()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 2.032

Importance

Changes 0
Metric Value
dl 0
loc 9
ccs 4
cts 5
cp 0.8
rs 9.6666
c 0
b 0
f 0
cc 2
eloc 5
nc 2
nop 0
crap 2.032
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\Exceptions\BotException;
22
23
define('PDO_DEFAULT_ADAPTER', 'mysql');
24
25
/**
26
 * \addtogroup Modules
27
 * @{
28
 */
29
30
/** \class Handler Handler Database connection handler
31
 */
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 1
    public function connect(array $params) : bool
63
    {
64 1
        $params = $this->addDefaultValue($params);
65 1
        $config = $this->getDns($params);
66
67
        try {
68 1
            $this->pdo = new \PDO($config, $params['username'], $params['password'], $params['options']);
69 1
            $this->pdo->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
70
71 1
            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 2
    protected function addDefaultValue(array $params) : array
84
    {
85 2
        static $defaults = [ 'adapter' => PDO_DEFAULT_ADAPTER, 'host' => 'localhost', 'options' => [] ];
86 2
        return array_merge($defaults, $params);
87
    }
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 3
    protected function getDns($params) : string
94
    {
95 3
        $response = $params['adapter'] . ':';
96 3
        unset($params['adapter']);
97 3
        $fields = [];
98
99 3
        foreach ($params as $field => $value) {
100
            /**
101
             *Check if the current field matches one of the fields
102
             * that are passed to PDO in another way and so don't need
103
             * to be included in the string.
104
             */
105 3
            if ($field === 'username' || $field === 'password' || $field === 'options') {
106 2
                unset($params[$field]);
107 2
                continue;
108
            }
109
110 3
            $fields[] = $field . '=' . $value;
111
        }
112
113 3
        return $response . join(';', $fields);
114
    }
115
116
    /**
117
     * \brief (<i>Internal</i>) Sanitize name of the user table depending on database used.
118
     */
119 2
    protected function sanitizeUserTable() {
120 2
        if ($this->pdo->getAttribute(\PDO::ATTR_DRIVER_NAME) === 'mysql')
121
        {
122
            $this->user_table = "`$this->user_table`";
123
        } else
124
        {
125 2
            $this->user_table = '"' . $this->user_table . '"';
126
        }
127 2
    }
128
129
    /** @} */
130
}
131