PdoDatabase::connect()   F
last analyzed

Complexity

Conditions 18
Paths 11125

Size

Total Lines 51
Code Lines 28

Duplication

Lines 10
Ratio 19.61 %

Importance

Changes 0
Metric Value
cc 18
eloc 28
nc 11125
nop 0
dl 10
loc 51
rs 2.882
c 0
b 0
f 0

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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
// |                                                                           |
8
// | For the full copyright and license information, please view the LICENSE   |
9
// | file that was distributed with this source code. You can also view the    |
10
// | LICENSE file online at http://www.agavi.org/LICENSE.txt                   |
11
// |   vi: set noexpandtab:                                                    |
12
// |   Local Variables:                                                        |
13
// |   indent-tabs-mode: t                                                     |
14
// |   End:                                                                    |
15
// +---------------------------------------------------------------------------+
16
use Agavi\Exception\DatabaseException;
17
18
/**
19
 * AgaviPdoDatabase provides connectivity for the PDO database API layer.
20
 *
21
 * @package    agavi
22
 * @subpackage database
23
 *
24
 * @author     Daniel Swarbrick <[email protected]>
25
 * @author     David Zülke <[email protected]>
26
 * @author     Dominik del Bondio <[email protected]>
27
 * @author     Veikko Mäkinen <[email protected]>
28
 * @copyright  Authors
29
 * @copyright  The Agavi Project
30
 *
31
 * @since      0.9.0
32
 *
33
 * @version    $Id$
34
 */
35
class PdoDatabase extends Database
36
{
37
    /**
38
     * Initialize this Database.
39
     *
40
     * @param      DatabaseManager $databaseManager The database manager of this instance.
41
     * @param      array           $parameters An assoc array of initialization params.
42
     *
43
     * @author     David Zülke <[email protected]>
44
     * @since      1.0.5
45
     */
46
    public function initialize(DatabaseManager $databaseManager, array $parameters = array())
47
    {
48
        parent::initialize($databaseManager, $parameters);
49
        
50
        if ($this->getParameter('warn_mysql_charset', true) && strpos($this->getParameter('dsn'), 'mysql:') === 0) {
51
            if ($matches = preg_grep('/^\s*SET\s+NAMES\b/i', (array)$this->getParameter('init_queries'))) {
52
                throw new DatabaseException(sprintf(
53
                    '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.' .
54
                    'As a result, string escaping may be applied incorrectly, leading to potential attack vectors in combination with certain multi-byte character sets such as GBK or Big5.' . "\n\n" .
55
                    'Please use the "charset" DSN option instead and remove the "%s" statement from the "init_queries" configuration parameter in databases.xml.' . "\n\n" .
56
                    'The associated PHP bug ticket http://bugs.php.net/47802 contains further information.',
57
                    $matches[0]
58
                ));
59
            }
60
            if (strpos($this->getParameter('dsn'), ';charset=') !== false && version_compare(PHP_VERSION, '5.3.6', '<')) {
61
                throw new DatabaseException(
62
                    'The "charset" option in a PDO_MYSQL DSN has no effect in PHP versions prior to 5.3.6. In combination with certain multi-byte character sets such as GBK or Big5, this may cause incorrectly escaped characters in prepared statements and quoted strings, potentially leading to vulnerabilities in application code.' . "\n\n" .
63
                    'There are two ways of working around this problem:' . "\n" .
64
                    '1) Upgrade to PHP 5.3.6 or later :)' . "\n" .
65
                    '2) Double-check your my.cnf configuration to make sure the default connection charset is compatible with the charset you wish to set (for example, latin1 as the connection default in combination with "SET NAMES utf8" is safe), then revert to using "SET NAMES" in "init_queries" and set the "warn_mysql_charset" configuration parameter on this connection to false. In this case, it is recommended to use native prepared statements by setting the flag PDO::ATTR_EMULATE_PREPARES to 0 in "options" or "attributes", but be advised that per-statement attributes can override this setting, and calls to PDO::quote() might still yield incorrectly escaped strings.'  . "\n\n" .
66
                    'The associated PHP bug ticket http://bugs.php.net/47802 contains further information.'
67
                );
68
            }
69
        }
70
    }
71
72
    /**
73
     * Connect to the database.
74
     *
75
     * @throws     <b>AgaviDatabaseException</b> If a connection could not be
76
     *                                           created.
77
     *
78
     * @author     Daniel Swarbrick <[email protected]>
79
     * @author     David Zülke <[email protected]>
80
     * @author     Dominik del Bondio <[email protected]>
81
     * @author     Veikko Mäkinen <[email protected]>
82
     * @since      0.9.0
83
     */
84
    protected function connect()
85
    {
86
        // determine how to get our parameters
87
        $method = $this->getParameter('method', 'dsn');
88
89
        // get parameters
90
        switch ($method) {
91
            case 'dsn':
92
                $dsn = $this->getParameter('dsn');
93
                if ($dsn == null) {
94
                    // missing required dsn parameter
95
                    $error = 'Database configuration specifies method "dsn", but is missing dsn parameter';
96
                    throw new DatabaseException($error);
97
                }
98
                break;
99
        }
100
101
        try {
102
            $username = $this->getParameter('username');
103
            $password = $this->getParameter('password');
104
105
            $options = array();
106
107 View Code Duplication
            if ($this->hasParameter('options')) {
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...
108
                foreach ((array)$this->getParameter('options') as $key => $value) {
109
                    $options[is_string($key) && strpos($key, '::') ? constant($key) : $key] = is_string($value) && strpos($value, '::') ? constant($value) : $value;
110
                }
111
            }
112
113
            $this->connection = $this->resource = new \PDO($dsn, $username, $password, $options);
0 ignored issues
show
Bug introduced by
The variable $dsn does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
114
115
            // default connection attributes
116
            $attributes = array(
117
                // lets generate exceptions instead of silent failures
118
                \PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION
119
            );
120 View Code Duplication
            if ($this->hasParameter('attributes')) {
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...
121
                foreach ((array)$this->getParameter('attributes') as $key => $value) {
122
                    $attributes[is_string($key) && strpos($key, '::') ? constant($key) : $key] = is_string($value) && strpos($value, '::') ? constant($value) : $value;
123
                }
124
            }
125
            foreach ($attributes as $key => $value) {
126
                $this->connection->setAttribute($key, $value);
127
            }
128
            foreach ((array)$this->getParameter('init_queries') as $query) {
129
                $this->connection->exec($query);
130
            }
131
        } catch (\PDOException $e) {
132
            throw new DatabaseException($e->getMessage(), 0, $e);
133
        }
134
    }
135
136
    /**
137
     * Execute the shutdown procedure.
138
     *
139
     * @throws     <b>AgaviDatabaseException</b> If an error occurs while shutting
140
     *                                           down this database.
141
     *
142
     * @author     Daniel Swarbrick <[email protected]>
143
     * @since      0.9.0
144
     */
145
    public function shutdown()
146
    {
147
        // assigning null to a previously open connection object causes a disconnect
148
        $this->connection = $this->resource = null;
149
    }
150
}
151