Issues (291)

src/ResultIterator.php (3 issues)

1
<?php
2
3
declare(strict_types=1);
4
5
namespace TheCodingMachine\TDBM;
6
7
use Doctrine\DBAL\Platforms\MySQLPlatform;
8
use Psr\Log\NullLogger;
9
use Doctrine\DBAL\Connection;
10
use Doctrine\DBAL\Statement;
11
use Mouf\Database\MagicQuery;
12
use TheCodingMachine\TDBM\QueryFactory\QueryFactory;
13
use Psr\Log\LoggerInterface;
14
use TheCodingMachine\TDBM\Utils\DbalUtils;
15
use Traversable;
16
17
use function array_map;
18
use function array_pop;
19
use function is_array;
20
use function is_int;
21
22
/*
23
 Copyright (C) 2006-2017 David Négrier - THE CODING MACHINE
24
25
 This program is free software; you can redistribute it and/or modify
26
 it under the terms of the GNU General Public License as published by
27
 the Free Software Foundation; either version 2 of the License, or
28
 (at your option) any later version.
29
30
 This program is distributed in the hope that it will be useful,
31
 but WITHOUT ANY WARRANTY; without even the implied warranty of
32
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
33
 GNU General Public License for more details.
34
35
 You should have received a copy of the GNU General Public License
36
 along with this program; if not, write to the Free Software
37
 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
38
 */
39
40
/**
41
 * Iterator used to retrieve results.
42
 */
