Failed Conditions
Pull Request — develop (#3486)
by Sergei
194:17 queued 129:15
created

SQLAnywhereStatement   B

Complexity

Total Complexity 52

Size/Duplication

Total Lines 320
Duplicated Lines 0 %

Test Coverage

Coverage 1.8%

Importance

Changes 0
Metric Value
wmc 52
eloc 120
dl 0
loc 320
ccs 2
cts 111
cp 0.018
rs 7.44
c 0
b 0
f 0

15 Methods

Rating   Name   Duplication   Size   Complexity  
A fetchAll() 0 24 6
A rowCount() 0 3 1
A setFetchMode() 0 13 3
A getIterator() 0 3 1
A castObject() 0 34 5
A __construct() 0 11 3
A execute() 0 19 6
A errorCode() 0 3 1
A fetchColumn() 0 10 3
B fetch() 0 43 11
A columnCount() 0 3 1
A errorInfo() 0 3 1
A bindValue() 0 3 1
A closeCursor() 0 3 1
B bindParam() 0 26 8

How to fix   Complexity   

Complex Class

Complex classes like SQLAnywhereStatement 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 SQLAnywhereStatement, and based on these observations, apply Extract Interface, too.

1
<?php
2
3
namespace Doctrine\DBAL\Driver\SQLAnywhere;
4
5
use Doctrine\DBAL\DBALException;
6
use Doctrine\DBAL\Driver\Statement;
7
use Doctrine\DBAL\Driver\StatementIterator;
8
use Doctrine\DBAL\FetchMode;
9
use Doctrine\DBAL\ParameterType;
10
use IteratorAggregate;
11
use ReflectionClass;
12
use ReflectionObject;
13
use stdClass;
14
use const SASQL_BOTH;
0 ignored issues
show
Bug introduced by
The constant SASQL_BOTH was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
15
use function array_key_exists;
16
use function count;
17
use function func_get_args;
18
use function gettype;
19
use function is_array;
20
use function is_int;
21
use function is_object;
22
use function is_resource;
23
use function is_string;
24
use function sasql_fetch_array;
0 ignored issues
show
introduced by
The function sasql_fetch_array was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
25
use function sasql_fetch_assoc;
0 ignored issues
show
introduced by
The function sasql_fetch_assoc was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
26
use function sasql_fetch_object;
0 ignored issues
show
introduced by
The function sasql_fetch_object was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
27
use function sasql_fetch_row;
0 ignored issues
show
introduced by
The function sasql_fetch_row was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
28
use function sasql_prepare;
0 ignored issues
show
introduced by
The function sasql_prepare was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
29
use function sasql_stmt_affected_rows;
0 ignored issues
show
introduced by
The function sasql_stmt_affected_rows was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
30
use function sasql_stmt_bind_param_ex;
0 ignored issues
show
introduced by
The function sasql_stmt_bind_param_ex was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
31
use function sasql_stmt_errno;
0 ignored issues
show
introduced by
The function sasql_stmt_errno was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
32
use function sasql_stmt_error;
0 ignored issues
show
introduced by
The function sasql_stmt_error was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
33
use function sasql_stmt_execute;
0 ignored issues
show
introduced by
The function sasql_stmt_execute was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
34
use function sasql_stmt_field_count;
0 ignored issues
show
introduced by
The function sasql_stmt_field_count was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
35
use function sasql_stmt_reset;
0 ignored issues
show
introduced by
The function sasql_stmt_reset was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
36
use function sasql_stmt_result_metadata;
0 ignored issues
show
introduced by
The function sasql_stmt_result_metadata was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
37
use function sprintf;
38
39
/**
40
 * SAP SQL Anywhere implementation of the Statement interface.
41
 */
42
class SQLAnywhereStatement implements IteratorAggregate, Statement
43
{
44
    /** @var resource The connection resource. */
45
    private $conn;
46
47
    /** @var string Name of the default class to instantiate when fetching class instances. */
48
    private $defaultFetchClass = '\stdClass';
49
50
    /** @var mixed[] Constructor arguments for the default class to instantiate when fetching class instances. */
51
    private $defaultFetchClassCtorArgs = [];
52
53
    /** @var int Default fetch mode to use. */
54
    private $defaultFetchMode = FetchMode::MIXED;
55
56
    /** @var resource The result set resource to fetch. */
57
    private $result;
58
59
    /** @var resource The prepared SQL statement to execute. */
60
    private $stmt;
61
62
    /** @var mixed[] The references to bound parameter values. */
63
    private $boundValues = [];
64
65
    /**
66
     * Prepares given statement for given connection.
67
     *
68
     * @param resource $conn The connection resource to use.
69
     * @param string   $sql  The SQL statement to prepare.
70
     *
71
     * @throws SQLAnywhereException
72
     */
73
    public function __construct($conn, $sql)
74
    {
75
        if (! is_resource($conn)) {
76
            throw new SQLAnywhereException('Invalid SQL Anywhere connection resource: ' . $conn);
77
        }
78
79
        $this->conn = $conn;
80
        $this->stmt = sasql_prepare($conn, $sql);
0 ignored issues
show
Bug introduced by
The function sasql_prepare was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

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

80
        $this->stmt = /** @scrutinizer ignore-call */ sasql_prepare($conn, $sql);
Loading history...
81
82
        if (! is_resource($this->stmt)) {
83
            throw SQLAnywhereException::fromSQLAnywhereError($conn);
84
        }
85
    }
86
87
    /**
88
     * {@inheritdoc}
89
     *
90
     * @throws SQLAnywhereException
91
     */
92
    public function bindParam($column, &$variable, $type = ParameterType::STRING, $length = null) : void
93
    {
94
        switch ($type) {
95
            case ParameterType::INTEGER:
96
            case ParameterType::BOOLEAN:
97
                $type = 'i';
98
                break;
99
100
            case ParameterType::LARGE_OBJECT:
101
                $type = 'b';
102
                break;
103
104
            case ParameterType::NULL:
105
            case ParameterType::STRING:
106
            case ParameterType::BINARY:
107
                $type = 's';
108
                break;
109
110
            default:
111
                throw new SQLAnywhereException('Unknown type: ' . $type);
112
        }
113
114
        $this->boundValues[$column] =& $variable;
115
116
        if (! sasql_stmt_bind_param_ex($this->stmt, $column - 1, $variable, $type, $variable === null)) {
0 ignored issues
show
Bug introduced by
The function sasql_stmt_bind_param_ex was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

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

116
        if (! /** @scrutinizer ignore-call */ sasql_stmt_bind_param_ex($this->stmt, $column - 1, $variable, $type, $variable === null)) {
Loading history...
117
            throw SQLAnywhereException::fromSQLAnywhereError($this->conn, $this->stmt);
118
        }
119
    }
120
121
    /**
122
     * {@inheritdoc}
123
     */
124
    public function bindValue($param, $value, $type = ParameterType::STRING) : void
125
    {
126
        $this->bindParam($param, $value, $type);
127
    }
128
129
    /**
130
     * {@inheritdoc}
131
     */
132
    public function closeCursor() : void
133
    {
134
        sasql_stmt_reset($this->stmt);
1 ignored issue
show
Bug introduced by
The function sasql_stmt_reset was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

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

134
        /** @scrutinizer ignore-call */ 
135
        sasql_stmt_reset($this->stmt);
Loading history...
135
    }
136
137
    /**
138
     * {@inheritdoc}
139
     */
140
    public function columnCount()
141
    {
142
        return sasql_stmt_field_count($this->stmt);
0 ignored issues
show
Bug introduced by
The function sasql_stmt_field_count was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

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

142
        return /** @scrutinizer ignore-call */ sasql_stmt_field_count($this->stmt);
Loading history...
143
    }
144
145
    /**
146
     * {@inheritdoc}
147
     */
148
    public function errorCode()
149
    {
150
        return sasql_stmt_errno($this->stmt);
0 ignored issues
show
Bug introduced by
The function sasql_stmt_errno was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

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

150
        return /** @scrutinizer ignore-call */ sasql_stmt_errno($this->stmt);
Loading history...
151
    }
152
153
    /**
154
     * {@inheritdoc}
155
     */
156
    public function errorInfo()
157
    {
158
        return sasql_stmt_error($this->stmt);
0 ignored issues
show
Bug introduced by
The function sasql_stmt_error was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

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

158
        return /** @scrutinizer ignore-call */ sasql_stmt_error($this->stmt);
Loading history...
159
    }
160
161
    /**
162
     * {@inheritdoc}
163
     *
164
     * @throws SQLAnywhereException
165
     */
166
    public function execute($params = null) : void
167
    {
168
        if (is_array($params)) {
169
            $hasZeroIndex = array_key_exists(0, $params);
170
171
            foreach ($params as $key => $val) {
172
                if ($hasZeroIndex && is_int($key)) {
173
                    $this->bindValue($key + 1, $val);
174
                } else {
175
                    $this->bindValue($key, $val);
176
                }
177
            }
178
        }
179
180
        if (! sasql_stmt_execute($this->stmt)) {
0 ignored issues
show
Bug introduced by
The function sasql_stmt_execute was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

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

180
        if (! /** @scrutinizer ignore-call */ sasql_stmt_execute($this->stmt)) {
Loading history...
181
            throw SQLAnywhereException::fromSQLAnywhereError($this->conn, $this->stmt);
182
        }
183
184
        $this->result = sasql_stmt_result_metadata($this->stmt);
0 ignored issues
show
Bug introduced by
The function sasql_stmt_result_metadata was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

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

184
        $this->result = /** @scrutinizer ignore-call */ sasql_stmt_result_metadata($this->stmt);
Loading history...
185
    }
186
187
    /**
188
     * {@inheritdoc}
189
     *
190
     * @throws SQLAnywhereException
191
     */
192
    public function fetch($fetchMode = null, ...$args)
193
    {
194
        if (! is_resource($this->result)) {
195
            return false;
196
        }
197
198
        $fetchMode = $fetchMode ?: $this->defaultFetchMode;
199
200
        switch ($fetchMode) {
201
            case FetchMode::COLUMN:
202
                return $this->fetchColumn();
203
204
            case FetchMode::ASSOCIATIVE:
205
                return sasql_fetch_assoc($this->result);
0 ignored issues
show
Bug introduced by
The function sasql_fetch_assoc was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

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

205
                return /** @scrutinizer ignore-call */ sasql_fetch_assoc($this->result);
Loading history...
206
207
            case FetchMode::MIXED:
208
                return sasql_fetch_array($this->result, SASQL_BOTH);
0 ignored issues
show
Bug introduced by
The constant SASQL_BOTH was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
Bug introduced by
The function sasql_fetch_array was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

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

208
                return /** @scrutinizer ignore-call */ sasql_fetch_array($this->result, SASQL_BOTH);
Loading history...
209
210
            case FetchMode::CUSTOM_OBJECT:
211
                $className = $this->defaultFetchClass;
212
                $ctorArgs  = $this->defaultFetchClassCtorArgs;
213
214
                if (count($args) > 0) {
215
                    $className = $args[0];
216
                    $ctorArgs  = $args[1] ?? [];
217
                }
218
219
                $result = sasql_fetch_object($this->result);
0 ignored issues
show
Bug introduced by
The function sasql_fetch_object was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

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

219
                $result = /** @scrutinizer ignore-call */ sasql_fetch_object($this->result);
Loading history...
220
221
                if ($result instanceof stdClass) {
222
                    $result = $this->castObject($result, $className, $ctorArgs);
223
                }
224
225
                return $result;
226
227
            case FetchMode::NUMERIC:
228
                return sasql_fetch_row($this->result);
0 ignored issues
show
Bug introduced by
The function sasql_fetch_row was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

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

228
                return /** @scrutinizer ignore-call */ sasql_fetch_row($this->result);
Loading history...
229
230
            case FetchMode::STANDARD_OBJECT:
231
                return sasql_fetch_object($this->result);
232
233
            default:
234
                throw new SQLAnywhereException('Fetch mode is not supported: ' . $fetchMode);
235
        }
236
    }
237
238
    /**
239
     * {@inheritdoc}
240
     */
241
    public function fetchAll($fetchMode = null, ...$args)
242
    {
243
        $rows = [];
244
245
        switch ($fetchMode) {
246
            case FetchMode::CUSTOM_OBJECT:
247
                while (($row = $this->fetch(...func_get_args())) !== false) {
248
                    $rows[] = $row;
249
                }
250
                break;
251
252
            case FetchMode::COLUMN:
253
                while (($row = $this->fetchColumn()) !== false) {
254
                    $rows[] = $row;
255
                }
256
                break;
257
258
            default:
259
                while (($row = $this->fetch($fetchMode)) !== false) {
260
                    $rows[] = $row;
261
                }
262
        }
263
264
        return $rows;
265
    }
266
267
    /**
268
     * {@inheritdoc}
269
     */
270
    public function fetchColumn($columnIndex = 0)
271
    {
272
        $row = $this->fetch(FetchMode::NUMERIC);
273
274
        if ($row === false) {
275
            return false;
276
        }
277
278
        if (! array_key_exists($columnIndex, $row)) {
279
            throw DBALException::invalidColumnIndex($columnIndex, count($row));
280
        }
281
    }
282
283
    /**
284
     * {@inheritdoc}
285
     */
286 46
    public function getIterator()
287
    {
288 46
        return new StatementIterator($this);
289
    }
290
291
    /**
292
     * {@inheritdoc}
293
     */
294
    public function rowCount() : int
295
    {
296
        return sasql_stmt_affected_rows($this->stmt);
0 ignored issues
show
Bug introduced by
The function sasql_stmt_affected_rows was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

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

296
        return /** @scrutinizer ignore-call */ sasql_stmt_affected_rows($this->stmt);
Loading history...
297
    }
298
299
    /**
300
     * {@inheritdoc}
301
     */
302
    public function setFetchMode($fetchMode, ...$args) : void
303
    {
304
        $this->defaultFetchMode = $fetchMode;
305
306
        if (isset($args[0])) {
307
            $this->defaultFetchClass = $args[0];
308
        }
309
310
        if (! isset($args[1])) {
311
            return;
312
        }
313
314
        $this->defaultFetchClassCtorArgs = (array) $args[1];
315
    }
316
317
    /**
318
     * Casts a stdClass object to the given class name mapping its' properties.
319
     *
320
     * @param stdClass      $sourceObject     Object to cast from.
321
     * @param string|object $destinationClass Name of the class or class instance to cast to.
322
     * @param mixed[]       $ctorArgs         Arguments to use for constructing the destination class instance.
323
     *
324
     * @return object
325
     *
326
     * @throws SQLAnywhereException
327
     */
328
    private function castObject(stdClass $sourceObject, $destinationClass, array $ctorArgs = [])
329
    {
330
        if (! is_string($destinationClass)) {
331
            if (! is_object($destinationClass)) {
332
                throw new SQLAnywhereException(sprintf(
333
                    'Destination class has to be of type string or object, %s given.',
334
                    gettype($destinationClass)
335
                ));
336
            }
337
        } else {
338
            $destinationClass = new ReflectionClass($destinationClass);
339
            $destinationClass = $destinationClass->newInstanceArgs($ctorArgs);
340
        }
341
342
        $sourceReflection           = new ReflectionObject($sourceObject);
343
        $destinationClassReflection = new ReflectionObject($destinationClass);
344
345
        foreach ($sourceReflection->getProperties() as $sourceProperty) {
346
            $sourceProperty->setAccessible(true);
347
348
            $name  = $sourceProperty->getName();
349
            $value = $sourceProperty->getValue($sourceObject);
350
351
            if ($destinationClassReflection->hasProperty($name)) {
352
                $destinationProperty = $destinationClassReflection->getProperty($name);
353
354
                $destinationProperty->setAccessible(true);
355
                $destinationProperty->setValue($destinationClass, $value);
356
            } else {
357
                $destinationClass->$name = $value;
358
            }
359
        }
360
361
        return $destinationClass;
362
    }
363
}
364