createConnection()   C
last analyzed

Complexity

Conditions 11
Paths 38

Size

Total Lines 59

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 59
rs 6.7478
c 0
b 0
f 0
cc 11
nc 38
nop 2

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
3
namespace SilverStripe\MSSQL;
4
5
use SilverStripe\Dev\Install\DatabaseAdapterRegistry;
6
use SilverStripe\Dev\Install\DatabaseConfigurationHelper;
7
use PDO;
8
use Exception;
9
10
/**
11
 * This is a helper class for the SS installer.
12
 *
13
 * It does all the specific checking for MSSQLDatabase
14
 * to ensure that the configuration is setup correctly.
15
 */
16
class MSSQLDatabaseConfigurationHelper implements DatabaseConfigurationHelper
17
{
18
19
    protected function isAzure($databaseConfig)
20
    {
21
        /** @skipUpgrade */
22
        return $databaseConfig['type'] === 'MSSQLAzureDatabase';
23
    }
24
25
    /**
26
     * Create a connection of the appropriate type
27
     *
28
     * @skipUpgrade
29
     * @param array $databaseConfig
30
     * @param string $error Error message passed by value
31
     * @return mixed|null Either the connection object, or null if error
32
     */
33
    protected function createConnection($databaseConfig, &$error)
34
    {
35
        $error = null;
36
        try {
37
            switch ($databaseConfig['type']) {
38
                case 'MSSQLDatabase':
39
                case 'MSSQLAzureDatabase':
40
                    $parameters = array(
41
                        'UID' => $databaseConfig['username'],
42
                        'PWD' => $databaseConfig['password']
43
                    );
44
45
                    // Azure has additional parameter requirements
46
                    if ($this->isAzure($databaseConfig)) {
47
                        $parameters['database'] = $databaseConfig['database'];
48
                        $parameters['multipleactiveresultsets'] = 1;
49
                        $parameters['returndatesasstrings'] = 1;
50
                    }
51
52
                    $conn = @sqlsrv_connect($databaseConfig['server'], $parameters);
53
54
                    if ($conn) {
55
                        return $conn;
56
                    }
57
58
                    // Get error
59
                    if ($errors = sqlsrv_errors()) {
60
                        $error = '';
61
                        foreach ($errors as $detail) {
62
                            $error .= "{$detail['message']}\n";
63
                        }
64
                    } else {
65
                        $error = 'Unknown connection error';
66
                    }
67
                    return null;
68
                case 'MSSQLPDODatabase':
69
                    $driver = $this->getPDODriver();
0 ignored issues
show
Bug introduced by
Are you sure the assignment to $driver is correct as $this->getPDODriver() (which targets SilverStripe\MSSQL\MSSQL...nHelper::getPDODriver()) seems to always return null.

This check looks for function or method calls that always return null and whose return value is assigned to a variable.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
$object = $a->getObject();

The method getObject() can return nothing but null, so it makes no sense to assign that value to a variable.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
70
                    if (!$driver) {
71
                        $error = 'No supported PDO driver';
72
                        return null;
73
                    }
74
75
                    // May throw a PDOException if fails
76
                    $conn = @new PDO($driver.':Server='.$databaseConfig['server'], $databaseConfig['username'], $databaseConfig['password']);
77
                    if ($conn) {
78
                        return $conn;
79
                    } else {
80
                        $error = 'Unknown connection error';
81
                        return null;
82
                    }
83
                default:
84
                    $error = 'Invalid connection type: ' . $databaseConfig['type'];
85
                    return null;
86
            }
87
        } catch (Exception $ex) {
88
            $error = $ex->getMessage();
89
            return null;
90
        }
91
    }
92
93
    /**
94
     * Get supported PDO driver
95
     *
96
     * @return null
97
     */
98
    public static function getPDODriver() {
99
        if (!class_exists('PDO')) {
100
            return null;
101
        }
102
103
        foreach(PDO::getAvailableDrivers() as $driver) {
104
            if (in_array($driver, array('sqlsrv', 'dblib'))) {
105
                return $driver;
106
            }
107
        }
108
109
        return null;
110
    }
111
112
    /**
113
     * Helper function to quote a string value
114
     *
115
     * @param mixed $conn Connection object/resource
116
     * @param string $value Value to quote
117
     * @return string Quoted string
118
     */
119
    protected function quote($conn, $value)
120
    {
121
        if ($conn instanceof PDO) {
122
            return $conn->quote($value);
123
        } elseif (is_resource($conn)) {
124
            $value = str_replace("'", "''", $value);
125
            $value = str_replace("\0", "[NULL]", $value);
126
            return "N'$value'";
127
        } else {
128
            user_error('Invalid database connection', E_USER_ERROR);
129
        }
130
131
        return null;
132
    }
133
134
    /**
135
     * Helper function to execute a query
136
     *
137
     * @param mixed $conn Connection object/resource
138
     * @param string $sql SQL string to execute
139
     * @return array List of first value from each resulting row
140
     */
141
    protected function query($conn, $sql)
142
    {
143
        $items = array();
144
        if ($conn instanceof PDO) {
145
            $result = $conn->query($sql);
146
            if ($result) {
147
                foreach ($result as $row) {
148
                    $items[] = $row[0];
149
                }
150
            }
151
        } elseif (is_resource($conn)) {
152
            $result = sqlsrv_query($conn, $sql);
153
            if ($result) {
154
                while ($row = sqlsrv_fetch_array($result, SQLSRV_FETCH_NUMERIC)) {
155
                    $items[] = $row[0];
156
                }
157
            }
158
        }
159
160
        return $items;
161
    }
162
163
    public function requireDatabaseFunctions($databaseConfig)
164
    {
165
        $data = DatabaseAdapterRegistry::get_adapter($databaseConfig['type']);
166
        return !empty($data['supported']);
167
    }
168
169 View Code Duplication
    public function requireDatabaseServer($databaseConfig)
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...
170
    {
171
        $conn = $this->createConnection($databaseConfig, $error);
172
        $success = !empty($conn);
173
174
        return array(
175
            'success' => $success,
176
            'error' => $error
177
        );
178
    }
179
180 View Code Duplication
    public function requireDatabaseConnection($databaseConfig)
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...
181
    {
182
        $conn = $this->createConnection($databaseConfig, $error);
183
        $success = !empty($conn);
184
185
        return array(
186
            'success' => $success,
187
            'connection' => $conn,
188
            'error' => $error
189
        );
190
    }
191
192
    public function getDatabaseVersion($databaseConfig)
193
    {
194
        $conn = $this->createConnection($databaseConfig, $error);
195
        $result = $this->query($conn, "SELECT CONVERT(char(15), SERVERPROPERTY('ProductVersion'))");
196
        return empty($result) ? 0 : reset($result);
197
    }
198
199
    /**
200
     * Ensure that the SQL Server version is at least 10.00.2531 (SQL Server 2008 SP1).
201
     *
202
     * @see http://www.sqlteam.com/article/sql-server-versions
203
     * @param array $databaseConfig Associative array of db configuration, e.g. "server", "username" etc
204
     * @return array Result - e.g. array('success' => true, 'error' => 'details of error')
205
     */
206
    public function requireDatabaseVersion($databaseConfig)
207
    {
208
        $success = false;
209
        $error = '';
210
        $version = $this->getDatabaseVersion($databaseConfig);
211
212
        if ($version) {
213
            $success = version_compare($version, '10.00.2531', '>=');
214
            if (!$success) {
215
                $error = "Your SQL Server version is $version. It's recommended you use at least 10.00.2531 (SQL Server 2008 SP1).";
216
            }
217
        } else {
218
            $error = "Your SQL Server version could not be determined.";
219
        }
220
221
        return array(
222
            'success' => $success,
223
            'error' => $error
224
        );
225
    }
226
227
    public function requireDatabaseOrCreatePermissions($databaseConfig)
228
    {
229
        $conn = $this->createConnection($databaseConfig, $error);
230
        /** @skipUpgrade */
231
        if (empty($conn)) {
232
            $success = false;
233
            $alreadyExists = false;
234
        } elseif ($databaseConfig['type'] == 'MSSQLAzureDatabase') {
235
            // Don't bother with DB selection for azure, as it's not supported
236
            $success = true;
237
            $alreadyExists = true;
238
        } else {
239
            // does this database exist already?
240
            $list = $this->query($conn, 'SELECT NAME FROM sys.sysdatabases');
241
            if (in_array($databaseConfig['database'], $list)) {
242
                $success = true;
243
                $alreadyExists = true;
244
            } else {
245
                $permissions = $this->query($conn, "select COUNT(*) from sys.fn_my_permissions('','') where permission_name like 'CREATE ANY DATABASE' or permission_name like 'CREATE DATABASE';");
246
                $success = $permissions[0] > 0;
247
                $alreadyExists = false;
248
            }
249
        }
250
251
        return array(
252
            'success' => $success,
253
            'alreadyExists' => $alreadyExists
254
        );
255
    }
256
257
    public function requireDatabaseAlterPermissions($databaseConfig)
258
    {
259
        $success = false;
260
        $conn = $this->createConnection($databaseConfig, $error);
261
        if (!empty($conn)) {
262
            if (!$this->isAzure($databaseConfig)) {
263
                // Make sure to select the current database when checking permission against this database
264
                $this->query($conn, "USE \"{$databaseConfig['database']}\"");
265
            }
266
267
            $permissions = $this->query($conn, "select COUNT(*) from sys.fn_my_permissions(NULL,'DATABASE') WHERE permission_name like 'create table';");
268
            $success = $permissions[0] > 0;
269
        }
270
271
        return array(
272
            'success' => $success,
273
            'applies' => true
274
        );
275
    }
276
}
277