43
class ResultIterator implements ResultInterface, \ArrayAccess, \JsonSerializable
44
{
45
    /** @var Statement */
46
    protected $statement;
47
48
    /** @var ObjectStorageInterface */
49
    private $objectStorage;
50
    /** @var class-string|null */
0 ignored issues
show
Documentation Bug introduced by
The doc comment class-string|null at position 0 could not be parsed: Unknown type name 'class-string' at position 0 in class-string|null.
Loading history...
51
    private $className;
52
53
    /** @var TDBMService */
54
    private $tdbmService;
55
    /** @var mixed[] */
56
    private $parameters;
57
    /** @var MagicQuery */
58
    private $magicQuery;
59
60
    /** @var QueryFactory */
61
    private $queryFactory;
62
63
    /** @var InnerResultIteratorInterface|null */
64
    private $innerResultIterator;
65
66
    /** @var int|null */
67
    private $totalCount;
68
69
    /** @var int */
70
    private $mode;
71
72
    /** @var LoggerInterface */
73
    private $logger;
74
75
    final private function __construct()
76
    {
77
    }
78
79
    /**
80
     * @param mixed[] $parameters
81
     * @param class-string|null $className
0 ignored issues
show
Documentation Bug introduced by
The doc comment class-string|null at position 0 could not be parsed: Unknown type name 'class-string' at position 0 in class-string|null.
Loading history...
82
     */
83
    public static function createResultIterator(QueryFactory $queryFactory, array $parameters, ObjectStorageInterface $objectStorage, ?string $className, TDBMService $tdbmService, MagicQuery $magicQuery, int $mode, LoggerInterface $logger): self
84
    {
85
        $iterator =  new static();
86
        if ($mode !== TDBMService::MODE_CURSOR && $mode !== TDBMService::MODE_ARRAY) {
87
            throw new TDBMException("Unknown fetch mode: '".$mode."'");
88
        }
89
90
        $iterator->queryFactory = $queryFactory;
91
        $iterator->objectStorage = $objectStorage;
92
        $iterator->className = $className;
93
        $iterator->tdbmService = $tdbmService;
94
        $iterator->parameters = $parameters;
95
        $iterator->magicQuery = $magicQuery;
96
        $iterator->mode = $mode;
97
        $iterator->logger = $logger;
98
        return $iterator;
99
    }
100
101
    public static function createEmpyIterator(): self
102
    {
103
        $iterator = new static();
104
        $iterator->totalCount = 0;
105
        $iterator->logger = new NullLogger();
106
        return $iterator;
107
    }
108
109
    protected function executeCountQuery(): void
110
    {
111
        $sql = $this->magicQuery->buildPreparedStatement($this->queryFactory->getMagicSqlCount(), $this->parameters);
112
        $this->logger->debug('Running count query: '.$sql);
113
        $this->totalCount = (int) $this->tdbmService->getConnection()->fetchOne($sql, $this->parameters, DbalUtils::generateTypes($this->parameters));
114
    }
115
116
    /**
117
     * Counts found records (this is the number of records fetched, taking into account the LIMIT and OFFSET settings).
118
     *
119
     * @return int
120
     */
121
    public function count(): int
122
    {
123
        if ($this->totalCount === null) {
124
            $this->executeCountQuery();
125
        }
126
127
        return $this->totalCount;
128
    }
129
130
    /**
131
     * Casts the result set to a PHP array.
132
     *
133
     * @return AbstractTDBMObject[]
134
     */
135
    public function toArray(): array
136
    {
137
        if ($this->totalCount === 0) {
138
            return [];
139
        }
140
        return iterator_to_array($this->getIterator());
141
    }
142
143
    /**
144
     * Returns a new iterator mapping any call using the $callable function.
145
     *
146
     * @param callable $callable
147
     *
148
     * @return MapIterator
149
     */
150
    public function map(callable $callable): MapIterator
151
    {
152
        if ($this->totalCount === 0) {
153
            return new MapIterator([], $callable);
154
        }
155
        return new MapIterator($this->getIterator(), $callable);
156
    }
157
158
    /**
159
     * Retrieve an external iterator.
160
     *
161
     * @return InnerResultIteratorInterface
162
     */
163
    public function getIterator(): \Traversable
164
    {
165
        if ($this->innerResultIterator === null) {
166
            if ($this->totalCount === 0) {
167
                $this->innerResultIterator = new EmptyInnerResultIterator();
168
            } elseif ($this->mode === TDBMService::MODE_CURSOR) {
169
                $this->innerResultIterator = InnerResultIterator::createInnerResultIterator($this->queryFactory->getMagicSql(), $this->parameters, null, null, $this->queryFactory->getColumnDescriptors(), $this->objectStorage, $this->className, $this->tdbmService, $this->magicQuery, $this->logger);
170
            } else {
171
                $this->innerResultIterator = InnerResultArray::createInnerResultIterator($this->queryFactory->getMagicSql(), $this->parameters, null, null, $this->queryFactory->getColumnDescriptors(), $this->objectStorage, $this->className, $this->tdbmService, $this->magicQuery, $this->logger);
172
            }
173
        }
174
175
        return $this->innerResultIterator;
176
    }
177
178
    public function take(int $offset, int $limit): PageIterator
179
    {
180
        if ($this->totalCount === 0) {
181
            return PageIterator::createEmpyIterator($this);
182
        }
183
        return PageIterator::createResultIterator($this, $this->queryFactory->getMagicSql(), $this->parameters, $limit, $offset, $this->queryFactory->getColumnDescriptors(), $this->objectStorage, $this->className, $this->tdbmService, $this->magicQuery, $this->mode, $this->logger);
184
    }
185
186
    /**
187
     * Whether a offset exists.
188
     *
189
     * @link http://php.net/manual/en/arrayaccess.offsetexists.php
190
     *
191
     * @param mixed $offset <p>
192
     *                      An offset to check for.
193
     *                      </p>
194
     *
195
     * @return bool true on success or false on failure.
196
     *              </p>
197
     *              <p>
198
     *              The return value will be casted to boolean if non-boolean was returned
199
     *
200
     * @since 5.0.0
201
     */
202
    public function offsetExists($offset): bool
203
    {
204
        return $this->getIterator()->offsetExists($offset);
205
    }
206
207
    /**
208
     * Offset to retrieve.
209
     *
210
     * @link http://php.net/manual/en/arrayaccess.offsetget.php
211
     *
212
     * @param mixed $offset <p>
213
     *                      The offset to retrieve.
214
     *                      </p>
215
     *
216
     * @return mixed Can return all value types
217
     *
218
     * @since 5.0.0
219
     */
220
    public function offsetGet($offset): mixed
221
    {
222
        return $this->getIterator()->offsetGet($offset);
223
    }
224
225
    /**
226
     * Offset to set.
227
     *
228
     * @link http://php.net/manual/en/arrayaccess.offsetset.php
229
     *
230
     * @param mixed $offset <p>
231
     *                      The offset to assign the value to.
232
     *                      </p>
233
     * @param mixed $value  <p>
234
     *                      The value to set.
235
     *                      </p>
236
     *
237
     * @since 5.0.0
238
     */
239
    public function offsetSet($offset, $value): void
240
    {
241
        $this->getIterator()->offsetSet($offset, $value);
242
    }
243
244
    /**
245
     * Offset to unset.
246
     *
247
     * @link http://php.net/manual/en/arrayaccess.offsetunset.php
248
     *
249
     * @param mixed $offset <p>
250
     *                      The offset to unset.
251
     *                      </p>
252
     *
253
     * @since 5.0.0
254
     */
255
    public function offsetUnset($offset): void
256
    {
257
        $this->getIterator()->offsetUnset($offset);
258
    }
259
260
    /**
261
     * Specify data which should be serialized to JSON.
262
     *
263
     * @link http://php.net/manual/en/jsonserializable.jsonserialize.php
264
     *
265
     * @param bool $stopRecursion Parameter used internally by TDBM to
266
     *                            stop embedded objects from embedding
267
     *                            other objects
268
     *
269
     * @return mixed data which can be serialized by <b>json_encode</b>,
270
     *               which is a value of any type other than a resource
271
     *
272
     * @since 5.4.0
273
     */
274
    public function jsonSerialize($stopRecursion = false): mixed
275
    {
276
        return array_map(function (AbstractTDBMObject $item) use ($stopRecursion) {
277
            return $item->jsonSerialize($stopRecursion);
0 ignored issues
show
The call to JsonSerializable::jsonSerialize() has too many arguments starting with $stopRecursion. ( Ignorable by Annotation )

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

277
            return $item->/** @scrutinizer ignore-call */ jsonSerialize($stopRecursion);

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...
278
        }, $this->toArray());
279
    }
280
281
    /**
282
     * Returns only one value (the first) of the result set.
283
     * Returns null if no value exists.
284
     *
285
     * @return mixed|null
286
     */
287
    public function first()
288
    {
289
        if ($this->totalCount === 0) {
290
            return null;
291
        }
292
        $page = $this->take(0, 1);
293
        foreach ($page as $bean) {
294
            return $bean;
295
        }
296
297
        return null;
298
    }
299
300
    /**
301
     * Sets the ORDER BY directive executed in SQL and returns a NEW ResultIterator.
302
     *
303
     * For instance:
304
     *
305
     *  $resultSet = $resultSet->withOrder('label ASC, status DESC');
306
     *
307
     * **Important:** TDBM does its best to protect you from SQL injection. In particular, it will only allow column names in the "ORDER BY" clause. This means you are safe to pass input from the user directly in the ORDER BY parameter.
308
     * If you want to pass an expression to the ORDER BY clause, you will need to tell TDBM to stop checking for SQL injections. You do this by passing a `UncheckedOrderBy` object as a parameter:
309
     *
310
     *  $resultSet->withOrder(new UncheckedOrderBy('RAND()'))
311
     *
312
     * @param string|UncheckedOrderBy|null $orderBy
313
     *
314
     * @return ResultIterator
315
     */
316
    public function withOrder($orderBy): ResultIterator
317
    {
318
        $clone = clone $this;
319
        if ($this->totalCount === 0) {
320
            return $clone;
321
        }
322
        $clone->queryFactory = clone $this->queryFactory;
323
        $clone->queryFactory->sort($orderBy);
324
        $clone->innerResultIterator = null;
325
326
        return $clone;
327
    }
328
329
    /**
330
     * Sets new parameters for the SQL query and returns a NEW ResultIterator.
331
     *
332
     * For instance:
333
     *
334
     *  $resultSet = $resultSet->withParameters([ 'status' => 'on' ]);
335
     *
336
     * @param mixed[] $parameters
337
     *
338
     * @return ResultIterator
339
     */
340
    public function withParameters(array $parameters): ResultIterator
341
    {
342
        $clone = clone $this;
343
        if ($this->totalCount === 0) {
344
            return $clone;
345
        }
346
        $clone->parameters = $parameters;
347
        $clone->innerResultIterator = null;
348
        $clone->totalCount = null;
349
350
        return $clone;
351
    }
352
353
    /**
354
     * @internal
355
     * @return string
356
     */
357
    public function _getSubQuery(): string
358
    {
359
        $this->magicQuery->setOutputDialect(new MySqlPlatform());
360
        try {
361
            $sql = $this->magicQuery->build($this->queryFactory->getMagicSqlSubQuery(), $this->parameters);
362
        } finally {
363
            $this->magicQuery->setOutputDialect($this->tdbmService->getConnection()->getDatabasePlatform());
364
        }
365
        $primaryKeyColumnDescs = $this->queryFactory->getSubQueryColumnDescriptors();
366
367
        if (count($primaryKeyColumnDescs) > 1) {
368
            throw new TDBMException('You cannot use in a sub-query a table that has a primary key on more that 1 column.');
369
        }
370
371
        $pkDesc = array_pop($primaryKeyColumnDescs);
372
373
        $mysqlPlatform = new MySqlPlatform();
374
        $sql = $mysqlPlatform->quoteIdentifier($pkDesc['table']).'.'.$mysqlPlatform->quoteIdentifier($pkDesc['column']).' IN ('.$sql.')';
375
376
        return $sql;
377
    }
378
}
379