Completed
Push — master ( f50fbb...681f17 )
by David
20s queued 12s
created

src/ResultIterator.php (1 issue)

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

285
            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...
286
        }, $this->toArray());
287
    }
288
289
    /**
290
     * Returns only one value (the first) of the result set.
291
     * Returns null if no value exists.
292
     *
293
     * @return mixed|null
294
     */
295
    public function first()
296
    {
297
        if ($this->totalCount === 0) {
298
            return null;
299
        }
300
        $page = $this->take(0, 1);
301
        foreach ($page as $bean) {
302
            return $bean;
303
        }
304
305
        return null;
306
    }
307
308
    /**
309
     * Sets the ORDER BY directive executed in SQL and returns a NEW ResultIterator.
310
     *
311
     * For instance:
312
     *
313
     *  $resultSet = $resultSet->withOrder('label ASC, status DESC');
314
     *
315
     * **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.
316
     * 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:
317
     *
318
     *  $resultSet->withOrder(new UncheckedOrderBy('RAND()'))
319
     *
320
     * @param string|UncheckedOrderBy|null $orderBy
321
     *
322
     * @return ResultIterator
323
     */
324
    public function withOrder($orderBy) : ResultIterator
325
    {
326
        $clone = clone $this;
327
        if ($this->totalCount === 0) {
328
            return $clone;
329
        }
330
        $clone->queryFactory = clone $this->queryFactory;
331
        $clone->queryFactory->sort($orderBy);
332
        $clone->innerResultIterator = null;
333
334
        return $clone;
335
    }
336
337
    /**
338
     * Sets new parameters for the SQL query and returns a NEW ResultIterator.
339
     *
340
     * For instance:
341
     *
342
     *  $resultSet = $resultSet->withParameters([ 'status' => 'on' ]);
343
     *
344
     * @param mixed[] $parameters
345
     *
346
     * @return ResultIterator
347
     */
348
    public function withParameters(array $parameters) : ResultIterator
349
    {
350
        $clone = clone $this;
351
        if ($this->totalCount === 0) {
352
            return $clone;
353
        }
354
        $clone->parameters = $parameters;
355
        $clone->innerResultIterator = null;
356
        $clone->totalCount = null;
357
358
        return $clone;
359
    }
360
361
    /**
362
     * @internal
363
     * @return string
364
     */
365
    public function _getSubQuery(): string
366
    {
367
        $this->magicQuery->setOutputDialect(new MySqlPlatform());
368
        try {
369
            $sql = $this->magicQuery->build($this->queryFactory->getMagicSqlSubQuery(), $this->parameters);
370
        } finally {
371
            $this->magicQuery->setOutputDialect($this->tdbmService->getConnection()->getDatabasePlatform());
372
        }
373
        $primaryKeyColumnDescs = $this->queryFactory->getSubQueryColumnDescriptors();
374
375
        if (count($primaryKeyColumnDescs) > 1) {
376
            throw new TDBMException('You cannot use in a sub-query a table that has a primary key on more that 1 column.');
377
        }
378
379
        $pkDesc = array_pop($primaryKeyColumnDescs);
380
381
        $mysqlPlatform = new MySqlPlatform();
382
        $sql = $mysqlPlatform->quoteIdentifier($pkDesc['table']).'.'.$mysqlPlatform->quoteIdentifier($pkDesc['column']).' IN ('.$sql.')';
383
384
        return $sql;
385
    }
386
}
387