Failed Conditions
Push — master ( b90d63...9b88bf )
by Sergei
29s queued 13s
created

DB2Statement   D

Complexity

Total Complexity 58

Size/Duplication

Total Lines 403
Duplicated Lines 0 %

Test Coverage

Coverage 52.68%

Importance

Changes 0
Metric Value
wmc 58
eloc 144
dl 0
loc 403
ccs 118
cts 224
cp 0.5268
rs 4.5599
c 0
b 0
f 0

19 Methods

Rating   Name   Duplication   Size   Complexity  
A bind() 0 6 2
A __construct() 0 3 1
A bindValue() 0 3 1
A bindParam() 0 27 4
B execute() 0 37 7
A columnCount() 0 3 2
A setFetchMode() 0 7 3
A fetchColumn() 0 9 2
A rowCount() 0 3 2
A closeCursor() 0 11 2
A writeStringToStream() 0 4 2
A errorCode() 0 3 1
A createTemporaryFile() 0 9 2
B castObject() 0 52 6
A getIterator() 0 3 1
B fetch() 0 45 11
A errorInfo() 0 5 1
A fetchAll() 0 22 6
A copyStreamToStream() 0 4 2

How to fix   Complexity   

Complex Class

Complex classes like DB2Statement often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use DB2Statement, and based on these observations, apply Extract Interface, too.

