ResultIterator::map()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 1
1
<?php
2
3
namespace Mouf\Database\TDBM;
4
5
use Doctrine\DBAL\Statement;
6
use Mouf\Database\MagicQuery;
7
use Mouf\Database\TDBM\QueryFactory\QueryFactory;
8
use Porpaginas\Result;
9
use Psr\Log\LoggerInterface;
10
use Traversable;
11
12
/*
13
 Copyright (C) 2006-2016 David Négrier - THE CODING MACHINE
14
15
 This program is free software; you can redistribute it and/or modify
16
 it under the terms of the GNU General Public License as published by
17
 the Free Software Foundation; either version 2 of the License, or
18
 (at your option) any later version.
19
20
 This program is distributed in the hope that it will be useful,
21
 but WITHOUT ANY WARRANTY; without even the implied warranty of
22
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
23
 GNU General Public License for more details.
24
25
 You should have received a copy of the GNU General Public License
26
 along with this program; if not, write to the Free Software
27
 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
28
 */
29
30
/**
31
 * Iterator used to retrieve results.
32
 */
33
class ResultIterator implements Result, \ArrayAccess, \JsonSerializable
34
{
35
    /**
36
     * @var Statement
37
     */
38
    protected $statement;
39
40
    private $objectStorage;
41
    private $className;
42
43
    private $tdbmService;
44
    private $parameters;
45
    private $magicQuery;
46
47
    /**
48
     * @var QueryFactory
49
     */
50
    private $queryFactory;
51
52
    /**
53
     * @var InnerResultIterator
54
     */
55
    private $innerResultIterator;
56
57
    private $databasePlatform;
58
59
    private $totalCount;
60
61
    private $mode;
62
63
    private $logger;
64
65
    public function __construct(QueryFactory $queryFactory, array $parameters, $objectStorage, $className, TDBMService $tdbmService, MagicQuery $magicQuery, $mode, LoggerInterface $logger)
66
    {
67
        if ($mode !== null && $mode !== TDBMService::MODE_CURSOR && $mode !== TDBMService::MODE_ARRAY) {
68
            throw new TDBMException("Unknown fetch mode: '".$mode."'");
69
        }
70
71
        $this->queryFactory = $queryFactory;
72
        $this->objectStorage = $objectStorage;
73
        $this->className = $className;
74
        $this->tdbmService = $tdbmService;
75
        $this->parameters = $parameters;
76
        $this->magicQuery = $magicQuery;
77
        $this->databasePlatform = $this->tdbmService->getConnection()->getDatabasePlatform();
78
        $this->mode = $mode;
79
        $this->logger = $logger;
80
    }
81
82
    protected function executeCountQuery()
83
    {
84
        $sql = $this->magicQuery->build($this->queryFactory->getMagicSqlCount(), $this->parameters);
85
        $this->logger->debug('Running count query: '.$sql);
86
        $this->totalCount = $this->tdbmService->getConnection()->fetchColumn($sql, $this->parameters);
87
    }
88
89
    /**
90
     * Counts found records (this is the number of records fetched, taking into account the LIMIT and OFFSET settings).
91
     *
92
     * @return int
93
     */
94
    public function count()
95
    {
96
        if ($this->totalCount === null) {
97
            $this->executeCountQuery();
98
        }
99
100
        return $this->totalCount;
101
    }
102
103
    /**
104
     * Casts the result set to a PHP array.
105
     *
106
     * @return array
107
     */
108
    public function toArray()
109
    {
110
        return iterator_to_array($this->getIterator());
111
    }
112
113
    /**
114
     * Returns a new iterator mapping any call using the $callable function.
115
     *
116
     * @param callable $callable
117
     *
118
     * @return MapIterator
119
     */
120
    public function map(callable $callable)
121
    {
122
        return new MapIterator($this->getIterator(), $callable);
123
    }
124
125
    /**
126
     * Retrieve an external iterator.
127
     *
128
     * @link http://php.net/manual/en/iteratoraggregate.getiterator.php
129
     *
130
     * @return InnerResultIterator An instance of an object implementing <b>Iterator</b> or
131
     *                             <b>Traversable</b>
132
     *
133
     * @since 5.0.0
134
     */
135
    public function getIterator()
136
    {
137
        if ($this->innerResultIterator === null) {
138
            if ($this->mode === TDBMService::MODE_CURSOR) {
139
                $this->innerResultIterator = new InnerResultIterator($this->queryFactory->getMagicSql(), $this->parameters, null, null, $this->queryFactory->getColumnDescriptors(), $this->objectStorage, $this->className, $this->tdbmService, $this->magicQuery, $this->logger);
140
            } else {
141
                $this->innerResultIterator = new InnerResultArray($this->queryFactory->getMagicSql(), $this->parameters, null, null, $this->queryFactory->getColumnDescriptors(), $this->objectStorage, $this->className, $this->tdbmService, $this->magicQuery, $this->logger);
142
            }
143
        }
144
145
        return $this->innerResultIterator;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $this->innerResultIterator; (Mouf\Database\TDBM\InnerResultIterator) is incompatible with the return type declared by the interface Porpaginas\Result::getIterator of type Porpaginas\Iterator.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
146
    }
147
148
    /**
149
     * @param int $offset
150
     * @param int $limit
151
     *
152
     * @return PageIterator
153
     */
154
    public function take($offset, $limit)
155
    {
156
        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);
157
    }
