Passed
Pull Request — master (#181)
by
unknown
05:45
created

ResultIterator::createEmptyIterator()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 4
c 0
b 0
f 0
dl 0
loc 6
rs 10
cc 1
nc 1
nop 0
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(
86
        QueryFactory $queryFactory,
87
        array $parameters,
88
        ObjectStorageInterface $objectStorage,
89
        ?string $className,
90
        TDBMService $tdbmService,
91
        MagicQuery $magicQuery,
92
        int $mode,
93
        LoggerInterface $logger
94
    ): self {
95
        $iterator =  new static();
96
        if ($mode !== TDBMService::MODE_CURSOR && $mode !== TDBMService::MODE_ARRAY) {
97
            throw new TDBMException("Unknown fetch mode: '".$mode."'");
98
        }
99
100
        if (is_subclass_of($iterator, self::class, false)) { // We only add iterator if it's specified
101
            $queryFactory->setResultIterator($iterator);
102
        }
103
        $iterator->queryFactory = $queryFactory;
104
        $iterator->objectStorage = $objectStorage;
105
        $iterator->className = $className;
106
        $iterator->tdbmService = $tdbmService;
107
        $iterator->parameters = $parameters;
108
        $iterator->magicQuery = $magicQuery;
109
        $iterator->mode = $mode;
110
        $iterator->logger = $logger;
111
        return $iterator;
112
    }
113
114
    public static function createEmptyIterator(): self
115
    {
116
        $iterator = new self();
117
        $iterator->totalCount = 0;
118
        $iterator->logger = new NullLogger();
119
        return $iterator;
120
    }
121
122
    protected function executeCountQuery(): void
123
    {
124
        $sql = $this->magicQuery->buildPreparedStatement($this->queryFactory->getMagicSqlCount(), $this->parameters);
125
        $this->logger->debug('Running count query: '.$sql);
126
        $this->totalCount = (int) $this->tdbmService->getConnection()->fetchColumn($sql, $this->parameters, 0, DbalUtils::generateArrayTypes($this->parameters));
127
    }
128
129
    /**
130
     * Counts found records (this is the number of records fetched, taking into account the LIMIT and OFFSET settings).
131
     *
132
     * @return int
133
     */
134
    public function count(): int
135
    {
136
        if ($this->totalCount === null) {
137
            $this->executeCountQuery();
138
        }
139
140
        return $this->totalCount;
141
    }
142
143
    /**
144
     * Casts the result set to a PHP array.
145
     *
146
     * @return AbstractTDBMObject[]
147
     */
148
    public function toArray(): array
149
    {
150
        if ($this->totalCount === 0) {
151
            return [];
152
        }
153
        return iterator_to_array($this->getIterator());
154
    }
155
156
    /**
157
     * Returns a new iterator mapping any call using the $callable function.
158
     *
159
     * @param callable $callable
160
     *
161
     * @return MapIterator
162
     */
163
    public function map(callable $callable): MapIterator
164
    {
165
        if ($this->totalCount === 0) {
166
            return new MapIterator([], $callable);
167
        }
168
        return new MapIterator($this->getIterator(), $callable);
169
    }
170
171
    /**
172
     * Retrieve an external iterator.
173
     *
174
     * @return InnerResultIteratorInterface
175
     */
176
    public function getIterator()
177
    {
178
        if ($this->innerResultIterator === null) {
179
            if ($this->totalCount === 0) {
180
                $this->innerResultIterator = new EmptyInnerResultIterator();
181
            } elseif ($this->mode === TDBMService::MODE_CURSOR) {
182
                $this->innerResultIterator = InnerResultIterator::createInnerResultIterator($this->queryFactory->getMagicSql(), $this->parameters, null, null, $this->queryFactory->getColumnDescriptors(), $this->objectStorage, $this->className, $this->tdbmService, $this->magicQuery, $this->logger);
183
            } else {
184
                $this->innerResultIterator = InnerResultArray::createInnerResultIterator($this->queryFactory->getMagicSql(), $this->parameters, null, null, $this->queryFactory->getColumnDescriptors(), $this->objectStorage, $this->className, $this->tdbmService, $this->magicQuery, $this->logger);
185
            }
186
        }
187
188
        return $this->innerResultIterator;
189
    }
190
191
    /**
192
     * @param int $offset
193
     * @param int $limit
194
     *
195
     * @return PageIterator
196
     */
197
    public function take($offset, $limit)
198
    {
199
        if ($this->totalCount === 0) {
200
            return PageIterator::createEmpyIterator($this);
201
        }
202
        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);
203
    }
