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

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