Result::shouldResetResultset()   A
last analyzed

Complexity

Conditions 4
Paths 4

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 4
nc 4
nop 0
1
<?php
2
3
namespace BenTools\SimpleDBAL\Model\Adapter\PDO;
4
5
use BenTools\SimpleDBAL\Contract\ResultInterface;
6
use BenTools\SimpleDBAL\Model\Exception\DBALException;
7
use IteratorAggregate;
8
use PDO;
9
use PDOStatement;
10
11
class Result implements IteratorAggregate, ResultInterface
12
{
13
    /**
14
     * @var PDO
15
     */
16
    private $pdo;
17
18
    /**
19
     * @var Statement
20
     */
21
    private $stmt;
22
23
    /**
24
     * @var array
25
     */
26
    private $storage = [];
27
28
    /**
29
     * @var bool
30
     */
31
    private $storageEnabled = true;
32
33
    /**
34
     * Result constructor.
35
     * @param PDO $pdo
36
     * @param Statement $stmt
37
     */
38
    public function __construct(PDO $pdo, PDOStatement $stmt = null)
39
    {
40
        $this->pdo = $pdo;
41
        $this->stmt = $stmt;
0 ignored issues
show
Documentation Bug introduced by
It seems like $stmt can also be of type object<PDOStatement>. However, the property $stmt is declared as type object<BenTools\SimpleDB...\Adapter\PDO\Statement>. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

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

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
42
    }
43
44
    /**
45
     * @inheritDoc
46
     */
47
    public function getLastInsertId()
48
    {
49
        return $this->pdo->lastInsertId();
50
    }
51
52
    /**
53
     * @inheritDoc
54
     */
55
    public function count()
56
    {
57
        return $this->stmt->rowCount();
0 ignored issues
show
Bug introduced by
The method rowCount() does not seem to exist on object<BenTools\SimpleDB...\Adapter\PDO\Statement>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
58
    }
59
60
    /**
61
     * @inheritDoc
62
     */
63
    public function asArray(): array
64
    {
65
        if (null === $this->stmt) {
66
            throw new DBALException("No \PDOStatement object provided.");
67
        }
68
        if (!empty($this->storage['row']) || !empty($this->storage['value']) || !empty($this->storage['list']) || !empty($this->storage['yield'])) {
69
            $this->stmt->execute();
0 ignored issues
show
Bug introduced by
The method execute() does not seem to exist on object<BenTools\SimpleDB...\Adapter\PDO\Statement>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
70
        }
71
        if (empty($this->storage['array'])) {
72
            if ($this->shouldResetResultset()) {
73
                $this->resetResultset();
74
            }
75
76
            $result = $this->stmt->fetchAll(PDO::FETCH_ASSOC);
0 ignored issues
show
Bug introduced by
The method fetchAll() does not seem to exist on object<BenTools\SimpleDB...\Adapter\PDO\Statement>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
77
78
            if (true === $this->storageEnabled) {
79
                $this->storage['array'] = $result;
80
            }
81
82
            return $result;
83
        }
84
        return $this->storage['array'];
85
    }
86
87
    /**
88
     * @inheritDoc
89
     */
90
    public function asRow(): ?array
91
    {
92
        if (null === $this->stmt) {
93
            throw new DBALException("No \PDOStatement object provided.");
94
        }
95
        if (empty($this->storage['row'])) {
96
            if (isset($this->storage['array'][0])) {
97
                $this->storage['row'] = &$this->storage['array'][0];
98
            } else {
99
                if ($this->shouldResetResultset()) {
100
                    $this->resetResultset();
101
                }
102
103
                $result = $this->stmt->fetch(PDO::FETCH_ASSOC) ?: null;
0 ignored issues
show
Bug introduced by
The method fetch() does not seem to exist on object<BenTools\SimpleDB...\Adapter\PDO\Statement>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
104
105
                if (true === $this->storageEnabled) {
106
                    $this->storage['row'] = $result;
107
                }
108
                return $result;
109
            }
110
        }
111
        return $this->storage['row'];
112
    }
113
114
    /**
115
     * @inheritDoc
116
     */
117
    public function asList(): array
118
    {
119
        if (null === $this->stmt) {
120
            throw new DBALException("No \PDOStatement object provided.");
121
        }
122
        if (empty($this->storage['list'])) {
123
            if (!empty($this->storage['array'])) {
124
                $this->storage['list'] = array_column($this->storage['array'], array_keys($this->storage['array'][0])[0]);
125
            } else {
126
                if ($this->shouldResetResultset()) {
127
                    $this->resetResultset();
128
                }
129
130
                $generator = function (\PDOStatement $stmt) {
131
                    while ($value = $stmt->fetchColumn(0)) {
132
                        yield $value;
133
                    }
134
                };
135
136
                $result = iterator_to_array($generator($this->stmt));
137
138
                if (true === $this->storageEnabled) {
139
                    $this->storage['list'] = $result;
140
                }
141
142
                return $result;
143
            }
144
        }
145
        return $this->storage['list'];
146
    }
147
148
    /**
149
     * @inheritDoc
150
     */
151
    public function asValue()
152
    {
153
        if (null === $this->stmt) {
154
            throw new DBALException("No \PDOStatement object provided.");
155
        }
156
        if (empty($this->storage['value'])) {
157
            if (!empty($this->storage['list'][0])) {
158
                $this->storage['value'] = $this->storage['list'][0];
159
            } elseif (!empty($this->storage['row'])) {
160
                $this->storage['value'] = array_values($this->storage['row'])[0];
161
            } elseif (!empty($this->storage['array'])) {
162
                $this->storage['value'] = array_values($this->storage['array'][0])[0];
163
            } else {
164
                if ($this->shouldResetResultset()) {
165
                    $this->resetResultset();
166
                }
167
168
                $result = $this->stmt->fetchColumn(0) ?: null;
0 ignored issues
show
Bug introduced by
The method fetchColumn() does not seem to exist on object<BenTools\SimpleDB...\Adapter\PDO\Statement>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
169
170
                if (true === $this->storageEnabled) {
171
                    $this->storage['value'] = $result;
172
                }
173
174
                return $result;
175
            }
176
        }
177
        return $this->storage['value'];
178
    }
179
180
181
    /**
182
     * @inheritDoc
183
     */
184
    public function getIterator()
185
    {
186
        if (null === $this->stmt) {
187
            throw new DBALException("No \PDOStatement object provided.");
188
        }
189
190
        // If asArray() was called earlier, iterate over the stored resultset.
191
        if (!empty($this->storage['array'])) {
192
            foreach ($this->storage['array'] as $key => $value) {
193
                yield $key => $value;
194
            }
195
        } else {
196
            $wrappedStmt = $this->stmt;
197
198
            if ($this->shouldResetResultset()) {
199
                $this->resetResultset();
200
            }
201
202
            while ($row = $wrappedStmt->fetch(PDO::FETCH_ASSOC)) {
0 ignored issues
show
Bug introduced by
The method fetch() does not seem to exist on object<BenTools\SimpleDB...\Adapter\PDO\Statement>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
203
                if (empty($this->storage['yield'])) {
204
                    $this->storage['yield'] = true;
205
                }
206
                yield $row;
207
            }
208
        }
209
    }
210
211
    /**
212
     * If asRow(), asList() or asValue() was called earlier, the iterator may be incomplete.
213
     * In such case we need to rewind the iterator by executing the statement a second time.
214
     * You should avoid to call getIterator() and asRow(), etc. with the same resultset.
215
     *
216
     * @return bool
217
     */
218
    private function shouldResetResultset(): bool
219
    {
220
        return !empty($this->storage['row']) || !empty($this->storage['value']) || !empty($this->storage['list']) || !empty($this->storage['yield']);
221
    }
222
223
    /**
224
     * Reset the resultset.
225
     */
226
    private function resetResultset()
227
    {
228
        $this->stmt->execute();
0 ignored issues
show
Bug introduced by
The method execute() does not seem to exist on object<BenTools\SimpleDB...\Adapter\PDO\Statement>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
229
    }
230
231
    /**
232
     * @return ResultInterface
233
     */
234
    public function withoutStorage(): ResultInterface
235
    {
236
        $clone = clone $this;
237
        $clone->storage = [];
238
        $clone->storageEnabled = false;
239
        return $clone;
240
    }
241
}
242