204
205
    /**
206
     * Whether a offset exists.
207
     *
208
     * @link http://php.net/manual/en/arrayaccess.offsetexists.php
209
     *
210
     * @param mixed $offset <p>
211
     *                      An offset to check for.
212
     *                      </p>
213
     *
214
     * @return bool true on success or false on failure.
215
     *              </p>
216
     *              <p>
217
     *              The return value will be casted to boolean if non-boolean was returned
218
     *
219
     * @since 5.0.0
220
     */
221
    public function offsetExists($offset)
222
    {
223
        return $this->getIterator()->offsetExists($offset);
224
    }
225
226
    /**
227
     * Offset to retrieve.
228
     *
229
     * @link http://php.net/manual/en/arrayaccess.offsetget.php
230
     *
231
     * @param mixed $offset <p>
232
     *                      The offset to retrieve.
233
     *                      </p>
234
     *
235
     * @return mixed Can return all value types
236
     *
237
     * @since 5.0.0
238
     */
239
    public function offsetGet($offset)
240
    {
241
        return $this->getIterator()->offsetGet($offset);
242
    }
243
244
    /**
245
     * Offset to set.
246
     *
247
     * @link http://php.net/manual/en/arrayaccess.offsetset.php
248
     *
249
     * @param mixed $offset <p>
250
     *                      The offset to assign the value to.
251
     *                      </p>
252
     * @param mixed $value  <p>
253
     *                      The value to set.
254
     *                      </p>
255
     *
256
     * @since 5.0.0
257
     */
258
    public function offsetSet($offset, $value)
259
    {
260
        $this->getIterator()->offsetSet($offset, $value);
261
    }
262
263
    /**
264
     * Offset to unset.
265
     *
266
     * @link http://php.net/manual/en/arrayaccess.offsetunset.php
267
     *
268
     * @param mixed $offset <p>
269
     *                      The offset to unset.
270
     *                      </p>
271
     *
272
     * @since 5.0.0
273
     */
274
    public function offsetUnset($offset)
275
    {
276
        $this->getIterator()->offsetUnset($offset);
277
    }
278
279
    /**
280
     * Specify data which should be serialized to JSON.
281
     *
282
     * @link http://php.net/manual/en/jsonserializable.jsonserialize.php
283
     *
284
     * @param bool $stopRecursion Parameter used internally by TDBM to
285
     *                            stop embedded objects from embedding
286
     *                            other objects
287
     *
288
     * @return mixed data which can be serialized by <b>json_encode</b>,
289
     *               which is a value of any type other than a resource
290
     *
291
     * @since 5.4.0
292
     */
293
    public function jsonSerialize($stopRecursion = false)
294
    {
295
        return array_map(function (AbstractTDBMObject $item) use ($stopRecursion) {
296
            return $item->jsonSerialize($stopRecursion);
0 ignored issues
show
Unused Code introduced by
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

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

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

398
    protected function addToWhitelist(/** @scrutinizer ignore-unused */ string $column, string $table) : void

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
399
    {
400
        throw new TDBMException('Table `' . $table . '` not found in inheritance Schema.');
401
    }
402
403
    public function isInWhitelist(string $column, string $table) : bool
0 ignored issues
show
Unused Code introduced by
The parameter $column is not used and could be removed. ( Ignorable by Annotation )

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

403
    public function isInWhitelist(/** @scrutinizer ignore-unused */ string $column, string $table) : bool

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
404
    {
405
        throw new TDBMException('Table `' . $table . '` not found in inheritance Schema');
406
    }
407
408
    protected function removeFromWhitelist(string $column, string $table) : void
0 ignored issues
show
Unused Code introduced by
The parameter $column is not used and could be removed. ( Ignorable by Annotation )

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

408
    protected function removeFromWhitelist(/** @scrutinizer ignore-unused */ string $column, string $table) : void

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
409
    {
410
        throw new TDBMException('Table `' . $table . '` not found in inheritance Schema');
411
    }
412
}
413