158
159
    /**
160
     * Whether a offset exists.
161
     *
162
     * @link http://php.net/manual/en/arrayaccess.offsetexists.php
163
     *
164
     * @param mixed $offset <p>
165
     *                      An offset to check for.
166
     *                      </p>
167
     *
168
     * @return bool true on success or false on failure.
169
     *              </p>
170
     *              <p>
171
     *              The return value will be casted to boolean if non-boolean was returned
172
     *
173
     * @since 5.0.0
174
     */
175
    public function offsetExists($offset)
176
    {
177
        return $this->getIterator()->offsetExists($offset);
178
    }
179
180
    /**
181
     * Offset to retrieve.
182
     *
183
     * @link http://php.net/manual/en/arrayaccess.offsetget.php
184
     *
185
     * @param mixed $offset <p>
186
     *                      The offset to retrieve.
187
     *                      </p>
188
     *
189
     * @return mixed Can return all value types
190
     *
191
     * @since 5.0.0
192
     */
193
    public function offsetGet($offset)
194
    {
195
        return $this->getIterator()->offsetGet($offset);
196
    }
197
198
    /**
199
     * Offset to set.
200
     *
201
     * @link http://php.net/manual/en/arrayaccess.offsetset.php
202
     *
203
     * @param mixed $offset <p>
204
     *                      The offset to assign the value to.
205
     *                      </p>
206
     * @param mixed $value  <p>
207
     *                      The value to set.
208
     *                      </p>
209
     *
210
     * @since 5.0.0
211
     */
212
    public function offsetSet($offset, $value)
213
    {
214
        return $this->getIterator()->offsetSet($offset, $value);
215
    }
216
217
    /**
218
     * Offset to unset.
219
     *
220
     * @link http://php.net/manual/en/arrayaccess.offsetunset.php
221
     *
222
     * @param mixed $offset <p>
223
     *                      The offset to unset.
224
     *                      </p>
225
     *
226
     * @since 5.0.0
227
     */
228
    public function offsetUnset($offset)
229
    {
230
        return $this->getIterator()->offsetUnset($offset);
231
    }
232
233
    /**
234
     * Specify data which should be serialized to JSON.
235
     *
236
     * @link http://php.net/manual/en/jsonserializable.jsonserialize.php
237
     *
238
     * @param bool $stopRecursion Parameter used internally by TDBM to
239
     *                            stop embedded objects from embedding
240
     *                            other objects
241
     *
242
     * @return mixed data which can be serialized by <b>json_encode</b>,
243
     *               which is a value of any type other than a resource
244
     *
245
     * @since 5.4.0
246
     */
247
    public function jsonSerialize($stopRecursion = false)
248
    {
249
        return array_map(function (AbstractTDBMObject $item) use ($stopRecursion) {
250
            return $item->jsonSerialize($stopRecursion);
251
        }, $this->toArray());
252
    }
253
254
    /**
255
     * Returns only one value (the first) of the result set.
256
     * Returns null if no value exists.
257
     *
258
     * @return mixed|null
259
     */
260
    public function first()
261
    {
262
        $page = $this->take(0, 1);
263
        foreach ($page as $bean) {
264
            return $bean;
265
        }
266
267
        return;
268
    }
269
270
    /**
271
     * Sets the ORDER BY directive executed in SQL and returns a NEW ResultIterator.
272
     *
273
     * For instance:
274
     *
275
     *  $resultSet = $resultSet->withOrder('label ASC, status DESC');
276
     *
277
     * **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.
278
     * 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:
279
     *
280
     *  $resultSet->withOrder(new UncheckedOrderBy('RAND()'))
281
     *
282
     * @param string|UncheckedOrderBy|null $orderBy
283
     *
284
     * @return ResultIterator
285
     */
286 View Code Duplication
    public function withOrder($orderBy) : ResultIterator
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
287
    {
288
        $clone = clone $this;
289
        $clone->queryFactory = clone $this->queryFactory;
290
        $clone->queryFactory->sort($orderBy);
291
        $clone->innerResultIterator = null;
292
293
        return $clone;
294
    }
295
296
    /**
297
     * Sets new parameters for the SQL query and returns a NEW ResultIterator.
298
     *
299
     * For instance:
300
     *
301
     *  $resultSet = $resultSet->withParameters('label ASC, status DESC');
302
     *
303
     * @param string|UncheckedOrderBy|null $orderBy
0 ignored issues
show
Bug introduced by
There is no parameter named $orderBy. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
304
     *
305
     * @return ResultIterator
306
     */
307 View Code Duplication
    public function withParameters(array $parameters) : ResultIterator
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
308
    {
309
        $clone = clone $this;
310
        $clone->parameters = $parameters;
311
        $clone->innerResultIterator = null;
312
        $clone->totalCount = null;
313
314
        return $clone;
315
    }
316
}
317