Completed
Pull Request — master (#3610)
by Sergei
03:27 queued 10s
created

SQLAnywhereStatement::getIterator()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 0
cts 1
cp 0
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 0
crap 2
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Doctrine\DBAL\Driver\SQLAnywhere;
6
7
use Doctrine\DBAL\Driver\Statement;
8
use Doctrine\DBAL\Driver\StatementIterator;
9
use Doctrine\DBAL\Exception\GetVariableType;
10
use Doctrine\DBAL\Exception\InvalidColumnIndex;
11
use Doctrine\DBAL\FetchMode;
12
use Doctrine\DBAL\ParameterType;
13
use IteratorAggregate;
14
use ReflectionClass;
15
use ReflectionObject;
16
use stdClass;
17
use const SASQL_BOTH;
18
use function array_key_exists;
19
use function assert;
20
use function count;
21
use function func_get_args;
22
use function is_array;
23
use function is_int;
24
use function is_object;
25
use function is_resource;
26
use function is_string;
27
use function sasql_fetch_array;
28
use function sasql_fetch_assoc;
29
use function sasql_fetch_object;
30
use function sasql_fetch_row;
31
use function sasql_prepare;
32
use function sasql_stmt_affected_rows;
33
use function sasql_stmt_bind_param_ex;
34
use function sasql_stmt_execute;
35
use function sasql_stmt_field_count;
36
use function sasql_stmt_reset;
37
use function sasql_stmt_result_metadata;
38
use function sprintf;
39
40
/**
41
 * SAP SQL Anywhere implementation of the Statement interface.
42
 */
43
class SQLAnywhereStatement implements IteratorAggregate, Statement
44
{
45
    /** @var resource The connection resource. */
46
    private $conn;
47
48
    /** @var string Name of the default class to instantiate when fetching class instances. */
49
    private $defaultFetchClass = '\stdClass';
50
51
    /** @var mixed[] Constructor arguments for the default class to instantiate when fetching class instances. */
52
    private $defaultFetchClassCtorArgs = [];
53
54
    /** @var int Default fetch mode to use. */
55
    private $defaultFetchMode = FetchMode::MIXED;
56
57
    /** @var resource The result set resource to fetch. */
58
    private $result;
59
60
    /** @var resource The prepared SQL statement to execute. */
61
    private $stmt;
62
63
    /** @var mixed[] The references to bound parameter values. */
64
    private $boundValues = [];
65
66
    /**
67
     * Prepares given statement for given connection.
68
     *
69
     * @param resource $conn The connection resource to use.
70
     * @param string   $sql  The SQL statement to prepare.
71
     *
72
     * @throws SQLAnywhereException
73
     */
74
    public function __construct($conn, string $sql)
75
    {
76
        if (! is_resource($conn)) {
77
            throw new SQLAnywhereException(sprintf(
78
                'Invalid SQL Anywhere connection resource, %s given.',
79
                (new GetVariableType())->__invoke($conn)
80
            ));
81
        }
82
83
        $this->conn = $conn;
84
        $this->stmt = sasql_prepare($conn, $sql);
85
86
        if (! is_resource($this->stmt)) {
87
            throw SQLAnywhereException::fromSQLAnywhereError($conn);
88
        }
89
    }
90
91
    /**
92
     * {@inheritdoc}
93
     *
94
     * @throws SQLAnywhereException
95
     */
96
    public function bindParam($param, &$variable, int $type = ParameterType::STRING, ?int $length = null) : void
97
    {
98
        assert(is_int($param));
99
100
        switch ($type) {
101
            case ParameterType::INTEGER:
102
            case ParameterType::BOOLEAN:
103
                $type = 'i';
104
                break;
105
106
            case ParameterType::LARGE_OBJECT:
107
                $type = 'b';
108
                break;
109
110
            case ParameterType::NULL:
111
            case ParameterType::STRING:
112
            case ParameterType::BINARY:
113
                $type = 's';
114
                break;
115
116
            default:
117
                throw new SQLAnywhereException(sprintf('Unknown type %d.', $type));
118
        }
119
120
        $this->boundValues[$param] =& $variable;
121
122
        if (! sasql_stmt_bind_param_ex($this->stmt, $param - 1, $variable, $type, $variable === null)) {
123
            throw SQLAnywhereException::fromSQLAnywhereError($this->conn, $this->stmt);
124
        }
125
    }
126
127
    /**
128
     * {@inheritdoc}
129
     */
130
    public function bindValue($param, $value, int $type = ParameterType::STRING) : void
131
    {
132
        $this->bindParam($param, $value, $type);
133
    }
134
135
    /**
136
     * {@inheritdoc}
137
     */
138
    public function closeCursor() : void
139
    {
140
        sasql_stmt_reset($this->stmt);
141
    }
142
143
    /**
144
     * {@inheritdoc}
145
     */
146
    public function columnCount() : int
147
    {
148
        return sasql_stmt_field_count($this->stmt);
149
    }
150
151
    /**
152
     * {@inheritdoc}
153
     *
154
     * @throws SQLAnywhereException
155
     */
156
    public function execute(?array $params = null) : void
157
    {
158
        if (is_array($params)) {
159
            $hasZeroIndex = array_key_exists(0, $params);
160
161
            foreach ($params as $key => $val) {
162
                if ($hasZeroIndex && is_int($key)) {
163
                    $this->bindValue($key + 1, $val);
164
                } else {
165
                    $this->bindValue($key, $val);
166
                }
167
            }
168
        }
169
170
        if (! sasql_stmt_execute($this->stmt)) {
171
            throw SQLAnywhereException::fromSQLAnywhereError($this->conn, $this->stmt);
172
        }
173
174
        $this->result = sasql_stmt_result_metadata($this->stmt);
175
    }
176
177
    /**
178
     * {@inheritdoc}
179
     *
180
     * @throws SQLAnywhereException
181
     */
182
    public function fetch(?int $fetchMode = null, ...$args)
183
    {
184
        if (! is_resource($this->result)) {
185
            return false;
186
        }
187
188
        $fetchMode = $fetchMode ?: $this->defaultFetchMode;
189
190
        switch ($fetchMode) {
191
            case FetchMode::COLUMN:
192
                return $this->fetchColumn();
193
194
            case FetchMode::ASSOCIATIVE:
195
                return sasql_fetch_assoc($this->result);
196
197
            case FetchMode::MIXED:
198
                return sasql_fetch_array($this->result, SASQL_BOTH);
199
200
            case FetchMode::CUSTOM_OBJECT:
201
                $className = $this->defaultFetchClass;
202
                $ctorArgs  = $this->defaultFetchClassCtorArgs;
203
204
                if (count($args) > 0) {
205
                    $className = $args[0];
206
                    $ctorArgs  = $args[1] ?? [];
207
                }
208
209
                $result = sasql_fetch_object($this->result);
210
211
                if ($result instanceof stdClass) {
212
                    $result = $this->castObject($result, $className, $ctorArgs);
213
                }
214
215
                return $result;
216
217
            case FetchMode::NUMERIC:
218
                return sasql_fetch_row($this->result);
219
220
            case FetchMode::STANDARD_OBJECT:
221
                return sasql_fetch_object($this->result);
222
223
            default:
224
                throw new SQLAnywhereException(sprintf('Fetch mode is not supported %d.', $fetchMode));
225
        }
226
    }
227
228
    /**
229
     * {@inheritdoc}
230
     */
231
    public function fetchAll(?int $fetchMode = null, ...$args) : array
232
    {
233
        $rows = [];
234
235
        switch ($fetchMode) {
236
            case FetchMode::CUSTOM_OBJECT:
237
                while (($row = $this->fetch(...func_get_args())) !== false) {
238
                    $rows[] = $row;
239
                }
240
                break;
241
242
            case FetchMode::COLUMN:
243
                while (($row = $this->fetchColumn()) !== false) {
244
                    $rows[] = $row;
245
                }
246
                break;
247
248
            default:
249
                while (($row = $this->fetch($fetchMode)) !== false) {
250
                    $rows[] = $row;
251
                }
252
        }
253
254
        return $rows;
255
    }
256
257
    /**
258
     * {@inheritdoc}
259
     */
260
    public function fetchColumn(int $columnIndex = 0)
261
    {
262
        $row = $this->fetch(FetchMode::NUMERIC);
263
264
        if ($row === false) {
265
            return false;
266
        }
267
268
        if (! array_key_exists($columnIndex, $row)) {
269
            throw InvalidColumnIndex::new($columnIndex, count($row));
270
        }
271
272
        return $row[$columnIndex];
273
    }
274
275
    /**
276
     * {@inheritdoc}
277
     */
278
    public function getIterator()
279
    {
280
        return new StatementIterator($this);
281
    }
282
283
    /**
284
     * {@inheritdoc}
285
     */
286
    public function rowCount() : int
287
    {
288
        return sasql_stmt_affected_rows($this->stmt);
289
    }
290
291
    /**
292
     * {@inheritdoc}
293
     */
294
    public function setFetchMode(int $fetchMode, ...$args) : void
295 4
    {
296
        $this->defaultFetchMode = $fetchMode;
297 4
298
        if (isset($args[0])) {
299
            $this->defaultFetchClass = $args[0];
300
        }
301
302
        if (! isset($args[1])) {
303
            return;
304
        }
305
306
        $this->defaultFetchClassCtorArgs = (array) $args[1];
307
    }
308
309
    /**
310
     * Casts a stdClass object to the given class name mapping its' properties.
311
     *
312
     * @param stdClass      $sourceObject     Object to cast from.
313
     * @param string|object $destinationClass Name of the class or class instance to cast to.
314
     * @param mixed[]       $ctorArgs         Arguments to use for constructing the destination class instance.
315
     *
316
     * @throws SQLAnywhereException
317
     */
318
    private function castObject(stdClass $sourceObject, $destinationClass, array $ctorArgs = []) : object
319
    {
320
        if (! is_string($destinationClass)) {
321
            if (! is_object($destinationClass)) {
322
                throw new SQLAnywhereException(sprintf(
323
                    'Destination class has to be of type string or object, "%s" given.',
324
                    (new GetVariableType())->__invoke($destinationClass)
325
                ));
326
            }
327
        } else {
328
            $destinationClass = new ReflectionClass($destinationClass);
329
            $destinationClass = $destinationClass->newInstanceArgs($ctorArgs);
330
        }
331
332
        $sourceReflection           = new ReflectionObject($sourceObject);
333
        $destinationClassReflection = new ReflectionObject($destinationClass);
334
335
        foreach ($sourceReflection->getProperties() as $sourceProperty) {
336
            $sourceProperty->setAccessible(true);
337
338
            $name  = $sourceProperty->getName();
339
            $value = $sourceProperty->getValue($sourceObject);
340
341
            if ($destinationClassReflection->hasProperty($name)) {
342
                $destinationProperty = $destinationClassReflection->getProperty($name);
343
344
                $destinationProperty->setAccessible(true);
345
                $destinationProperty->setValue($destinationClass, $value);
346
            } else {
347
                $destinationClass->$name = $value;
348
            }
349
        }
350
351
        return $destinationClass;
352
    }
353
}
354