Passed
Pull Request — master (#3808)
by Sergei
09:45
created

SQLSrvStatement::getIterator()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1.037

Importance

Changes 0
Metric Value
dl 0
loc 3
ccs 2
cts 3
cp 0.6667
rs 10
c 0
b 0
f 0
cc 1
eloc 1
nc 1
nop 0
crap 1.037
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Doctrine\DBAL\Driver\SQLSrv;
6
7
use Doctrine\DBAL\Driver\Statement;
8
use Doctrine\DBAL\Driver\StatementIterator;
9
use Doctrine\DBAL\Exception\InvalidColumnIndex;
10
use Doctrine\DBAL\FetchMode;
11
use Doctrine\DBAL\ParameterType;
12
use IteratorAggregate;
13
use const SQLSRV_ENC_BINARY;
14
use const SQLSRV_FETCH_ASSOC;
15
use const SQLSRV_FETCH_BOTH;
16
use const SQLSRV_FETCH_NUMERIC;
17
use const SQLSRV_PARAM_IN;
18
use function array_key_exists;
19
use function assert;
20
use function count;
21
use function in_array;
22
use function is_int;
23
use function sqlsrv_execute;
24
use function sqlsrv_fetch;
25
use function sqlsrv_fetch_array;
26
use function sqlsrv_fetch_object;
27
use function sqlsrv_get_field;
28
use function sqlsrv_next_result;
29
use function sqlsrv_num_fields;
30
use function SQLSRV_PHPTYPE_STREAM;
31
use function SQLSRV_PHPTYPE_STRING;
32
use function sqlsrv_prepare;
33
use function sqlsrv_rows_affected;
34
use function SQLSRV_SQLTYPE_VARBINARY;
35
use function stripos;
36
37
/**
38
 * SQL Server Statement.
39
 */
40
final class SQLSrvStatement implements IteratorAggregate, Statement
41
{
42
    /**
43
     * The SQLSRV Resource.
44
     *
45
     * @var resource
46
     */
47
    private $conn;
48
49
    /**
50
     * The SQL statement to execute.
51
     *
52
     * @var string
53
     */
54
    private $sql;
55
56
    /**
57
     * The SQLSRV statement resource.
58
     *
59
     * @var resource|null
60
     */
61
    private $stmt;
62
63
    /**
64
     * References to the variables bound as statement parameters.
65
     *
66
     * @var mixed
67
     */
68
    private $variables = [];
69
70
    /**
71
     * Bound parameter types.
72
     *
73
     * @var int[]
74
     */
75
    private $types = [];
76
77
    /**
78
     * Translations.
79
     *
80
     * @var int[]
81
     */
82
    private static $fetchMap = [
83
        FetchMode::MIXED       => SQLSRV_FETCH_BOTH,
84
        FetchMode::ASSOCIATIVE => SQLSRV_FETCH_ASSOC,
85
        FetchMode::NUMERIC     => SQLSRV_FETCH_NUMERIC,
86
    ];
87
88
    /**
89
     * The name of the default class to instantiate when fetching class instances.
90
     *
91
     * @var string
92
     */
93
    private $defaultFetchClass = '\stdClass';
94
95
    /**
96
     * The constructor arguments for the default class to instantiate when fetching class instances.
97
     *
98
     * @var mixed[]
99
     */
100
    private $defaultFetchClassCtorArgs = [];
101
102
    /**
103
     * The fetch style.
104
     *
105
     * @var int
106
     */
107
    private $defaultFetchMode = FetchMode::MIXED;
108
109
    /**
110
     * The last insert ID.
111
     *
112
     * @var LastInsertId|null
113
     */
114
    private $lastInsertId;
115
116
    /**
117
     * Indicates whether the statement is in the state when fetching results is possible
118
     *
119
     * @var bool
120
     */
121
    private $result = false;
122
123
    /**
124
     * Append to any INSERT query to retrieve the last insert id.
125
     */
126
    private const LAST_INSERT_ID_SQL = ';SELECT SCOPE_IDENTITY() AS LastInsertId;';
127
128
    /**
129
     * @param resource $conn
130
     */
131 324
    public function __construct($conn, string $sql, ?LastInsertId $lastInsertId = null)
132
    {
133 324
        $this->conn = $conn;
134 324
        $this->sql  = $sql;
135
136 324
        if (stripos($sql, 'INSERT INTO ') !== 0) {
137 317
            return;
138
        }
139
140 92
        $this->sql         .= self::LAST_INSERT_ID_SQL;
141 92
        $this->lastInsertId = $lastInsertId;
142 92
    }
143
144
    /**
145
     * {@inheritdoc}
146
     */
147 114
    public function bindValue($param, $value, int $type = ParameterType::STRING) : void
148
    {
149 114
        assert(is_int($param));
150
151 114
        $this->variables[$param] = $value;
152 114
        $this->types[$param]     = $type;
153 114
    }
154
155
    /**
156
     * {@inheritdoc}
157
     */
158 24
    public function bindParam($param, &$variable, int $type = ParameterType::STRING, ?int $length = null) : void
159
    {
160 24
        assert(is_int($param));
161
162 24
        $this->variables[$param] =& $variable;
163 24
        $this->types[$param]     = $type;
164
165
        // unset the statement resource if it exists as the new one will need to be bound to the new variable
166 24
        $this->stmt = null;
167 24
    }
168
169
    /**
170
     * {@inheritdoc}
171
     */
172 19
    public function closeCursor() : void
173
    {
174
        // not having the result means there's nothing to close
175 19
        if ($this->stmt === null || ! $this->result) {
176 3
            return;
177
        }
178
179
        // emulate it by fetching and discarding rows, similarly to what PDO does in this case
180
        // @link http://php.net/manual/en/pdostatement.closecursor.php
181
        // @link https://github.com/php/php-src/blob/php-7.0.11/ext/pdo/pdo_stmt.c#L2075
182
        // deliberately do not consider multiple result sets, since doctrine/dbal doesn't support them
183 16
        while (sqlsrv_fetch($this->stmt) !== false) {
184
        }
185
186 16
        $this->result = false;
187 16
    }
188
189
    /**
190
     * {@inheritdoc}
191
     */
192 4
    public function columnCount() : int
193
    {
194 4
        if ($this->stmt === null) {
195
            return 0;
196
        }
197
198 4
        return sqlsrv_num_fields($this->stmt) ?: 0;
199
    }
200
201
    /**
202
     * {@inheritdoc}
203
     */
204 317
    public function execute(?array $params = null) : void
205
    {
206 317
        if ($params) {
207 83
            foreach ($params as $key => $val) {
208 83
                if (is_int($key)) {
209 83
                    $this->bindValue($key + 1, $val);
210
                } else {
211
                    $this->bindValue($key, $val);
212
                }
213
            }
214
        }
215
216 317
        if (! $this->stmt) {
217 317
            $this->stmt = $this->prepare();
218
        }
219
220 316
        if (! sqlsrv_execute($this->stmt)) {
221
            throw SQLSrvException::fromSqlSrvErrors();
222
        }
223
224 316
        if ($this->lastInsertId) {
225 92
            sqlsrv_next_result($this->stmt);
226 92
            sqlsrv_fetch($this->stmt);
227 92
            $this->lastInsertId->setId(sqlsrv_get_field($this->stmt, 0));
228
        }
229
230 316
        $this->result = true;
231 316
    }
232
233
    /**
234
     * {@inheritdoc}
235
     */
236 317
    public function setFetchMode(int $fetchMode, ...$args) : void
237
    {
238 317
        $this->defaultFetchMode = $fetchMode;
239
240 317
        if (isset($args[0])) {
241 2
            $this->defaultFetchClass = $args[0];
242
        }
243
244 317
        if (! isset($args[1])) {
245 317
            return;
246
        }
247
248
        $this->defaultFetchClassCtorArgs = (array) $args[1];
249
    }
250
251
    /**
252
     * {@inheritdoc}
253
     */
254 1
    public function getIterator()
255
    {
256 1
        return new StatementIterator($this);
257
    }
258
259
    /**
260
     * {@inheritdoc}
261
     *
262
     * @throws SQLSrvException
263
     */
264 308
    public function fetch(?int $fetchMode = null, ...$args)
265
    {
266
        // do not try fetching from the statement if it's not expected to contain result
267
        // in order to prevent exceptional situation
268 308
        if ($this->stmt === null || ! $this->result) {
269 9
            return false;
270
        }
271
272 299
        $fetchMode = $fetchMode ?: $this->defaultFetchMode;
273
274 299
        if ($fetchMode === FetchMode::COLUMN) {
275 1
            return $this->fetchColumn();
276
        }
277
278 299
        if (isset(self::$fetchMap[$fetchMode])) {
279 295
            return sqlsrv_fetch_array($this->stmt, self::$fetchMap[$fetchMode]) ?: false;
280
        }
281
282 4
        if (in_array($fetchMode, [FetchMode::STANDARD_OBJECT, FetchMode::CUSTOM_OBJECT], true)) {
283 4
            $className = $this->defaultFetchClass;
284 4
            $ctorArgs  = $this->defaultFetchClassCtorArgs;
285
286 4
            if (count($args) > 0) {
287 1
                $className = $args[0];
288 1
                $ctorArgs  = $args[1] ?? [];
289
            }
290
291 4
            return sqlsrv_fetch_object($this->stmt, $className, $ctorArgs) ?: false;
292
        }
293
294
        throw new SQLSrvException('Fetch mode is not supported.');
295
    }
296
297
    /**
298
     * {@inheritdoc}
299
     */
300 120
    public function fetchAll(?int $fetchMode = null, ...$args) : array
301
    {
302 120
        $rows = [];
303
304 120
        switch ($fetchMode) {
305
            case FetchMode::CUSTOM_OBJECT:
306 1
                while (($row = $this->fetch($fetchMode, ...$args)) !== false) {
307 1
                    $rows[] = $row;
308
                }
309 1
                break;
310
311
            case FetchMode::COLUMN:
312 10
                while (($row = $this->fetchColumn()) !== false) {
313 10
                    $rows[] = $row;
314
                }
315 10
                break;
316
317
            default:
318 109
                while (($row = $this->fetch($fetchMode)) !== false) {
319 101
                    $rows[] = $row;
320
                }
321
        }
322
323 120
        return $rows;
324
    }
325
326
    /**
327
     * {@inheritdoc}
328
     */
329 198
    public function fetchColumn(int $columnIndex = 0)
330
    {
331 198
        $row = $this->fetch(FetchMode::NUMERIC);
332
333 198
        if ($row === false) {
334 16
            return false;
335
        }
336
337 192
        if (! array_key_exists($columnIndex, $row)) {
0 ignored issues
show
Bug introduced by
It seems like $row can also be of type object; however, parameter $search of array_key_exists() does only seem to accept array, maybe add an additional type check? ( Ignorable by Annotation )

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

337
        if (! array_key_exists($columnIndex, /** @scrutinizer ignore-type */ $row)) {
Loading history...
338 2
            throw InvalidColumnIndex::new($columnIndex, count($row));
339
        }
340
341 190
        return $row[$columnIndex];
342
    }
343
344
    /**
345
     * {@inheritdoc}
346
     */
347 91
    public function rowCount() : int
348
    {
349 91
        if ($this->stmt === null) {
350
            return 0;
351
        }
352
353 91
        return sqlsrv_rows_affected($this->stmt) ?: 0;
354
    }
355
356
    /**
357
     * Prepares SQL Server statement resource
358
     *
359
     * @return resource
360
     *
361
     * @throws SQLSrvException
362
     */
363 317
    private function prepare()
364
    {
365 317
        $params = [];
366
367 317
        foreach ($this->variables as $column => &$variable) {
368 136
            switch ($this->types[$column]) {
369
                case ParameterType::LARGE_OBJECT:
370 7
                    $params[$column - 1] = [
371 7
                        &$variable,
372
                        SQLSRV_PARAM_IN,
373 7
                        SQLSRV_PHPTYPE_STREAM(SQLSRV_ENC_BINARY),
374 7
                        SQLSRV_SQLTYPE_VARBINARY('max'),
375
                    ];
376 7
                    break;
377
378
                case ParameterType::BINARY:
379 1
                    $params[$column - 1] = [
380 1
                        &$variable,
381
                        SQLSRV_PARAM_IN,
382 1
                        SQLSRV_PHPTYPE_STRING(SQLSRV_ENC_BINARY),
383
                    ];
384 1
                    break;
385
386
                default:
387 133
                    $params[$column - 1] =& $variable;
388 133
                    break;
389
            }
390
        }
391
392 317
        $stmt = sqlsrv_prepare($this->conn, $this->sql, $params);
393
394 317
        if (! $stmt) {
0 ignored issues
show
introduced by
$stmt is of type false|resource, thus it always evaluated to false.
Loading history...
395 1
            throw SQLSrvException::fromSqlSrvErrors();
396
        }
397
398 316
        return $stmt;
399
    }
400
}
401