Passed
Pull Request — master (#161)
by David
05:10 queued 02:05
created

ResultIterator::_getSubQuery()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 15
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

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

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