Passed
Pull Request — master (#161)
by David
02:33
created

ResultIterator::_getSubQuery()   A

Complexity

Conditions 2
Paths 4

Size

Total Lines 20
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 12
c 0
b 0
f 0
dl 0
loc 20
rs 9.8666
cc 2
nc 4
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 InnerResultIterator|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 self();
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::generateArrayTypes($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
     * @link http://php.net/manual/en/iteratoraggregate.getiterator.php
164
     *
165
     * @return InnerResultIterator An instance of an object implementing <b>Iterator</b> or
166
     *                             <b>Traversable</b>
167
     *
168
     * @since 5.0.0
169
     */
170
    public function getIterator()
171
    {
172
        if ($this->innerResultIterator === null) {
173
            if ($this->totalCount === 0) {
174
                $this->innerResultIterator = InnerResultArray::createEmpyIterator();
175
            } elseif ($this->mode === TDBMService::MODE_CURSOR) {
176
                $this->innerResultIterator = InnerResultIterator::createInnerResultIterator($this->queryFactory->getMagicSql(), $this->parameters, null, null, $this->queryFactory->getColumnDescriptors(), $this->objectStorage, $this->className, $this->tdbmService, $this->magicQuery, $this->logger);
177
            } else {
178
                $this->innerResultIterator = InnerResultArray::createInnerResultIterator($this->queryFactory->getMagicSql(), $this->parameters, null, null, $this->queryFactory->getColumnDescriptors(), $this->objectStorage, $this->className, $this->tdbmService, $this->magicQuery, $this->logger);
179
            }
180
        }
181
182
        return $this->innerResultIterator;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $this->innerResultIterator returns the type TheCodingMachine\TDBM\In...DBM\InnerResultIterator which is incompatible with the return type mandated by Porpaginas\Result::getIterator() of Porpaginas\Iterator.

In the issue above, the returned value is violating the contract defined by the mentioned interface.

Let's take a look at an example:

interface HasName {
    /** @return string */
    public function getName();
}

class Name {
    public $name;
}

class User implements HasName {
    /** @return string|Name */
    public function getName() {
        return new Name('foo'); // This is a violation of the ``HasName`` interface
                                // which only allows a string value to be returned.
    }
}
Loading history...
183
    }
184
185
    /**
186
     * @param int $offset
187
     * @param int $limit
188
     *
189
     * @return PageIterator
190
     */
191
    public function take($offset, $limit)
192
    {
193
        if ($this->totalCount === 0) {
194
            return PageIterator::createEmpyIterator($this);
195
        }
196
        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);
197
    }
198
199
    /**
200
     * Whether a offset exists.
201
     *
202
     * @link http://php.net/manual/en/arrayaccess.offsetexists.php
203
     *
204
     * @param mixed $offset <p>
205
     *                      An offset to check for.
206
     *                      </p>
207
     *
208
     * @return bool true on success or false on failure.
209
     *              </p>
210
     *              <p>
211
     *              The return value will be casted to boolean if non-boolean was returned
212
     *
213
     * @since 5.0.0
214
     */
215
    public function offsetExists($offset)
216
    {
217
        return $this->getIterator()->offsetExists($offset);
218
    }
219
220
    /**
221
     * Offset to retrieve.
222
     *
223
     * @link http://php.net/manual/en/arrayaccess.offsetget.php
224
     *
225
     * @param mixed $offset <p>
226
     *                      The offset to retrieve.
227
     *                      </p>
228
     *
229
     * @return mixed Can return all value types
230
     *
231
     * @since 5.0.0
232
     */
233
    public function offsetGet($offset)
234
    {
235
        return $this->getIterator()->offsetGet($offset);
236
    }
237
238
    /**
239
     * Offset to set.
240
     *
241
     * @link http://php.net/manual/en/arrayaccess.offsetset.php
242
     *
243
     * @param mixed $offset <p>
244
     *                      The offset to assign the value to.
245
     *                      </p>
246
     * @param mixed $value  <p>
247
     *                      The value to set.
248
     *                      </p>
249
     *
250
     * @since 5.0.0
251
     */
252
    public function offsetSet($offset, $value)
253
    {
254
        return $this->getIterator()->offsetSet($offset, $value);
255
    }
256
257
    /**
258
     * Offset to unset.
259
     *
260
     * @link http://php.net/manual/en/arrayaccess.offsetunset.php
261
     *
262
     * @param mixed $offset <p>
263
     *                      The offset to unset.
264
     *                      </p>
265
     *
266
     * @since 5.0.0
267
     */
268
    public function offsetUnset($offset)
269
    {
270
        return $this->getIterator()->offsetUnset($offset);
271
    }
272
273
    /**
274
     * Specify data which should be serialized to JSON.
275
     *
276
     * @link http://php.net/manual/en/jsonserializable.jsonserialize.php
277
     *
278
     * @param bool $stopRecursion Parameter used internally by TDBM to
279
     *                            stop embedded objects from embedding
280
     *                            other objects
281
     *
282
     * @return mixed data which can be serialized by <b>json_encode</b>,
283
     *               which is a value of any type other than a resource
284
     *
285
     * @since 5.4.0
286
     */
287
    public function jsonSerialize($stopRecursion = false)
288
    {
289
        return array_map(function (AbstractTDBMObject $item) use ($stopRecursion) {
290
            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

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