Completed
Push — master ( 549b3b...080752 )
by Danilo
15:29
created

Handler::stringify()   B

Complexity

Conditions 4
Paths 3

Size

Total Lines 22
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 4.128

Importance

Changes 0
Metric Value
dl 0
loc 22
ccs 8
cts 10
cp 0.8
rs 8.9197
c 0
b 0
f 0
cc 4
eloc 10
nc 3
nop 1
crap 4.128
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 PDOException;
22
23
define('DATA_CONNECTION_FILE', './data/connection.json');
24
25
trait Handler
26
{
27
28
    /**
29
     * \addtogroup Bot Bot
30
     * @{
31
     */
32
33
    /** Pdo connection to the database. */
34
    public $pdo;
35
36
    /**
37
     * \brief Open a database connection using PDO.
38
     * \details Provides a simpler way to initialize a database connection
39
     * and create a PDO instance.
40
     * @param $params Parameters for initialize connection.
41
     * @return True on success.
42
     */
43
    public function connect(array $params = []) : bool
44
    {
45
        if (empty($params) && file_exists('DATA_CONNECTION_FILE')) {
46
            $params = json_decode(file_get_contents('DATA_CONNECTION_FILE'), true);
47
        }
48
49
        try {
50
            $config = $this->stringify($this->mergeWithDefaults($params));
51
52
            $this->pdo = new \PDO($config, $params['username'], $params['password'], $params['option']);
53
            $this->pdo->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
54
55
            return true;
56
        } catch (PDOException $e) {
57
            echo 'Unable to connect to database, an error occured:' . $e->getMessage();
58
        }
59
60
        return false;
61
    }
62
63 1
    protected function mergeWithDefaults($params)
64
    {
65 1
        $DEFAULTS = [ 'adapter' => 'mysql', 'host' => 'localhost' ];
66 1
        return array_merge($DEFAULTS, $params);
67
    }
68
69
    /** \brief Returns a string that can passed to PDO in order to open connection.
70
     * @param array $params Array containing parameter of the connection
71
     */
72 2
    protected function stringify($params) : string
73
    {
74 2
        $response = $params['adapter'] . ':';
75 2
        unset($params['adapter']);
76 2
        $fields = [];
77
78 2
        foreach ($params as $field => $value) {
79
            /**
80
             *Check if the current field matches one of the fields
81
             * that are passed to PDO in another way and so don't need
82
             * to be included in the string.
83
             */
84 2
            if ($field === 'username' || $field === 'password') {
85
                unset($params[$field]);
86
                continue;
87
            }
88
89 2
            $fields[] = $field . '=' . $value;
90
        }
91
92 2
        return $response . join(';', $fields);
93
    }
94
95
    /** @} */
96
}
97