Completed
Push — master ( 8575c2...a53269 )
by Marco
02:31 queued 01:15
created

SQLAnywhereStatement::fetch()   C

Complexity

Conditions 11
Paths 11

Size

Total Lines 39
Code Lines 27

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 132

Importance

Changes 0
Metric Value
dl 0
loc 39
ccs 0
cts 32
cp 0
rs 5.2653
c 0
b 0
f 0
cc 11
eloc 27
nc 11
nop 3
crap 132

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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\SQLAnywhere;
21
22
use Doctrine\DBAL\Driver\StatementIterator;
23
use IteratorAggregate;
24
use PDO;
25
use Doctrine\DBAL\Driver\Statement;
26
27
/**
28
 * SAP SQL Anywhere implementation of the Statement interface.
29
 *
30
 * @author Steve Müller <[email protected]>
31
 * @link   www.doctrine-project.org
32
 * @since  2.5
33
 */
34
class SQLAnywhereStatement implements IteratorAggregate, Statement
35
{
36
    /**
37
     * @var resource The connection resource.
38
     */
39
    private $conn;
40
41
    /**
42
     * @var string Name of the default class to instantiate when fetch mode is \PDO::FETCH_CLASS.
43
     */
44
    private $defaultFetchClass = '\stdClass';
45
46
    /**
47
     * @var string Constructor arguments for the default class to instantiate when fetch mode is \PDO::FETCH_CLASS.
48
     */
49
    private $defaultFetchClassCtorArgs = [];
50
51
    /**
52
     * @var int Default fetch mode to use.
53
     */
54
    private $defaultFetchMode = PDO::FETCH_BOTH;
55
56
    /**
57
     * @var resource The result set resource to fetch.
58
     */
59
    private $result;
60
61
    /**
62
     * @var resource The prepared SQL statement to execute.
63
     */
64
    private $stmt;
65
66
    /**
67
     * Constructor.
68
     *
69
     * Prepares given statement for given connection.
70
     *
71
     * @param resource $conn The connection resource to use.
72
     * @param string   $sql  The SQL statement to prepare.
73
     *
74
     * @throws SQLAnywhereException
75
     */
76
    public function __construct($conn, $sql)
77
    {
78
        if ( ! is_resource($conn)) {
79
            throw new SQLAnywhereException('Invalid SQL Anywhere connection resource: ' . $conn);
80
        }
81
82
        $this->conn = $conn;
83
        $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

83
        $this->stmt = /** @scrutinizer ignore-call */ sasql_prepare($conn, $sql);
Loading history...
84
85
        if ( ! is_resource($this->stmt)) {
86
            throw SQLAnywhereException::fromSQLAnywhereError($conn);
87
        }
88
    }
89
90
    /**
91
     * {@inheritdoc}
92
     *
93
     * @throws SQLAnywhereException
94
     */
95
    public function bindParam($column, &$variable, $type = null, $length = null)
96
    {
97
        switch ($type) {
98
            case PDO::PARAM_INT:
99
            case PDO::PARAM_BOOL:
100
                $type = 'i';
101
                break;
102
            case PDO::PARAM_LOB:
103
                $type = 'b';
104
                break;
105
            case PDO::PARAM_NULL:
106
            case PDO::PARAM_STR:
107
                $type = 's';
108
                break;
109
            default:
110
                throw new SQLAnywhereException('Unknown type: ' . $type);
111
        }
112
113
        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

113
        if ( ! /** @scrutinizer ignore-call */ sasql_stmt_bind_param_ex($this->stmt, $column - 1, $variable, $type, $variable === null)) {
Loading history...
114
            throw SQLAnywhereException::fromSQLAnywhereError($this->conn, $this->stmt);
115
        }
116
117
        return true;
118
    }
119
120
    /**
121
     * {@inheritdoc}
122
     */
123
    public function bindValue($param, $value, $type = null)
124
    {
125
        return $this->bindParam($param, $value, $type);
126
    }
127
128
    /**
129
     * {@inheritdoc}
130
     *
131
     * @throws SQLAnywhereException
132
     */
133
    public function closeCursor()
134
    {
135
        if (!sasql_stmt_reset($this->stmt)) {
0 ignored issues
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

135
        if (!/** @scrutinizer ignore-call */ sasql_stmt_reset($this->stmt)) {
Loading history...
136
            throw SQLAnywhereException::fromSQLAnywhereError($this->conn, $this->stmt);
137
        }
138
139
        return true;
140
    }
141
142
    /**
143
     * {@inheritdoc}
144
     */
145
    public function columnCount()
146
    {
147
        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

147
        return /** @scrutinizer ignore-call */ sasql_stmt_field_count($this->stmt);
Loading history...
148
    }
149
150
    /**
151
     * {@inheritdoc}
152
     */
153
    public function errorCode()
154
    {
155
        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

155
        return /** @scrutinizer ignore-call */ sasql_stmt_errno($this->stmt);
Loading history...
156
    }
157
158
    /**
159
     * {@inheritdoc}
160
     */
161
    public function errorInfo()
162
    {
163
        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

163
        return /** @scrutinizer ignore-call */ sasql_stmt_error($this->stmt);
Loading history...
164
    }
165
166
    /**
167
     * {@inheritdoc}
168
     *
169
     * @throws SQLAnywhereException
170
     */
171
    public function execute($params = null)
172
    {
173
        if (is_array($params)) {
174
            $hasZeroIndex = array_key_exists(0, $params);
175
176
            foreach ($params as $key => $val) {
177
                $key = ($hasZeroIndex && is_numeric($key)) ? $key + 1 : $key;
178
179
                $this->bindValue($key, $val);
180
            }
181
        }
182
183
        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

183
        if ( ! /** @scrutinizer ignore-call */ sasql_stmt_execute($this->stmt)) {
Loading history...
184
            throw SQLAnywhereException::fromSQLAnywhereError($this->conn, $this->stmt);
185
        }
186
187
        $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

187
        $this->result = /** @scrutinizer ignore-call */ sasql_stmt_result_metadata($this->stmt);
Loading history...
188
189
        return true;
190
    }
191
192
    /**
193
     * {@inheritdoc}
194
     *
195
     * @throws SQLAnywhereException
196
     */
197
    public function fetch($fetchMode = null, $cursorOrientation = \PDO::FETCH_ORI_NEXT, $cursorOffset = 0)
198
    {
199
        if ( ! is_resource($this->result)) {
200
            return false;
201
        }
202
203
        $fetchMode = $fetchMode ?: $this->defaultFetchMode;
204
205
        switch ($fetchMode) {
206
            case PDO::FETCH_COLUMN:
207
                return $this->fetchColumn();
208
209
            case PDO::FETCH_ASSOC:
210
                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

210
                return /** @scrutinizer ignore-call */ sasql_fetch_assoc($this->result);
Loading history...
211
            case PDO::FETCH_BOTH:
212
                return sasql_fetch_array($this->result, SASQL_BOTH);
0 ignored issues
show
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

212
                return /** @scrutinizer ignore-call */ sasql_fetch_array($this->result, SASQL_BOTH);
Loading history...
Bug introduced by
The constant Doctrine\DBAL\Driver\SQLAnywhere\SASQL_BOTH was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
213
            case PDO::FETCH_CLASS:
214
                $className = $this->defaultFetchClass;
215
                $ctorArgs  = $this->defaultFetchClassCtorArgs;
216
217
                if (func_num_args() >= 2) {
218
                    $args      = func_get_args();
219
                    $className = $args[1];
220
                    $ctorArgs  = $args[2] ?? [];
221
                }
222
223
                $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

223
                $result = /** @scrutinizer ignore-call */ sasql_fetch_object($this->result);
Loading history...
224
225
                if ($result instanceof \stdClass) {
226
                    $result = $this->castObject($result, $className, $ctorArgs);
0 ignored issues
show
Bug introduced by
It seems like $ctorArgs can also be of type string; however, parameter $ctorArgs of Doctrine\DBAL\Driver\SQL...Statement::castObject() 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

226
                    $result = $this->castObject($result, $className, /** @scrutinizer ignore-type */ $ctorArgs);
Loading history...
227
                }
228
229
                return $result;
230
            case PDO::FETCH_NUM:
0 ignored issues
show
Coding Style introduced by
case statements should be defined using a colon.

As per the PSR-2 coding standard, case statements should not be wrapped in curly braces. There is no need for braces, since each case is terminated by the next break.

There is also the option to use a semicolon instead of a colon, this is discouraged because many programmers do not even know it works and the colon is universal between programming languages.

switch ($expr) {
    case "A": { //wrong
        doSomething();
        break;
    }
    case "B"; //wrong
        doSomething();
        break;
    case "C": //right
        doSomething();
        break;
}

To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.

Loading history...
231
                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

231
                return /** @scrutinizer ignore-call */ sasql_fetch_row($this->result);
Loading history...
232
            case PDO::FETCH_OBJ:
0 ignored issues
show
Coding Style introduced by
case statements should be defined using a colon.

As per the PSR-2 coding standard, case statements should not be wrapped in curly braces. There is no need for braces, since each case is terminated by the next break.

There is also the option to use a semicolon instead of a colon, this is discouraged because many programmers do not even know it works and the colon is universal between programming languages.

switch ($expr) {
    case "A": { //wrong
        doSomething();
        break;
    }
    case "B"; //wrong
        doSomething();
        break;
    case "C": //right
        doSomething();
        break;
}

To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.

Loading history...
233
                return sasql_fetch_object($this->result);
234
            default:
235
                throw new SQLAnywhereException('Fetch mode is not supported: ' . $fetchMode);
236
        }
237
    }
238
239
    /**
240
     * {@inheritdoc}
241
     */
242
    public function fetchAll($fetchMode = null, $fetchArgument = null, $ctorArgs = null)
243
    {
244
        $rows = [];
245
246
        switch ($fetchMode) {
247
            case PDO::FETCH_CLASS:
248
                while ($row = call_user_func_array([$this, 'fetch'], func_get_args())) {
249
                    $rows[] = $row;
250
                }
251
                break;
252
            case PDO::FETCH_COLUMN:
253
                while ($row = $this->fetchColumn()) {
254
                    $rows[] = $row;
255
                }
256
                break;
257
            default:
258
                while ($row = $this->fetch($fetchMode)) {
259
                    $rows[] = $row;
260
                }
261
        }
262
263
        return $rows;
264
    }
265
266
    /**
267
     * {@inheritdoc}
268
     */
269
    public function fetchColumn($columnIndex = 0)
270
    {
271
        $row = $this->fetch(PDO::FETCH_NUM);
272
273
        if (false === $row) {
274
            return false;
275
        }
276
277
        return $row[$columnIndex] ?? null;
278
    }
279
280
    /**
281
     * {@inheritdoc}
282
     */
283
    public function getIterator()
284
    {
285
        return new StatementIterator($this);
286
    }
287
288
    /**
289
     * {@inheritdoc}
290
     */
291
    public function rowCount()
292
    {
293
        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

293
        return /** @scrutinizer ignore-call */ sasql_stmt_affected_rows($this->stmt);
Loading history...
294
    }
295
296
    /**
297
     * {@inheritdoc}
298
     */
299
    public function setFetchMode($fetchMode, $arg2 = null, $arg3 = null)
300
    {
301
        $this->defaultFetchMode          = $fetchMode;
302
        $this->defaultFetchClass         = $arg2 ? $arg2 : $this->defaultFetchClass;
303
        $this->defaultFetchClassCtorArgs = $arg3 ? (array) $arg3 : $this->defaultFetchClassCtorArgs;
0 ignored issues
show
Documentation Bug introduced by
It seems like $arg3 ? (array)$arg3 : $...faultFetchClassCtorArgs can also be of type array. However, the property $defaultFetchClassCtorArgs is declared as type string. 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...
304
    }
305
306
    /**
307
     * Casts a stdClass object to the given class name mapping its' properties.
308
     *
309
     * @param \stdClass     $sourceObject     Object to cast from.
310
     * @param string|object $destinationClass Name of the class or class instance to cast to.
311
     * @param array         $ctorArgs         Arguments to use for constructing the destination class instance.
312
     *
313
     * @return object
314
     *
315
     * @throws SQLAnywhereException
316
     */
317
    private function castObject(\stdClass $sourceObject, $destinationClass, array $ctorArgs = [])
318
    {
319
        if ( ! is_string($destinationClass)) {
320
            if ( ! is_object($destinationClass)) {
321
                throw new SQLAnywhereException(sprintf(
322
                    'Destination class has to be of type string or object, %s given.', gettype($destinationClass)
323
                ));
324
            }
325
        } else {
326
            $destinationClass = new \ReflectionClass($destinationClass);
327
            $destinationClass = $destinationClass->newInstanceArgs($ctorArgs);
328
        }
329
330
        $sourceReflection           = new \ReflectionObject($sourceObject);
331
        $destinationClassReflection = new \ReflectionObject($destinationClass);
0 ignored issues
show
Bug introduced by
It seems like $destinationClass can also be of type string; however, parameter $argument of ReflectionObject::__construct() does only seem to accept object, 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

331
        $destinationClassReflection = new \ReflectionObject(/** @scrutinizer ignore-type */ $destinationClass);
Loading history...
332
333
        foreach ($sourceReflection->getProperties() as $sourceProperty) {
334
            $sourceProperty->setAccessible(true);
335
336
            $name  = $sourceProperty->getName();
337
            $value = $sourceProperty->getValue($sourceObject);
338
339
            if ($destinationClassReflection->hasProperty($name)) {
340
                $destinationProperty = $destinationClassReflection->getProperty($name);
341
342
                $destinationProperty->setAccessible(true);
343
                $destinationProperty->setValue($destinationClass, $value);
0 ignored issues
show
Unused Code introduced by
The call to ReflectionProperty::setValue() has too many arguments starting with $value. ( Ignorable by Annotation )

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

343
                $destinationProperty->/** @scrutinizer ignore-call */ 
344
                                      setValue($destinationClass, $value);

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress. Please note the @ignore annotation hint above.

Loading history...
344
            } else {
345
                $destinationClass->$name = $value;
346
            }
347
        }
348
349
        return $destinationClass;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $destinationClass also could return the type string which is incompatible with the documented return type object.
Loading history...
350
    }
351
}
352