Completed
Pull Request — master (#31)
by Damian
06:15
created

MSSQLDatabaseConfigurationHelper   B

Complexity

Total Complexity 36

Size/Duplication

Total Lines 226
Duplicated Lines 8.41 %

Coupling/Cohesion

Components 1
Dependencies 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 36
c 1
b 0
f 0
lcom 1
cbo 1
dl 19
loc 226
rs 8.8

11 Methods

Rating   Name   Duplication   Size   Complexity  
A isAzure() 0 4 1
C createConnection() 0 50 10
A quote() 0 12 3
B query() 0 20 7
A requireDatabaseFunctions() 0 5 1
A requireDatabaseServer() 9 10 1
A requireDatabaseConnection() 10 11 1
A getDatabaseVersion() 0 6 2
A requireDatabaseVersion() 0 20 3
B requireDatabaseOrCreatePermissions() 0 28 4
A requireDatabaseAlterPermissions() 0 18 3

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
3
namespace SilverStripe\MSSQL;
4
5
use DatabaseConfigurationHelper;
6
use PDO;
7
use Exception;
8
use DatabaseAdapterRegistry;
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
 * @package mssql
17
 */
18
class MSSQLDatabaseConfigurationHelper implements DatabaseConfigurationHelper
19
{
20
21
    protected function isAzure($databaseConfig)
22
    {
23
        return $databaseConfig['type'] === 'MSSQLAzureDatabase';
24
    }
25
26
    /**
27
     * Create a connection of the appropriate type
28
     *
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'] = 0;
49
                    }
50
                    $conn = @sqlsrv_connect($databaseConfig['server'], $parameters);
51
                    if ($conn) {
52
                        return $conn;
53
                    }
54
55
                    // Get error
56
                    if ($errors = sqlsrv_errors()) {
57
                        $error = '';
58
                        foreach ($errors as $detail) {
59
                            $error .= "{$detail['message']}\n";
60
                        }
61
                    } else {
62
                        $error = 'Unknown connection error';
63
                    }
64
                    return null;
65
                case 'MSSQLPDODatabase':
0 ignored issues
show
Coding Style introduced by
There must be a comment when fall-through is intentional in a non-empty case body
Loading history...
66
                    // May throw a PDOException if fails
67
                    $conn = @new PDO('sqlsrv:Server='.$databaseConfig['server'], $databaseConfig['username'], $databaseConfig['password']);
68
                    if ($conn) {
69
                        return $conn;
70
                    } else {
71
                        $error = 'Unknown connection error';
72
                        return null;
73
                    }
74
                default:
75
                    $error = 'Invalid connection type';
76
                    return null;
77
            }
78
        } catch (Exception $ex) {
79
            $error = $ex->getMessage();
80
            return null;
81
        }
82
    }
83
84
    /**
85
     * Helper function to quote a string value
86
     *
87
     * @param mixed $conn Connection object/resource
88
     * @param string $value Value to quote
89
     * @return string Quoted strieng
90
     */
91
    protected function quote($conn, $value)
92
    {
93
        if ($conn instanceof PDO) {
94
            return $conn->quote($value);
95
        } elseif (is_resource($conn)) {
96
            $value = str_replace("'", "''", $value);
97
            $value = str_replace("\0", "[NULL]", $value);
98
            return "N'$value'";
99
        } else {
100
            user_error('Invalid database connection', E_USER_ERROR);
101
        }
102
    }
103
104
    /**
105
     * Helper function to execute a query
106
     *
107
     * @param mixed $conn Connection object/resource
108
     * @param string $sql SQL string to execute
109
     * @return array List of first value from each resulting row
110
     */
111
    protected function query($conn, $sql)
112
    {
113
        $items = array();
114
        if ($conn instanceof PDO) {
115
            $result = $conn->query($sql);
116
            if ($result) {
117
                foreach ($result as $row) {
118
                    $items[] = $row[0];
119
                }
120
            }
121
        } elseif (is_resource($conn)) {
122
            $result = sqlsrv_query($conn, $sql);
123
            if ($result) {
124
                while ($row = sqlsrv_fetch_array($result, SQLSRV_FETCH_NUMERIC)) {
125
                    $items[] = $row[0];
126
                }
127
            }
128
        }
129
        return $items;
130
    }
131
132
    public function requireDatabaseFunctions($databaseConfig)
133
    {
134
        $data = DatabaseAdapterRegistry::get_adapter($databaseConfig['type']);
135
        return !empty($data['supported']);
136
    }
137
138 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...
139
    {
140
        $conn = $this->createConnection($databaseConfig, $error);
141
        $success = !empty($conn);
142
143
        return array(
144
            'success' => $success,
145
            'error' => $error
146
        );
147
    }
148
149 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...
150
    {
151
        $conn = $this->createConnection($databaseConfig, $error);
152
        $success = !empty($conn);
153
154
        return array(
155
            'success' => $success,
156
            'connection' => $conn,
157
            'error' => $error
158
        );
159
    }
160
161
    public function getDatabaseVersion($databaseConfig)
162
    {
163
        $conn = $this->createConnection($databaseConfig, $error);
164
        $result = $this->query($conn, "SELECT CONVERT(char(15), SERVERPROPERTY('ProductVersion'))");
165
        return empty($result) ? 0 : reset($result);
166
    }
167
168
    /**
169
     * Ensure that the SQL Server version is at least 10.00.2531 (SQL Server 2008 SP1).
170
     *
171
     * @see http://www.sqlteam.com/article/sql-server-versions
172
     * @param array $databaseConfig Associative array of db configuration, e.g. "server", "username" etc
173
     * @return array Result - e.g. array('success' => true, 'error' => 'details of error')
174
     */
175
    public function requireDatabaseVersion($databaseConfig)
176
    {
177
        $success = false;
178
        $error = '';
179
        $version = $this->getDatabaseVersion($databaseConfig);
180
181
        if ($version) {
182
            $success = version_compare($version, '10.00.2531', '>=');
183
            if (!$success) {
184
                $error = "Your SQL Server version is $version. It's recommended you use at least 10.00.2531 (SQL Server 2008 SP1).";
185
            }
186
        } else {
187
            $error = "Your SQL Server version could not be determined.";
188
        }
189
190
        return array(
191
            'success' => $success,
192
            'error' => $error
193
        );
194
    }
195
196
    public function requireDatabaseOrCreatePermissions($databaseConfig)
197
    {
198
        $conn = $this->createConnection($databaseConfig, $error);
199
        if (empty($conn)) {
200
            $success = false;
201
            $alreadyExists = false;
202
        } elseif ($databaseConfig['type'] == 'MSSQLAzureDatabase') {
203
            // Don't bother with DB selection for azure, as it's not supported
204
            $success = true;
205
            $alreadyExists = true;
206
        } else {
207
            // does this database exist already?
208
            $list = $this->query($conn, 'SELECT NAME FROM sys.sysdatabases');
209
            if (in_array($databaseConfig['database'], $list)) {
210
                $success = true;
211
                $alreadyExists = true;
212
            } else {
213
                $permissions = $this->query($conn, "select COUNT(*) from sys.fn_my_permissions('','') where permission_name like 'CREATE ANY DATABASE' or permission_name like 'CREATE DATABASE';");
214
                $success = $permissions[0] > 0;
215
                $alreadyExists = false;
216
            }
217
        }
218
219
        return array(
220
            'success' => $success,
221
            'alreadyExists' => $alreadyExists
222
        );
223
    }
224
225
    public function requireDatabaseAlterPermissions($databaseConfig)
226
    {
227
        $success = false;
228
        $conn = $this->createConnection($databaseConfig, $error);
229
        if (!empty($conn)) {
230
            if (!$this->isAzure($databaseConfig)) {
231
                // Make sure to select the current database when checking permission against this database
232
                $this->query($conn, "USE \"{$databaseConfig['database']}\"");
233
            }
234
            $permissions = $this->query($conn, "select COUNT(*) from sys.fn_my_permissions(NULL,'DATABASE') WHERE permission_name like 'create table';");
235
            $success = $permissions[0] > 0;
236
        }
237
238
        return array(
239
            'success' => $success,
240
            'applies' => true
241
        );
242
    }
243
}
244