Passed
Pull Request — master (#161)
by David
04:44
created

ResultIterator::_getSubQuery()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 14
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

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

257
            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...
258
        }, $this->toArray());
259
    }
260
261
    /**
262
     * Returns only one value (the first) of the result set.
263
     * Returns null if no value exists.
264
     *
265
     * @return mixed|null
266
     */
267
    public function first()
268
    {
269
        $page = $this->take(0, 1);
270
        foreach ($page as $bean) {
271
            return $bean;
272
        }
273
274
        return;
275
    }
276
277
    /**
278
     * Sets the ORDER BY directive executed in SQL and returns a NEW ResultIterator.
279
     *
280
     * For instance:
281
     *
282
     *  $resultSet = $resultSet->withOrder('label ASC, status DESC');
283
     *
284
     * **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.
285
     * 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:
286
     *
287
     *  $resultSet->withOrder(new UncheckedOrderBy('RAND()'))
288
     *
289
     * @param string|UncheckedOrderBy|null $orderBy
290
     *
291
     * @return ResultIterator
292
     */
293
    public function withOrder($orderBy) : ResultIterator
294
    {
295
        $clone = clone $this;
296
        $clone->queryFactory = clone $this->queryFactory;
297
        $clone->queryFactory->sort($orderBy);
298
        $clone->innerResultIterator = null;
299
300
        return $clone;
301
    }
302
303
    /**
304
     * Sets new parameters for the SQL query and returns a NEW ResultIterator.
305
     *
306
     * For instance:
307
     *
308
     *  $resultSet = $resultSet->withParameters([ 'status' => 'on' ]);
309
     *
310
     * @param mixed[] $parameters
311
     *
312
     * @return ResultIterator
313
     */
314
    public function withParameters(array $parameters) : ResultIterator
315
    {
316
        $clone = clone $this;
317
        $clone->parameters = $parameters;
318
        $clone->innerResultIterator = null;
319
        $clone->totalCount = null;
320
321
        return $clone;
322
    }
323
324
    /**
325
     * @internal
326
     * @return string
327
     */
328
    public function _getSubQuery(): string
329
    {
330
        $sql = $this->magicQuery->build($this->queryFactory->getMagicSqlSubQuery(), $this->parameters);
331
        $primaryKeyColumnDescs = $this->queryFactory->getSubQueryColumnDescriptors();
332
333
        if (count($primaryKeyColumnDescs) > 1) {
334
            throw new TDBMException('You cannot use in a sub-query a table that has a primary key on more that 1 column.');
335
        }
336
337
        $pkDesc = array_pop($primaryKeyColumnDescs);
338
339
        $sql = $this->tdbmService->getConnection()->quoteIdentifier($pkDesc['table']).'.'.$this->tdbmService->getConnection()->quoteIdentifier($pkDesc['column']).' IN ('.$sql.')';
340
341
        return $sql;
342
    }
343
}
344