Passed
Pull Request — master (#170)
by ARP
02:28
created

ResultIterator::createEmpyIterator()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

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

279
            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...
280
        }, $this->toArray());
281
    }
282
283
    /**
284
     * Returns only one value (the first) of the result set.
285
     * Returns null if no value exists.
286
     *
287
     * @return mixed|null
288
     */
289
    public function first()
290
    {
291
        if ($this->totalCount === 0) {
292
            return null;
293
        }
294
        $page = $this->take(0, 1);
295
        foreach ($page as $bean) {
296
            return $bean;
297
        }
298
299
        return null;
300
    }
301
302
    /**
303
     * Sets the ORDER BY directive executed in SQL and returns a NEW ResultIterator.
304
     *
305
     * For instance:
306
     *
307
     *  $resultSet = $resultSet->withOrder('label ASC, status DESC');
308
     *
309
     * **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.
310
     * 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:
311
     *
312
     *  $resultSet->withOrder(new UncheckedOrderBy('RAND()'))
313
     *
314
     * @param string|UncheckedOrderBy|null $orderBy
315
     *
316
     * @return ResultIterator
317
     */
318
    public function withOrder($orderBy) : ResultIterator
319
    {
320
        $clone = clone $this;
321
        if ($this->totalCount === 0) {
322
            return $clone;
323
        }
324
        $clone->queryFactory = clone $this->queryFactory;
325
        $clone->queryFactory->sort($orderBy);
326
        $clone->innerResultIterator = null;
327
328
        return $clone;
329
    }
330
331
    /**
332
     * Sets new parameters for the SQL query and returns a NEW ResultIterator.
333
     *
334
     * For instance:
335
     *
336
     *  $resultSet = $resultSet->withParameters([ 'status' => 'on' ]);
337
     *
338
     * @param mixed[] $parameters
339
     *
340
     * @return ResultIterator
341
     */
342
    public function withParameters(array $parameters) : ResultIterator
343
    {
344
        $clone = clone $this;
345
        if ($this->totalCount === 0) {
346
            return $clone;
347
        }
348
        $clone->parameters = $parameters;
349
        $clone->innerResultIterator = null;
350
        $clone->totalCount = null;
351
352
        return $clone;
353
    }
354
}
355