Passed
Pull Request — develop (#340)
by Felipe
04:56
created

Connection::getPG9Connection()   B

Complexity

Conditions 10
Paths 9

Size

Total Lines 32
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 10
eloc 15
c 0
b 0
f 0
nc 9
nop 7
dl 0
loc 32
rs 7.6666

How to fix   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
3
/**
4
 * PHPPgAdmin 6.0.0
5
 */
6
7
namespace PHPPgAdmin;
8
9
/**
10
 * @file
11
 * Class to represent a database connection
12
 *
13
 * Id: Connection.php,v 1.15 2008/02/18 21:42:47 ioguix Exp $
14
 */
15
class Connection
16
{
17
    use \PHPPgAdmin\Traits\HelperTrait;
18
19
    public $conn;
20
21
    public $platform = 'UNKNOWN';
22
23
    /**
24
     * @var string
25
     */
26
    public $driver;
27
28
    protected $container;
29
30
    protected $server_info;
31
32
    protected $version_dictionary = [
33
        '13' => 'Postgres13',
34
        '12' => 'Postgres12',
35
        '11' => 'Postgres11',
36
        '10' => 'Postgres10',
37
        '9.7' => 'Postgres96',
38
        '9.6' => 'Postgres96',
39
        '9.5' => 'Postgres95',
40
        '9.4' => 'Postgres94',
41
        '9.3' => 'Postgres93',
42
        '9.2' => 'Postgres92',
43
        '9.1' => 'Postgres91',
44
        '9.0' => 'Postgres90',
45
    ];
46
47
    /**
48
     * @var string
49
     */
50
    private $pgVersion;
0 ignored issues
show
Coding Style introduced by
Private member variable "pgVersion" must be prefixed with an underscore
Loading history...
51
52
    private $adodb_driver = 'postgres9';
0 ignored issues
show
Coding Style introduced by
Private member variable "adodb_driver" must be prefixed with an underscore
Loading history...
53
54
    // or pdo
55
    // The backend platform.  Set to UNKNOWN by default.
56
    private $_connection_result;
0 ignored issues
show
introduced by
The private property $_connection_result is not used, and could be removed.
Loading history...
57
58
    /**
59
     * Creates a new connection.  Will actually make a database connection.
60
     *
61
     * @param array           $server_info
62
     * @param string          $database    database name
63
     * @param \PHPPgAdmin\ContainerUtils $container
64
     * @param int             $fetchMode   Defaults to associative.  Override for different behaviour
65
     */
66
    public function __construct($server_info, $database, $container, $fetchMode = ADODB_FETCH_ASSOC)
67
    {
68
        $host = $server_info['host'];
69
        $port = $server_info['port'];
70
        $sslmode = $server_info['sslmode'];
71
        $user = $server_info['username'];
72
        $password = $server_info['password'];
73
74
        $this->server_info = $server_info;
75
76
        $this->container = $container;
77
78
        // ADODB_Postgres9 Approach
79
        //$driver='postgres9';
80
        $this->conn = \ADONewConnection($this->adodb_driver);
81
       
82
83
        // PDO Approach
84
85
        /*try {
86
        $this->_connection_result = $this->conn->connect($pghost, $user, $password, $database);
87
        $this->prtrace(['_connection_result' => $this->_connection_result, 'conn' => $this->conn]);
88
        } catch (\PHPPgAdmin\ADOdbException $e) {
89
        $this->prtrace(['message' => $e->getMessage(), 'trace' => $e->getTraceAsString()]);
90
         */
91
        try {
92
            $this->conn = 'pdo' === $this->adodb_driver ?
0 ignored issues
show
introduced by
The condition 'pdo' === $this->adodb_driver is always false.
Loading history...
93
                $this->getPDOConnection($host, $port, $sslmode, $database, $user, $password, $fetchMode) :
94
                $this->getPG9Connection($host, $port, $sslmode, $database, $user, $password, $fetchMode);
95
                $this->conn->setFetchMode($fetchMode);
0 ignored issues
show
Bug introduced by
$fetchMode of type integer is incompatible with the type The expected by parameter $mode of ADOConnection::SetFetchMode(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

95
                $this->conn->setFetchMode(/** @scrutinizer ignore-type */ $fetchMode);
Loading history...
96
            //$this->prtrace($this->conn);
97
        } catch (\Exception $e) {
98
            //dump($dsnString, $this->adodb_driver);
99
            $this->prtrace($e->getMessage(), \array_slice($e->getTrace(), 0, 10));
100
        }
101
    }
102
 
103
104
    public function getVersion():string
105
    {
106
        return $this->pgVersion;
107
    }
108
109
    /**
110
     * Gets the name of the correct database driver to use.  As a side effect,
111
     * sets the platform.
112
     *
113
     * @param string $description A description of the database and version (returns by reference)
114
     *
115
     * @return string The driver. e.g. Postgres96
116
     */
117
    public function getDriver(&$description)
118
    {
119
        if (!$this->conn->IsConnected()) {
120
            return null;
121
        }
122
        $serverInfo = $this->conn->ServerInfo();
123
        dump($serverInfo);
0 ignored issues
show
Bug introduced by
The call to dump() has too few arguments starting with str. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

123
        /** @scrutinizer ignore-call */ 
124
        dump($serverInfo);

This check compares calls to functions or methods with their respective definitions. If the call has less arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress. Please note the @ignore annotation hint above.

Loading history...
124
        $this->pgVersion = $serverInfo['version'];
125
        $description = "PostgreSQL {$this->pgVersion}";
126
127
        $version_parts = \explode('.', $this->pgVersion);
128
129
        if ((int) (10 <= $version_parts[0])) {
130
            $major_version = $version_parts[0];
131
        } else {
132
            $major_version = \implode('.', [$version_parts[0], $version_parts[1]]);
133
        }
134
135
        // if major version is less than 9 return null, we don't support it
136
        if (9 > (float) $major_version) {
137
            $this->driver = null;
138
139
            return null;
140
        }
141
142
        $this->driver = 'Postgres';
143
        //$this->prtrace(['pg_version' => pg_version($this->conn->_connectionID), 'version' => $version, 'major_version' => $major_version]);
144
        // Detect version and choose appropriate database driver
145
        if (\array_key_exists($major_version, $this->version_dictionary)) {
146
            $this->driver = $this->version_dictionary[$major_version];
147
        }
148
149
        // If unknown version, then default to latest driver
150
        return $this->driver;
151
    }
152
153
    /**
154
     * Get the last error in the connection.
155
     *
156
     * @return string Error string
157
     */
158
    public function getLastError()
159
    {
160
        return $this->conn->ErrorMsg();
0 ignored issues
show
Bug Best Practice introduced by
The expression return $this->conn->ErrorMsg() also could return the type true which is incompatible with the documented return type string.
Loading history...
161
    }
162
163
    private function getPG9Connection(
164
        string $host,
165
        int $port,
166
        string $sslmode,
167
        ?string $database,
168
        ?string $user,
169
        ?string $password,
170
        int $fetchMode = \ADODB_FETCH_ASSOC
171
    ): \ADODB_postgres9 {
172
        $this->conn = ADONewConnection('postgres9');
173
        $this->conn->setFetchMode($fetchMode);
174
        // Ignore host if null
175
        if (null === $host || '' === $host) {
176
            if (null !== $port && '' !== $port) {
0 ignored issues
show
introduced by
The condition '' !== $port is always true.
Loading history...
177
                $pghost = ':' . $port;
178
            } else {
179
                $pghost = '';
180
            }
181
        } else {
182
            $pghost = "{$host}:{$port}";
183
        }
184
185
        // Add sslmode to $pghost as needed
186
        if (('disable' === $sslmode) || ('allow' === $sslmode) || ('prefer' === $sslmode) || ('require' === $sslmode)) {
187
            $pghost .= ':' . $sslmode;
188
        } elseif ('legacy' === $sslmode) {
189
            $pghost .= ' requiressl=1';
190
        }
191
192
        $this->conn->connect($pghost, $user, $password, $database);
193
194
        return $this->conn;
195
    }
196
197
    private function getPDOConnection(
198
        string $host,
199
        int $port,
200
        string $sslmode,
201
        ?string $database,
202
        ?string $user,
203
        ?string $password,
204
        int $fetchMode = \ADODB_FETCH_ASSOC
205
    ): \ADODB_pdo {
206
        $this->conn = ADONewConnection('pdo');
207
        $this->conn->setFetchMode($fetchMode);
208
        $dsnString = \sprintf('pgsql:host=%s;port=%d;dbname=%s;sslmode=%s;application_name=PHPPgAdmin6', $host, $port, $database, $sslmode);
209
        $this->conn->connect($dsnString, $user, $password);
210
211
        return $this->conn;
212
    }
213
}
214