Failed Conditions
Pull Request — master (#3217)
by Matthias
60:35
created

MysqliStatement::processLongData()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 9
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 4

Importance

Changes 0
Metric Value
eloc 6
dl 0
loc 9
ccs 2
cts 2
cp 1
rs 10
c 0
b 0
f 0
cc 4
nc 4
nop 0
crap 4
1
<?php
2
/*
3
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
4
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
5
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
6
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
7
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
8
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
9
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
10
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
11
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
12
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
13
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
14
 *
15
 * This software consists of voluntary contributions made by many individuals
16
 * and is licensed under the MIT license. For more information, see
17
 * <http://www.doctrine-project.org>.
18
 */
19
20
namespace Doctrine\DBAL\Driver\Mysqli;
21
22
use Doctrine\DBAL\Driver\Statement;
23
use Doctrine\DBAL\Driver\StatementIterator;
24
use Doctrine\DBAL\Exception\InvalidArgumentException;
25
use Doctrine\DBAL\FetchMode;
26
use Doctrine\DBAL\ParameterType;
27
use function array_combine;
28
use function array_fill;
29
use function count;
30
use function feof;
31
use function fread;
32
use function get_resource_type;
33
use function is_resource;
34
use function str_repeat;
35
36
/**
37
 * @author Kim Hemsø Rasmussen <[email protected]>
38
 */
39
class MysqliStatement implements \IteratorAggregate, Statement
40
{
41
    /**
42
     * @var array
43
     */
44
    protected static $_paramTypeMap = [
45
        ParameterType::STRING       => 's',
46
        ParameterType::BINARY       => 's',
47
        ParameterType::BOOLEAN      => 'i',
48
        ParameterType::NULL         => 's',
49
        ParameterType::INTEGER      => 'i',
50
        ParameterType::LARGE_OBJECT => 'b',
51
    ];
52
53
    /**
54
     * @var \mysqli
55
     */
56
    protected $_conn;
57
58
    /**
59
     * @var \mysqli_stmt
60
     */
61
    protected $_stmt;
62
63
    /**
64
     * @var null|boolean|array
65
     */
66
    protected $_columnNames;
67
68
    /**
69
     * @var null|array
70
     */
71
    protected $_rowBindedValues;
72
73
    /**
74
     * @var array
75
     */
76
    protected $_bindedValues;
77
78
    /**
79
     * @var string
80
     */
81
    protected $types;
82
83
    /**
84
     * Contains ref values for bindValue().
85
     *
86
     * @var array
87
     */
88
    protected $_values = [];
89
90
    /**
91
     * Contains values from bindValue() that need to be sent
92
     * using send_long_data *after* bind_param has been called.
93
     *
94
     * @var resource[]
95
     */
96
    private $longData = [];
97
98
    /**
99
     * @var int
100
     */
101
    protected $_defaultFetchMode = FetchMode::MIXED;
102
103 765
    /**
104
     * Indicates whether the statement is in the state when fetching results is possible
105 765
     *
106 765
     * @var bool
107 765
     */
108 12
    private $result = false;
109
110
    /**
111 753
     * @param \mysqli $conn
112 753
     * @param string  $prepareString
113 366
     *
114 366
     * @throws \Doctrine\DBAL\Driver\Mysqli\MysqliException
115
     */
116 753
    public function __construct(\mysqli $conn, $prepareString)
117
    {
118
        $this->_conn = $conn;
119
        $this->_stmt = $conn->prepare($prepareString);
120
        if (false === $this->_stmt) {
0 ignored issues
show
introduced by
The condition $this->_stmt is always false. If $this->_stmt can have other possible types, add them to lib/Doctrine/DBAL/Driver...qli/MysqliStatement.php:59
Loading history...
121 21
            throw new MysqliException($this->_conn->error, $this->_conn->sqlstate, $this->_conn->errno);
122
        }
123 21
124
        $paramCount = $this->_stmt->param_count;
125
        if (0 < $paramCount) {
126 21
            $this->types = str_repeat('s', $paramCount);
127 21
            $this->_bindedValues = array_fill(1, $paramCount, null);
128
        }
129
    }
130
131
    /**
132
     * {@inheritdoc}
133 21
     */
134 21
    public function bindParam($column, &$variable, $type = ParameterType::STRING, $length = null)
135
    {
136 21
        if (null === $type) {
137
            $type = 's';
138
        } else {
139
            if (isset(self::$_paramTypeMap[$type])) {
140
                $type = self::$_paramTypeMap[$type];
141
            } else {
142 102
                throw new MysqliException("Unknown type: '{$type}'");
143
            }
144 102
        }
145
146
        $this->_bindedValues[$column] =& $variable;
147 102
        $this->types[$column - 1] = $type;
148 102
149
        return true;
150
    }
151
152
    /**
153
     * {@inheritdoc}
154 102
     */
155 102
    public function bindValue($param, $value, $type = ParameterType::STRING)
156 102
    {
157
        if ($type === ParameterType::LARGE_OBJECT) {
158 102
            if (is_resource($value)) {
159
                if (get_resource_type($value) !== 'stream') {
160
                    throw new InvalidArgumentException('Resources passed with the LARGE_OBJECT parameter type must be stream resources.');
161
                }
162
163
                $this->longData[$param - 1] = $value;
164 729
                $value                      = null;
165
            } else {
166 729
                $type = ParameterType::STRING;
167 366
            }
168 264
        }
169 264
170
        if (null === $type) {
171
            $type = 's';
172 123
        } else {
173
            if (isset(self::$_paramTypeMap[$type])) {
174
                $type = self::$_paramTypeMap[$type];
175
            } else {
176
                throw new MysqliException("Unknown type: '{$type}'");
177
            }
178 729
        }
179 18
180
        $this->_values[$param] = $value;
181
        $this->_bindedValues[$param] =& $this->_values[$param];
182 726
        $this->types[$param - 1] = $type;
183 726
184 726
        return true;
185 669
    }
186 669
187 669
    /**
188
     * {@inheritdoc}
189 669
     */
190
    public function execute($params = null)
191 669
    {
192
        if (null !== $this->_bindedValues) {
193 286
            if (null !== $params) {
194
                if ( ! $this->_bindValues($params)) {
195
                    throw new MysqliException($this->_stmt->error, $this->_stmt->errno);
196
                }
197 726
            } else {
198
                if (! $this->_stmt->bind_param($this->types, ...$this->_bindedValues)) {
199
                    throw new MysqliException($this->_stmt->error, $this->_stmt->sqlstate, $this->_stmt->errno);
200
                }
201 669
                $this->processLongData();
202
            }
203
        }
204
205
        if ( ! $this->_stmt->execute()) {
206
            throw new MysqliException($this->_stmt->error, $this->_stmt->sqlstate, $this->_stmt->errno);
207
        }
208
209
        if (null === $this->_columnNames) {
210
            $meta = $this->_stmt->result_metadata();
211
            if (false !== $meta) {
212
                $columnNames = [];
213
                foreach ($meta->fetch_fields() as $col) {
214 669
                    $columnNames[] = $col->name;
215
                }
216 669
                $meta->free();
217 669
218 669
                $this->_columnNames = $columnNames;
219
            } else {
220
                $this->_columnNames = false;
221 669
            }
222
        }
223
224
        if (false !== $this->_columnNames) {
225
            // Store result of every execution which has it. Otherwise it will be impossible
226 726
            // to execute a new statement in case if the previous one has non-fetched rows
227
            // @link http://dev.mysql.com/doc/refman/5.7/en/commands-out-of-sync.html
228 726
            $this->_stmt->store_result();
229
230
            // Bind row values _after_ storing the result. Otherwise, if mysqli is compiled with libmysql,
231
            // it will have to allocate as much memory as it may be needed for the given column type
232
            // (e.g. for a LONGBLOB field it's 4 gigabytes)
233
            // @link https://bugs.php.net/bug.php?id=51386#1270673122
234
            //
235
            // Make sure that the values are bound after each execution. Otherwise, if closeCursor() has been
236
            // previously called on the statement, the values are unbound making the statement unusable.
237
            //
238 264
            // It's also important that row values are bound after _each_ call to store_result(). Otherwise,
239
            // if mysqli is compiled with libmysql, subsequently fetched string values will get truncated
240 264
            // to the length of the ones fetched during the previous execution.
241 264
            $this->_rowBindedValues = array_fill(0, count($this->_columnNames), null);
0 ignored issues
show
Bug introduced by
It seems like $this->_columnNames can also be of type true; however, parameter $var of count() does only seem to accept Countable|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

241
            $this->_rowBindedValues = array_fill(0, count(/** @scrutinizer ignore-type */ $this->_columnNames), null);
Loading history...
242
243 264
            $refs = [];
244 264
            foreach ($this->_rowBindedValues as $key => &$value) {
245
                $refs[$key] =& $value;
246
            }
247 264
248
            if (! $this->_stmt->bind_result(...$refs)) {
249
                throw new MysqliException($this->_stmt->error, $this->_stmt->sqlstate, $this->_stmt->errno);
250
            }
251
        }
252
253 645
        $this->result = true;
254
255 645
        return true;
256
    }
257 645
258 612
    /**
259 612
     * Handle $this->_longData after regular query parameters have been bound
260 612
     *
261
     * @throws MysqliException
262
     */
263 612
    private function processLongData()
264
    {
265
        foreach ($this->longData as $paramNr => $stream) {
266 372
            while (! feof($stream)) {
267
                $chunk = fread($stream, 8192);
268
                if ($chunk === false) {
269
                    throw new MysqliException("Failed reading the stream resource for parameter offset ${paramNr}.");
270
                }
271
                $this->sendLongData($paramNr, $chunk);
272 672
            }
273
        }
274
    }
275
276 672
    /**
277 27
     * Bind parameters using send_long_data
278
     *
279
     * @param int    $paramNr  Parameter offset
280 645
     * @param string $longData A chunk of data to send
281
     *
282 645
     * @throws MysqliException
283 3
     */
284
    private function sendLongData($paramNr, $longData) : void
285
    {
286 645
        if (! $this->_stmt->send_long_data($paramNr, $longData)) {
287 645
            throw new MysqliException($this->_stmt->error, $this->_stmt->sqlstate, $this->_stmt->errno);
288 372
        }
289
    }
290
291 612
    /**
292
     * Binds a array of values to bound parameters.
293
     *
294
     * @param array $values
295
     *
296 612
     * @return bool
297 162
     */
298
    private function _bindValues($values)
299 456
    {
300 447
        $params = [];
301
        $types = str_repeat('s', count($values));
302 9
303 6
        foreach ($values as &$v) {
304 6
            $params[] =& $v;
305
        }
306 6
307
        return $this->_stmt->bind_param($types, ...$params);
308 3
    }
309 3
310 3
    /**
311
     * @return mixed[]|false
312 3
     */
313 3
    private function _fetch()
314
    {
315
        $ret = $this->_stmt->fetch();
316 3
317
        if (true === $ret) {
318
            $values = [];
319
            foreach ($this->_rowBindedValues as $v) {
320
                $values[] = $v;
321
            }
322
323
            return $values;
324
        }
325
326 327
        return $ret;
327
    }
328 327
329
    /**
330 327
     * {@inheritdoc}
331
     */
332 327
    public function fetch($fetchMode = null, $cursorOrientation = \PDO::FETCH_ORI_NEXT, $cursorOffset = 0)
333 12
    {
334 12
        // do not try fetching from the statement if it's not expected to contain result
335
        // in order to prevent exceptional situation
336
        if (!$this->result) {
337 315
            return false;
338 294
        }
339
340
        $fetchMode = $fetchMode ?: $this->_defaultFetchMode;
341
342 327
        if ($fetchMode === FetchMode::COLUMN) {
343
            return $this->fetchColumn();
344
        }
345
346
        $values = $this->_fetch();
347
        if (null === $values) {
0 ignored issues
show
introduced by
The condition null === $values is always false.
Loading history...
348 162
            return false;
349
        }
350 162
351
        if (false === $values) {
352 162
            throw new MysqliException($this->_stmt->error, $this->_stmt->sqlstate, $this->_stmt->errno);
353 30
        }
354
355
        switch ($fetchMode) {
356 144
            case FetchMode::NUMERIC:
357
                return $values;
358
359
            case FetchMode::ASSOCIATIVE:
360
                return array_combine($this->_columnNames, $values);
0 ignored issues
show
Bug introduced by
It seems like $this->_columnNames can also be of type null and boolean; however, parameter $keys of array_combine() 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

360
                return array_combine(/** @scrutinizer ignore-type */ $this->_columnNames, $values);
Loading history...
361
362
            case FetchMode::MIXED:
363
                $ret = array_combine($this->_columnNames, $values);
364
                $ret += $values;
365
366
                return $ret;
367
368
            case FetchMode::STANDARD_OBJECT:
369
                $assoc = array_combine($this->_columnNames, $values);
370
                $ret = new \stdClass();
371
372
                foreach ($assoc as $column => $value) {
373
                    $ret->$column = $value;
374
                }
375
376
                return $ret;
377
378 60
            default:
379
                throw new MysqliException("Unknown fetch type '{$fetchMode}'");
380 60
        }
381 60
    }
382
383 60
    /**
384
     * {@inheritdoc}
385
     */
386
    public function fetchAll($fetchMode = null, $fetchArgument = null, $ctorArgs = null)
387
    {
388
        $fetchMode = $fetchMode ?: $this->_defaultFetchMode;
389 279
390
        $rows = [];
391 279
392 279
        if ($fetchMode === FetchMode::COLUMN) {
393
            while (($row = $this->fetchColumn()) !== false) {
394
                $rows[] = $row;
395
            }
396
        } else {
397
            while (($row = $this->fetch($fetchMode)) !== false) {
398
                $rows[] = $row;
399
            }
400
        }
401 12
402
        return $rows;
403 12
    }
404
405
    /**
406
     * {@inheritdoc}
407
     */
408
    public function fetchColumn($columnIndex = 0)
409 705
    {
410
        $row = $this->fetch(FetchMode::NUMERIC);
411 705
412
        if (false === $row) {
413 705
            return false;
414
        }
415
416
        return $row[$columnIndex] ?? null;
417
    }
418
419 41
    /**
420
     * {@inheritdoc}
421 41
     */
422
    public function errorCode()
423
    {
424
        return $this->_stmt->errno;
425
    }
426
427
    /**
428
     * {@inheritdoc}
429
     */
430
    public function errorInfo()
431
    {
432
        return $this->_stmt->error;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $this->_stmt->error returns the type string which is incompatible with the return type mandated by Doctrine\DBAL\Driver\Statement::errorInfo() of array.

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...
433
    }
434
435
    /**
436
     * {@inheritdoc}
437
     */
438
    public function closeCursor()
439
    {
440
        $this->_stmt->free_result();
441
        $this->result = false;
442
443
        return true;
444
    }
445
446
    /**
447
     * {@inheritdoc}
448
     */
449
    public function rowCount()
450
    {
451
        if (false === $this->_columnNames) {
452
            return $this->_stmt->affected_rows;
453
        }
454
455
        return $this->_stmt->num_rows;
456
    }
457
458
    /**
459
     * {@inheritdoc}
460
     */
461
    public function columnCount()
462
    {
463
        return $this->_stmt->field_count;
464
    }
465
466
    /**
467
     * {@inheritdoc}
468
     */
469
    public function setFetchMode($fetchMode, $arg2 = null, $arg3 = null)
470
    {
471
        $this->_defaultFetchMode = $fetchMode;
472
473
        return true;
474
    }
475
476
    /**
477
     * {@inheritdoc}
478
     */
479
    public function getIterator()
480
    {
481
        return new StatementIterator($this);
482
    }
483
}
484