PostgresqlDatabase::loadParameters()   B
last analyzed

Complexity

Conditions 6
Paths 32

Size

Total Lines 17
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 6
eloc 12
nc 32
nop 1
dl 0
loc 17
rs 8.8571
c 0
b 0
f 0
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
 * PostgresqlDatabase provides connectivity for the PostgreSQL brand
21
 * database.
22
 *
23
 * <b>Optional parameters:</b>
24
 *
25
 * # <b>database</b>   - [none]      - The database name.
26
 * # <b>host</b>       - [localhost] - The database host.
27
 * # <b>method</b>     - [normal]    - How to read connection parameters.
28
 *                                     Possible values are normal, server, and
29
 *                                     env. The normal method reads them from
30
 *                                     the specified values. server reads them
31
 *                                     from $_SERVER where the keys to retrieve
32
 *                                     the values are what you specify the value
33
 *                                     as in the settings. env reads them from
34
 *                                     $_ENV and works like $_SERVER.
35
 * # <b>password</b>   - [none]      - The database password.
36
 * # <b>persistent</b> - [No]        - Indicates that the connection should be
37
 *                                     persistent.
38
 * # <b>port</b>       - [none]      - TCP/IP port on which PostgreSQL is
39
 *                                     listening.
40
 * # <b>username</b>   - [none]      - The database user.
41
 *
42
 * @package    agavi
43
 * @subpackage database
44
 *
45
 * @author     Sean Kerr <[email protected]>
46
 * @copyright  Authors
47
 * @copyright  The Agavi Project
48
 *
49
 * @since      0.9.0
50
 *
51
 * @version    $Id$
52
 */
53
class PostgresqlDatabase extends Database
54
{
55
    /**
56
     * Connect to the database.
57
     *
58
     * @throws     <b>AgaviDatabaseException</b> If a connection could not be
59
     *                                           created.
60
     *
61
     * @author     Sean Kerr <[email protected]>
62
     * @since      0.9.0
63
     */
64
    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...
65
    {
66
        // determine how to get our parameters
67
        $method = $this->getParameter('method', 'normal');
68
69
        // get parameters
70
        switch ($method) {
71
            case 'normal':
72
                // get parameters normally
73
                $database = $this->getParameter('database');
74
                $host     = $this->getParameter('host');
75
                $password = $this->getParameter('password');
76
                $port     = $this->getParameter('port');
77
                $user     = $this->getParameter('username');
78
                // construct connection string
79
                $string = (($database != null) ? (' dbname='   . $database) : '') .
80
                                    (($host != null)     ? (' host='     . $host)     : '') .
81
                                    (($password != null) ? (' password=' . $password) : '') .
82
                                    (($port != null)     ? (' port='     . $port)     : '') .
83
                                    (($user != null)     ? (' user='     . $user)     : '');
84
                break;
85
86
            case 'server':
87
                // construct a connection string from existing $_SERVER values
88
                $string = $this->loadParameters($_SERVER);
89
                break;
90
91
            case 'env':
92
                // construct a connection string from existing $_ENV values
93
                $string = $this->loadParameters($_ENV);
94
                break;
95
96
            default:
97
                // who knows what the user wants...
98
                $error = 'Invalid AgaviPostgreSQLDatabase parameter retrieval method "%s"';
99
                $error = sprintf($error, $method);
100
                throw new DatabaseException($error);
101
        }
102
103
        // let's see if we need a persistent connection
104
        $persistent = $this->getParameter('persistent', false);
105
106
        if ($persistent) {
107
            $this->connection = pg_pconnect($string);
108
        } else {
109
            $this->connection = pg_connect($string, PGSQL_CONNECT_FORCE_NEW);
110
        }
111
112
        // make sure the connection went through
113
        if ($this->connection === false) {
114
            // the connection's foobar'd
115
            $error = 'Failed to create a AgaviPostgreSQLDatabase connection';
116
117
            throw new DatabaseException($error);
118
        }
119
120
        // since we're not an abstraction layer, we copy the connection
121
        // to the resource
122
        $this->resource =& $this->connection;
123
        
124
        
125
        foreach ((array)$this->getParameter('init_queries') as $query) {
126
            pg_query($this->connection, $query);
127
        }
128
    }
129
130
    /**
131
     * Load connection parameters from an existing array.
132
     *
133
     * @param      array  $array An array containing the connection information.
134
     *
135
     * @return     string A connection string.
136
     *
137
     * @author     Sean Kerr <[email protected]>
138
     * @since      0.9.0
139
     */
140
    protected function loadParameters(array $array)
141
    {
142
        $database = $this->getParameter('database');
143
        $host     = $this->getParameter('host');
144
        $password = $this->getParameter('password');
145
        $port     = $this->getParameter('port');
146
        $user     = $this->getParameter('username');
147
148
        // construct connection string
149
        $string = (($database != null) ? (' dbname='   . $array[$database]) : '') .
150
                            (($host != null)     ? (' host='     . $array[$host])     : '') .
151
                            (($password != null) ? (' password=' . $array[$password]) : '') .
152
                            (($port != null)     ? (' port='     . $array[$port])     : '') .
153
                            (($user != null)     ? (' user='     . $array[$user])     : '');
154
155
        return $string;
156
    }
157
158
    /**
159
     * Execute the shutdown procedure.
160
     *
161
     * @throws     <b>AgaviDatabaseException</b> If an error occurs while shutting
162
     *                                           down this database.
163
     *
164
     * @author     Sean Kerr <[email protected]>
165
     * @since      0.9.0
166
     */
167
    public function shutdown()
168
    {
169
        if ($this->connection != null) {
170
            @pg_close($this->connection);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
171
            $this->connection = $this->resource = null;
172
        }
173
    }
174
}
175