Failed Conditions
Pull Request — develop (#3368)
by Benjamin
13:33
created

SQLSrvConnection::getSequenceNumber()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 12
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 2.0438

Importance

Changes 0
Metric Value
eloc 6
dl 0
loc 12
ccs 7
cts 9
cp 0.7778
rs 10
c 0
b 0
f 0
cc 2
nc 2
nop 1
crap 2.0438
1
<?php
2
3
namespace Doctrine\DBAL\Driver\SQLSrv;
4
5
use Doctrine\DBAL\Driver\Connection;
6
use Doctrine\DBAL\Driver\DriverException;
7
use Doctrine\DBAL\Driver\ResultStatement;
8
use Doctrine\DBAL\Driver\ServerInfoAwareConnection;
9
use Doctrine\DBAL\Driver\Statement as DriverStatement;
10
use const SQLSRV_ERR_ERRORS;
11
use function rtrim;
12
use function sqlsrv_begin_transaction;
13
use function sqlsrv_commit;
14
use function sqlsrv_configure;
15
use function sqlsrv_connect;
16
use function sqlsrv_errors;
17
use function sqlsrv_query;
18
use function sqlsrv_rollback;
19
use function sqlsrv_rows_affected;
20
use function sqlsrv_server_info;
21
use function str_replace;
22
23
/**
24
 * SQL Server implementation for the Connection interface.
25
 */
26
class SQLSrvConnection implements Connection, ServerInfoAwareConnection
27
{
28
    /** @var resource */
29
    protected $conn;
30
31
    /** @var LastInsertId */
32
    protected $lastInsertId;
33
34
    /**
35
     * @param string  $serverName
36
     * @param mixed[] $connectionOptions
37
     *
38
     * @throws DriverException
39
     */
40 26
    public function __construct($serverName, $connectionOptions)
41
    {
42 26
        if (! sqlsrv_configure('WarningsReturnAsErrors', 0)) {
43
            throw self::exceptionFromSqlSrvErrors();
44
        }
45
46 26
        $this->conn = sqlsrv_connect($serverName, $connectionOptions);
0 ignored issues
show
Documentation Bug introduced by
It seems like sqlsrv_connect($serverName, $connectionOptions) can also be of type false. However, the property $conn is declared as type resource. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
47 26
        if (! $this->conn) {
48 1
            throw self::exceptionFromSqlSrvErrors();
49
        }
50 26
        $this->lastInsertId = new LastInsertId();
51 26
    }
52
53
    /**
54
     * {@inheritdoc}
55
     */
56 23
    public function getServerVersion()
57
    {
58 23
        $serverInfo = sqlsrv_server_info($this->conn);
59
60 23
        return $serverInfo['SQLServerVersion'];
61
    }
62
63
    /**
64
     * {@inheritdoc}
65
     */
66 24
    public function requiresQueryForServerVersion()
67
    {
68 24
        return false;
69
    }
70
71
    /**
72
     * {@inheritDoc}
73
     */
74 244
    public function prepare(string $sql) : DriverStatement
75
    {
76 244
        return new SQLSrvStatement($this->conn, $sql, $this->lastInsertId);
77
    }
78
79
    /**
80
     * {@inheritDoc}
81
     */
82 180
    public function query(string $sql) : ResultStatement
83
    {
84 180
        $stmt = $this->prepare($sql);
85 180
        $stmt->execute();
86
87 180
        return $stmt;
88
    }
89
90
    /**
91
     * {@inheritDoc}
92
     */
93 7
    public function quote(string $value) : string
94
    {
95 7
        return "'" . str_replace("'", "''", $value) . "'";
96
    }
97
98
    /**
99
     * {@inheritDoc}
100
     */
101 162
    public function exec(string $statement) : int
102
    {
103 162
        $stmt = sqlsrv_query($this->conn, $statement);
104
105 162
        if ($stmt === false) {
106 103
            throw self::exceptionFromSqlSrvErrors();
107
        }
108
109 137
        return sqlsrv_rows_affected($stmt);
110
    }
111
112
    /**
113
     * {@inheritDoc}
114
     */
115 3
    public function lastInsertId() : string
116
    {
117 3
        $stmt = $this->query('SELECT @@IDENTITY');
118
119 3
        $result = $stmt->fetchColumn();
120
121 3
        if ($result === null) {
122 1
            throw DriverException::noInsertId();
123
        }
124
125 2
        return (string) $result;
126
    }
127
128
    /**
129
     * {@inheritDoc}
130
     */
131 2
    public function getSequenceNumber(string $name) : string
132
    {
133 2
        $stmt = $this->prepare('SELECT CONVERT(VARCHAR(MAX), current_value) FROM sys.sequences WHERE name = ?');
134 2
        $stmt->execute([$name]);
135
136 2
        $result = $stmt->fetchColumn();
137
138 2
        if ($result === false) {
139 1
            throw DriverException::noSuchSequence($name);
140
        }
141
142 1
        return (string) $result;
143
    }
144
145
    /**
146
     * {@inheritDoc}
147
     */
148 15
    public function beginTransaction() : void
149
    {
150 15
        if (! sqlsrv_begin_transaction($this->conn)) {
151
            throw self::exceptionFromSqlSrvErrors();
152
        }
153 15
    }
154
155
    /**
156
     * {@inheritDoc}
157
     */
158 6
    public function commit() : void
159
    {
160 6
        if (! sqlsrv_commit($this->conn)) {
161
            throw self::exceptionFromSqlSrvErrors();
162
        }
163 6
    }
164
165
    /**
166
     * {@inheritDoc}
167
     */
168 10
    public function rollBack() : void
169
    {
170 10
        if (! sqlsrv_rollback($this->conn)) {
171
            throw self::exceptionFromSqlSrvErrors();
172
        }
173 10
    }
174
175
    /**
176
     * {@inheritDoc}
177
     */
178
    public function errorCode()
179
    {
180
        $errors = sqlsrv_errors(SQLSRV_ERR_ERRORS);
181
        if ($errors) {
182
            return $errors[0]['code'];
183
        }
184
185
        return false;
0 ignored issues
show
Bug Best Practice introduced by
The expression return false returns the type false which is incompatible with the return type mandated by Doctrine\DBAL\Driver\Connection::errorCode() of null|string.

In the issue above, the returned value is violating the contract defined by the mentioned interface.

Let's take a look at an example:

interface HasName {
    /** @return string */
    public function getName();
}

class Name {
    public $name;
}

class User implements HasName {
    /** @return string|Name */
    public function getName() {
        return new Name('foo'); // This is a violation of the ``HasName`` interface
                                // which only allows a string value to be returned.
    }
}
Loading history...
186
    }
187
188
    /**
189
     * {@inheritDoc}
190
     */
191
    public function errorInfo()
192
    {
193
        return sqlsrv_errors(SQLSRV_ERR_ERRORS);
194
    }
195
196
    /**
197
     * Helper method to turn sql server errors into exception.
198
     */
199 105
    public static function exceptionFromSqlSrvErrors() : DriverException
200
    {
201 105
        $errors    = sqlsrv_errors(SQLSRV_ERR_ERRORS);
202 105
        $message   = '';
203 105
        $sqlState  = null;
204 105
        $errorCode = null;
205
206 105
        foreach ($errors as $error) {
207 105
            $message .= 'SQLSTATE [' . $error['SQLSTATE'] . ', ' . $error['code'] . ']: ' . $error['message'] . "\n";
208
209 105
            if ($sqlState === null) {
210 105
                $sqlState = $error['SQLSTATE'];
211
            }
212
213 105
            if ($errorCode !== null) {
214 1
                continue;
215
            }
216
217 105
            $errorCode = $error['code'];
218
        }
219 105
        if (! $message) {
220
            $message = 'SQL Server error occurred but no error message was retrieved from driver.';
221
        }
222
223 105
        return new DriverException(rtrim($message), $sqlState, $errorCode);
224
    }
225
}
226