MysqliDatabase   A
last analyzed

Complexity

Total Complexity 16

Size/Duplication

Total Lines 124
Duplicated Lines 48.39 %

Coupling/Cohesion

Components 1
Dependencies 2

Importance

Changes 0
Metric Value
dl 60
loc 124
rs 10
c 0
b 0
f 0
wmc 16
lcom 1
cbo 2

3 Methods

Rating   Name   Duplication   Size   Complexity  
A initialize() 8 8 2
C connect() 52 79 12
A shutdown() 0 7 2

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

1
<?php
2
namespace Agavi\Database;
3
4
// +---------------------------------------------------------------------------+
5
// | This file is part of the Agavi package.                                   |
6
// | Copyright (c) 2005-2011 the Agavi Project.                                |
7
// | Based on the Mojavi3 MVC Framework, Copyright (c) 2003-2005 Sean Kerr.    |
8
// |                                                                           |
9
// | For the full copyright and license information, please view the LICENSE   |
10
// | file that was distributed with this source code. You can also view the    |
11
// | LICENSE file online at http://www.agavi.org/LICENSE.txt                   |
12
// |   vi: set noexpandtab:                                                    |
13
// |   Local Variables:                                                        |
14
// |   indent-tabs-mode: t                                                     |
15
// |   End:                                                                    |
16
// +---------------------------------------------------------------------------+
17
use Agavi\Exception\DatabaseException;
18
19
/**
20
 * MysqliDatabase provides advanced connectivity for the MySQL database.
21
 *
22
 * <b>Optional parameters:</b>
23
 *
24
 * # <b>database</b>   - [none]      - The database name.
25
 * # <b>host</b>       - [localhost] - The database host.
26
 * # <b>method</b>     - [normal]    - How to read connection parameters.
27
 *                                     Possible values are normal, server, and
28
 *                                     env. The normal method reads them from
29
 *                                     the specified values. server reads them
30
 *                                     from $_SERVER where the keys to retrieve
31
 *                                     the values are what you specify the value
32
 *                                     as in the settings. env reads them from
33
 *                                     $_ENV and works like $_SERVER.
34
 * # <b>password</b>   - [none]      - The database password.
35
 * # <b>username</b>   - [none]      - The database user.
36
 *
37
 * @package    agavi
38
 * @subpackage database
39
 *
40
 * @author     Sean Kerr <[email protected]>
41
 * @author     Blake Matheny <[email protected]>
42
 * @copyright  Authors
43
 * @copyright  The Agavi Project
44
 *
45
 * @since      1.0.0
46
 *
47
 * @version    $Id$
48
 */
49
class MysqliDatabase extends MysqlDatabase
50
{
51
    /**
52
     * Initialize this Database.
53
     *
54
     * @param      DatabaseManager $databaseManager The database manager of this instance.
55
     * @param      array           $parameters An assoc array of initialization params.
56
     *
57
     * @author     David Zülke <[email protected]>
58
     * @since      1.0.5
59
     */
60 View Code Duplication
    public function initialize(DatabaseManager $databaseManager, array $parameters = array())
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
61
    {
62
        parent::initialize($databaseManager, $parameters);
63
        
64
        if ($matches = preg_grep('/^\s*SET\s+NAMES\b/i', (array)$this->getParameter('init_queries'))) {
65
            throw new DatabaseException(sprintf('Depending on your MySQL server configuration, it may not be safe to use "SET NAMES" to configure the connection encoding, as the underlying MySQL client library will not be aware of the changed character set. As a result, string escaping may be applied incorrectly (even for prepared statements), leading to potential attack vectors in combination with certain multi-byte character sets such as GBK or Big5.' . "\n\n" . 'Please remove the "%s" statement from the "init_queries" configuration parameter in databases.xml and use the configuration parameter "charset" instead.' . "\n\n" . 'The associated PHP bug ticket http://bugs.php.net/47802 contains further information (describes PDO, but the basic issue is the same).', $matches[0]));
66
        }
67
    }
68
69
    /**
70
     * Connect to the database.
71
     *
72
     * @throws     <b>AgaviDatabaseException</b> If a connection could not be
73
     *                                           created.
74
     *
75
     * @author     Sean Kerr <[email protected]>
76
     * @author     Blake Matheny <[email protected]>
77
     * @since      1.0.0
78
     */
79
    protected function connect()
0 ignored issues
show
Coding Style introduced by
connect uses the super-global variable $_SERVER which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
Coding Style introduced by
connect uses the super-global variable $_ENV which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
80
    {
81
        // determine how to get our
82
        $method = $this->getParameter('method', 'normal');
83
84 View Code Duplication
        switch ($method) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
85
            case 'normal':
86
                // get parameters normally
87
                $database = $this->getParameter('database');
88
                $host     = $this->getParameter('host', 'localhost');
89
                $password = $this->getParameter('password');
90
                $user     = $this->getParameter('username');
91
                break;
92
93
            case 'server':
94
                // construct a connection string from existing $_SERVER values
95
                // and extract them to local scope
96
                $parameters = $this->loadParameters($_SERVER);
97
                extract($parameters);
98
                break;
99
100
            case 'env':
101
                // construct a connection string from existing $_ENV values
102
                // and extract them to local scope
103
                $parameters = $this->loadParameters($_ENV);
104
                extract($parameters);
105
                break;
106
107
            default:
108
                // who knows what the user wants...
109
                $error = 'Invalid AgaviMySQLiDatabase parameter retrieval method ' .
110
                         '"%s"';
111
                $error = sprintf($error, $method);
112
                throw new DatabaseException($error);
113
        }
114
115 View Code Duplication
        if ($password === null) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
116
            if ($user === null) {
117
                $args = array($host, null, null);
118
            } else {
119
                $args = array($host, $user, null);
120
            }
121
        } else {
122
            $args = array($host, $user, $password);
123
        }
124
        
125
        $this->connection = new \mysqli($args[0], $args[1], $args[2]);
126
        
127
        // make sure the connection went through
128
        if ($this->connection === false) {
129
            // the connection's foobar'd
130
            $error = 'Failed to create a AgaviMySQLiDatabase connection';
131
            throw new DatabaseException($error);
132
        }
133
        
134 View Code Duplication
        if ($this->hasParameter('charset')) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
135
            if (!$this->connection->set_charset($this->getParameter('charset'))) {
136
                $error = 'Failed to set charset "%s"';
137
                $error = sprintf($error, $this->getParameter('charset'));
138
                throw new DatabaseException($error);
139
            }
140
        }
141
142
        // select our database
143 View Code Duplication
        if ($database !== null && !$this->connection->select_db($database)) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
144
            // can't select the database
145
            $error = 'Failed to select AgaviMySQLiDatabase "%s"';
146
            $error = sprintf($error, $database);
147
            throw new DatabaseException($error);
148
        }
149
150
        // since we're not an abstraction layer, we copy the connection
151
        // to the resource
152
        $this->resource =& $this->connection;
153
        
154
        foreach ((array)$this->getParameter('init_queries') as $query) {
155
            $this->connection->query($query);
156
        }
157
    }
158
159
    /**
160
     * Execute the shutdown procedure.
161
     *
162
     * @author     Blake Matheny <[email protected]>
163
     * @since      1.0.0
164
     */
165
    public function shutdown()
166
    {
167
        if ($this->connection != null) {
168
            $this->connection->close();
169
            $this->connection = $this->resource = null;
170
        }
171
    }
172
}
173