Completed
Push — master ( 3845e2...a95f7d )
by Danilo
09:37
created

Handler   A

Complexity

Total Complexity 11

Size/Duplication

Total Lines 106
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 0

Test Coverage

Coverage 41.94%

Importance

Changes 0
Metric Value
wmc 11
lcom 1
cbo 0
dl 0
loc 106
ccs 13
cts 31
cp 0.4194
rs 10
c 0
b 0
f 0

4 Methods

Rating   Name   Duplication   Size   Complexity  
A addDefaultValue() 0 5 1
B getDns() 0 22 5
A connect() 0 16 2
A sanitizeUserTable() 0 16 3
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
    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
84
    {
85 1
        static $defaults = [ 'adapter' => PDO_DEFAULT_ADAPTER, 'host' => 'localhost', 'options' => [] ];
86 1
        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 2
    protected function getDns($params) : string
94
    {
95 2
        $response = $params['adapter'] . ':';
96 2
        unset($params['adapter']);
97 2
        $fields = [];
98
99 2
        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 2
            if ($field === 'username' || $field === 'password' || $field === 'options') {
106 1
                unset($params[$field]);
107 1
                continue;
108
            }
109
110 2
            $fields[] = $field . '=' . $value;
111
        }
112
113 2
        return $response . join(';', $fields);
114
    }
115
116
    /**
117
     * \brief (<i>Internal</i>) Sanitize name of the user table depending on database used.
118
     */
119
    protected function sanitizeUserTable()
120
    {
121
        static $is_sanitized = false;
122
123
        if ($is_sanitized) {
124
            return;
125
        }
126
127
        if ($this->pdo->getAttribute(\PDO::ATTR_DRIVER_NAME) === 'mysql') {
128
            $this->user_table = "`$this->user_table`";
129
        } else {
130
            $this->user_table = '"' . $this->user_table . '"';
131
        }
132
133
        $is_sanitized = true;
134
    }
135
136
    /** @} */
137
}
138