1
<?php
2
3
namespace Doctrine\DBAL\Driver\IBMDB2;
4
5
use Doctrine\DBAL\Driver\Statement;
6
use Doctrine\DBAL\Driver\StatementIterator;
7
use Doctrine\DBAL\FetchMode;
8
use Doctrine\DBAL\ParameterType;
9
use IteratorAggregate;
10
use PDO;
11
use ReflectionClass;
12
use ReflectionObject;
13
use ReflectionProperty;
14
use stdClass;
15
use const CASE_LOWER;
16
use const DB2_BINARY;
17
use const DB2_CHAR;
18
use const DB2_LONG;
19
use const DB2_PARAM_FILE;
20
use const DB2_PARAM_IN;
21
use function array_change_key_case;
22
use function db2_bind_param;
23
use function db2_execute;
24
use function db2_fetch_array;
25
use function db2_fetch_assoc;
26
use function db2_fetch_both;
27
use function db2_fetch_object;
28
use function db2_free_result;
29
use function db2_num_fields;
30
use function db2_num_rows;
31
use function db2_stmt_error;
32
use function db2_stmt_errormsg;
33
use function error_get_last;
34
use function fclose;
35
use function func_get_args;
36
use function func_num_args;
37
use function fwrite;
38
use function gettype;
39
use function is_object;
40
use function is_resource;
41
use function is_string;
42
use function ksort;
43
use function sprintf;
44
use function stream_copy_to_stream;
45
use function stream_get_meta_data;
46
use function strtolower;
47
use function tmpfile;
48
49
class DB2Statement implements IteratorAggregate, Statement
50
{
51
    /** @var resource */
52
    private $stmt;
53
54
    /** @var mixed[] */
55
    private $bindParam = [];
56
57
    /**
58
     * Map of LOB parameter positions to the tuples containing reference to the variable bound to the driver statement
59
     * and the temporary file handle bound to the underlying statement
60
     *
61
     * @var mixed[][]
62
     */
63
    private $lobs = [];
64
65
    /** @var string Name of the default class to instantiate when fetching class instances. */
66
    private $defaultFetchClass = '\stdClass';
67
68
    /** @var mixed[] Constructor arguments for the default class to instantiate when fetching class instances. */
69
    private $defaultFetchClassCtorArgs = [];
70
71
    /** @var int */
72
    private $defaultFetchMode = FetchMode::MIXED;
73
74
    /**
75
     * Indicates whether the statement is in the state when fetching results is possible
76
     *
77
     * @var bool
78
     */
79
    private $result = false;
80
81
    /**
82
     * @param resource $stmt
83
     */
84 230
    public function __construct($stmt)
85
    {
86 230
        $this->stmt = $stmt;
87 230
    }
88
89
    /**
90
     * {@inheritdoc}
91
     */
92 36
    public function bindValue($param, $value, $type = ParameterType::STRING)
93
    {
94 36
        return $this->bindParam($param, $value, $type);
95
    }
96
97
    /**
98
     * {@inheritdoc}
99
     */
100 44
    public function bindParam($column, &$variable, $type = ParameterType::STRING, $length = null)
101
    {
102 44
        switch ($type) {
103
            case ParameterType::INTEGER:
104 24
                $this->bind($column, $variable, DB2_PARAM_IN, DB2_LONG);
105 24
                break;
106
107
            case ParameterType::LARGE_OBJECT:
108 7
                if (isset($this->lobs[$column])) {
109
                    [, $handle] = $this->lobs[$column];
110
                    fclose($handle);
111
                }
112
113 7
                $handle = $this->createTemporaryFile();
114 7
                $path   = stream_get_meta_data($handle)['uri'];
115
116 7
                $this->bind($column, $path, DB2_PARAM_FILE, DB2_BINARY);
117
118 7
                $this->lobs[$column] = [&$variable, $handle];
119 7
                break;
120
121
            default:
122 37
                $this->bind($column, $variable, DB2_PARAM_IN, DB2_CHAR);
123 37
                break;
124
        }
125
126 44
        return true;
127
    }
128
129
    /**
130
     * @param int|string $parameter Parameter position or name
131
     * @param mixed      $variable
132
     *
133
     * @throws DB2Exception
134
     */
135 44
    private function bind($parameter, &$variable, int $parameterType, int $dataType) : void
136
    {
137 44
        $this->bindParam[$parameter] =& $variable;
138
139 44
        if (! db2_bind_param($this->stmt, $parameter, 'variable', $parameterType, $dataType)) {
0 ignored issues
show
Bug introduced by
It seems like $parameter can also be of type string; however, parameter $parameter_number of db2_bind_param() does only seem to accept integer, 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

139
        if (! db2_bind_param($this->stmt, /** @scrutinizer ignore-type */ $parameter, 'variable', $parameterType, $dataType)) {
Loading history...
140
            throw new DB2Exception(db2_stmt_errormsg());
141
        }
142 44
    }
143
144
    /**
145
     * {@inheritdoc}
146
     */
147 20
    public function closeCursor()
148
    {
149 20
        $this->bindParam = [];
150
151
        if (! db2_free_result($this->stmt)) {
152
            return false;
153 20
        }
154
155 20
        $this->result = false;
156
157
        return true;
158
    }
159 20
160
    /**
161 20
     * {@inheritdoc}
162
     */
163
    public function columnCount()
164
    {
165
        return db2_num_fields($this->stmt) ?: 0;
166
    }
167 4
168
    /**
169 4
     * {@inheritdoc}
170
     */
171
    public function errorCode()
172
    {
173 4
        return db2_stmt_error();
174
    }
175
176
    /**
177
     * {@inheritdoc}
178
     */
179
    public function errorInfo()
180
    {
181
        return [
182
            db2_stmt_errormsg(),
183
            db2_stmt_error(),
184
        ];
185
    }
186
187
    /**
188
     * {@inheritdoc}
189
     */
190
    public function execute($params = null)
191
    {
192
        if ($params === null) {
193
            ksort($this->bindParam);
194
195
            $params = [];
196
197
            foreach ($this->bindParam as $column => $value) {
198 222
                $params[] = $value;
199
            }
200 222
        }
201
202
        foreach ($this->lobs as [$source, $target]) {
203
            if (is_resource($source)) {
204 222
                $this->copyStreamToStream($source, $target);
205 200
206
                continue;
207 200
            }
208
209 200
            $this->writeStringToStream($source, $target);
210 44
        }
211
212
        $retval = db2_execute($this->stmt, $params);
213
214 222
        foreach ($this->lobs as [, $handle]) {
215 7
            fclose($handle);
216 3
        }
217
218 3
        $this->lobs = [];
219
220
        if ($retval === false) {
221 5
            throw new DB2Exception(db2_stmt_errormsg());
222
        }
223
224 222
        $this->result = true;
225
226 217
        return $retval;
227 7
    }
228
229
    /**
230 217
     * {@inheritdoc}
231
     */
232 217
    public function setFetchMode($fetchMode, $arg2 = null, $arg3 = null)
233
    {
234
        $this->defaultFetchMode          = $fetchMode;
235
        $this->defaultFetchClass         = $arg2 ?: $this->defaultFetchClass;
236 217
        $this->defaultFetchClassCtorArgs = $arg3 ? (array) $arg3 : $this->defaultFetchClassCtorArgs;
237
238 217
        return true;
239
    }
240
241
    /**
242
     * {@inheritdoc}
243
     */
244 221
    public function getIterator()
245
    {
246 221
        return new StatementIterator($this);
247 221
    }
248 221
249
    /**
250 221
     * {@inheritdoc}
251
     */
252
    public function fetch($fetchMode = null, $cursorOrientation = PDO::FETCH_ORI_NEXT, $cursorOffset = 0)
253
    {
254
        // do not try fetching from the statement if it's not expected to contain result
255
        // in order to prevent exceptional situation
256 3
        if (! $this->result) {
257
            return false;
258 3
        }
259
260
        $fetchMode = $fetchMode ?: $this->defaultFetchMode;
261
        switch ($fetchMode) {
262
            case FetchMode::COLUMN:
263
                return $this->fetchColumn();
264 208
265
            case FetchMode::MIXED:
266
                return db2_fetch_both($this->stmt);
267
268 208
            case FetchMode::ASSOCIATIVE:
269 9
                return db2_fetch_assoc($this->stmt);
270
271
            case FetchMode::CUSTOM_OBJECT:
272 199
                $className = $this->defaultFetchClass;
273 199
                $ctorArgs  = $this->defaultFetchClassCtorArgs;
274
275 1
                if (func_num_args() >= 2) {
276
                    $args      = func_get_args();
277
                    $className = $args[1];
278 2
                    $ctorArgs  = $args[2] ?? [];
279
                }
280
281 136
                $result = db2_fetch_object($this->stmt);
282
283
                if ($result instanceof stdClass) {
284 3
                    $result = $this->castObject($result, $className, $ctorArgs);
285 3
                }
286
287 3
                return $result;
288 1
289 1
            case FetchMode::NUMERIC:
290 1
                return db2_fetch_array($this->stmt);
291
292
            case FetchMode::STANDARD_OBJECT:
293 3
                return db2_fetch_object($this->stmt);
294
295 3
            default:
296 3
                throw new DB2Exception('Given Fetch-Style ' . $fetchMode . ' is not supported.');
297
        }
298
    }
299 3
300
    /**
301
     * {@inheritdoc}
302 59
     */
303
    public function fetchAll($fetchMode = null, $fetchArgument = null, $ctorArgs = null)
304
    {
305 1
        $rows = [];
306
307
        switch ($fetchMode) {
308
            case FetchMode::CUSTOM_OBJECT:
309
                while (($row = $this->fetch(...func_get_args())) !== false) {
310
                    $rows[] = $row;
311
                }
312
                break;
313
            case FetchMode::COLUMN:
314
                while (($row = $this->fetchColumn()) !== false) {
315 95
                    $rows[] = $row;
316
                }
317 95
                break;
318
            default:
319 95
                while (($row = $this->fetch($fetchMode)) !== false) {
320
                    $rows[] = $row;
321 1
                }
322 1
        }
323
324 1
        return $rows;
325
    }
326 9
327 9
    /**
328
     * {@inheritdoc}
329 9
     */
330
    public function fetchColumn($columnIndex = 0)
331 85
    {
332 77
        $row = $this->fetch(FetchMode::NUMERIC);
333
334
        if ($row === false) {
335
            return false;
336 95
        }
337
338
        return $row[$columnIndex] ?? null;
339
    }
340
341
    /**
342 56
     * {@inheritdoc}
343
     */
344 56
    public function rowCount()
345
    {
346 56
        return @db2_num_rows($this->stmt) ? : 0;
347 15
    }
348
349
    /**
350 50
     * Casts a stdClass object to the given class name mapping its' properties.
351
     *
352
     * @param stdClass      $sourceObject     Object to cast from.
353
     * @param string|object $destinationClass Name of the class or class instance to cast to.
354
     * @param mixed[]       $ctorArgs         Arguments to use for constructing the destination class instance.
355
     *
356 86
     * @return object
357
     *
358 86
     * @throws DB2Exception
359
     */
360
    private function castObject(stdClass $sourceObject, $destinationClass, array $ctorArgs = [])
361
    {
362
        if (! is_string($destinationClass)) {
363
            if (! is_object($destinationClass)) {
364
                throw new DB2Exception(sprintf(
365
                    'Destination class has to be of type string or object, %s given.',
366
                    gettype($destinationClass)
367
                ));
368
            }
369
        } else {
370
            $destinationClass = new ReflectionClass($destinationClass);
371
            $destinationClass = $destinationClass->newInstanceArgs($ctorArgs);
372 3
        }
373
374 3
        $sourceReflection           = new ReflectionObject($sourceObject);
375
        $destinationClassReflection = new ReflectionObject($destinationClass);
376
        /** @var ReflectionProperty[] $destinationProperties */
377
        $destinationProperties = array_change_key_case($destinationClassReflection->getProperties(), CASE_LOWER);
378
379
        foreach ($sourceReflection->getProperties() as $sourceProperty) {
380
            $sourceProperty->setAccessible(true);
381
382 3
            $name  = $sourceProperty->getName();
383 3
            $value = $sourceProperty->getValue($sourceObject);
384
385
            // Try to find a case-matching property.
386 3
            if ($destinationClassReflection->hasProperty($name)) {
387 3
                $destinationProperty = $destinationClassReflection->getProperty($name);
388
389 3
                $destinationProperty->setAccessible(true);
390
                $destinationProperty->setValue($destinationClass, $value);
391 3
392 3
                continue;
393
            }
394 3
395 3
            $name = strtolower($name);
396
397
            // Try to find a property without matching case.
398 3
            // Fallback for the driver returning either all uppercase or all lowercase column names.
399
            if (isset($destinationProperties[$name])) {
400
                $destinationProperty = $destinationProperties[$name];
401
402
                $destinationProperty->setAccessible(true);
403
                $destinationProperty->setValue($destinationClass, $value);
404
405
                continue;
406
            }
407 3
408
            $destinationClass->$name = $value;
409
        }
410
411 3
        return $destinationClass;
412
    }
413
414
    /**
415
     * @return resource
416
     *
417
     * @throws DB2Exception
418
     */
419
    private function createTemporaryFile()
420 3
    {
421
        $handle = @tmpfile();
422
423 3
        if ($handle === false) {
424
            throw new DB2Exception('Could not create temporary file: ' . error_get_last()['message']);
425
        }
426
427
        return $handle;
428
    }
429
430
    /**
431 7
     * @param resource $source
432
     * @param resource $target
433 7
     *
434
     * @throws DB2Exception
435 7
     */
436
    private function copyStreamToStream($source, $target) : void
437
    {
438
        if (@stream_copy_to_stream($source, $target) === false) {
439 7
            throw new DB2Exception('Could not copy source stream to temporary file: ' . error_get_last()['message']);
440
        }
441
    }
442
443
    /**
444
     * @param resource $target
445
     *
446
     * @throws DB2Exception
447
     */
448 3
    private function writeStringToStream(string $string, $target) : void
449
    {
450 3
        if (@fwrite($target, $string) === false) {
451
            throw new DB2Exception('Could not write string to temporary file: ' . error_get_last()['message']);
452
        }
453 3
    }
454
}
455