Repository navigation
Expand file tree
/
Copy pathFakeDbService.php
More file actions
209 lines (171 loc) · 6.74 KB
/
Copy pathFakeDbService.php
File metadata and controls
209 lines (171 loc) · 6.74 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
<?php
declare(strict_types=1);
namespace SqlFirstDemo\Testing;
use Generator;
use LogicException;
use SqlFirstDemo\Db\DbServiceInterface;
use SqlFirstDemo\Db\QueryException;
use SqlFirstDemo\Result\RowSet;
use Throwable;
/**
* A hand-written fake of {@see DbServiceInterface}, keyed by SQL text. Use it in unit tests
* instead of a mocking library.
*
* WHY A FAKE AND NOT A MOCK
* -------------------------
* A mock (`createMock(DbServiceInterface::class)`) is configured in terms of METHOD CALLS:
* "expect query() to be called once with any arguments and return X". That couples the test to
* how the query class happens to call the gateway, and it says nothing about the SQL.
*
* This fake is configured in terms of SQL: "when THIS statement runs, return THESE rows". The
* query class under test passes its own `SQL` constant, the test configures the fake with the
* same constant, and the fake returns the raw rows you gave it, exactly as a driver would hand
* them over. After the call, the test can read back exactly which SQL ran with which parameters.
*
* Unconfigured SQL is an error, not an empty result. A test that forgot to configure a statement
* fails with a message listing what WAS configured, instead of passing on an accidental `[]`.
*
* WHAT IT CANNOT DO
* -----------------
* It cannot tell you the SQL is right. It returns whatever rows you hand it, even for a SELECT
* naming a column that does not exist. That is why every query class in this demo also has an
* integration test against a real database, and why
* {@see \SqlFirstDemo\PHPStan\Rules\FakeDbTestNeedsIntegrationTestRule} makes that pairing
* compulsory rather than a good intention.
*/
final class FakeDbService implements DbServiceInterface
{
/** @var array<string, list<list<array<string, mixed>>>> normalised SQL => queued row sets */
private array $queryResults = [];
/** @var array<string, list<int>> normalised SQL => queued affected-row counts */
private array $executeResults = [];
/** @var array<string, int> normalised SQL => insert id */
private array $insertResults = [];
/** @var array<string, Throwable> normalised SQL => failure to throw */
private array $failures = [];
/** @var list<array{sql: string, params: array<string, scalar|null>}> */
private array $executed = [];
private int $transactions = 0;
/**
* When `$sql` is queried, return `$rows`. Call it more than once for the same SQL to queue
* results; the last one repeats once the queue is down to it.
*
* Write rows in the least helpful shape a driver might send: numbers as strings (what PDO gives
* with STRINGIFY_FETCHES, an older driver or older PHP), NULL as null. If the code under test
* copes with that, it copes with native ints too, because Row accepts both.
*
* @param list<array<string, mixed>> $rows
*/
public function onQuery(string $sql, array $rows): self
{
$this->queryResults[self::normalise($sql)][] = $rows;
return $this;
}
public function onExecute(string $sql, int $affectedRows): self
{
$this->executeResults[self::normalise($sql)][] = $affectedRows;
return $this;
}
public function onInsert(string $sql, int $insertId): self
{
$this->insertResults[self::normalise($sql)] = $insertId;
return $this;
}
/**
* When `$sql` runs, fail the way the real service would: with the cause wrapped in a
* {@see QueryException}. Use it to test your error paths.
*/
public function onFailure(string $sql, Throwable $cause): self
{
$this->failures[self::normalise($sql)] = $cause;
return $this;
}
/**
* Every statement that ran, in order, with its parameters, whitespace-normalised.
*
* @return list<array{sql: string, params: array<string, scalar|null>}>
*/
public function executed(): array
{
return $this->executed;
}
public function transactionCount(): int
{
return $this->transactions;
}
public function queryRows(string $sql, array $params = []): RowSet
{
return RowSet::fromRawRows($this->query($sql, $params));
}
public function query(string $sql, array $params = []): array
{
$key = $this->record($sql, $params);
return self::shift($this->queryResults, $key) ?? throw $this->unconfigured('query', $key);
}
public function stream(string $sql, array $params = []): Generator
{
yield from $this->query($sql, $params);
}
public function execute(string $sql, array $params = []): int
{
$key = $this->record($sql, $params);
return self::shift($this->executeResults, $key) ?? throw $this->unconfigured('execute', $key);
}
public function insert(string $sql, array $params = []): int
{
$key = $this->record($sql, $params);
if (!str_starts_with(strtoupper($key), 'INSERT')) {
throw QueryException::forNonInsert($sql);
}
return $this->insertResults[$key] ?? throw $this->unconfigured('insert', $key);
}
public function transactional(callable $action): mixed
{
++$this->transactions;
return $action();
}
/**
* Log the call, throw the configured failure if there is one, and return the lookup key.
*
* @param array<string, scalar|null> $params
*/
private function record(string $sql, array $params): string
{
$key = self::normalise($sql);
$this->executed[] = ['sql' => $key, 'params' => $params];
if (isset($this->failures[$key])) {
throw QueryException::forFailedStatement($sql, $params, $this->failures[$key]);
}
return $key;
}
/**
* Take the next queued result for `$key`, leaving the last one in place so it repeats.
*
* @template T
*
* @param array<string, list<T>> $queues
*
* @return T|null
*/
private static function shift(array &$queues, string $key): mixed
{
if (!isset($queues[$key]) || [] === $queues[$key]) {
return null;
}
return \count($queues[$key]) > 1 ? array_shift($queues[$key]) : $queues[$key][0];
}
private function unconfigured(string $method, string $sql): LogicException
{
$configured = array_keys($this->queryResults + $this->executeResults + $this->insertResults);
return new LogicException(\sprintf(
"FakeDbService::%s() got SQL nobody configured:\n %s\nConfigured:\n %s",
$method,
$sql,
[] === $configured ? '(nothing)' : implode("\n ", $configured),
));
}
private static function normalise(string $sql): string
{
return trim((string)preg_replace('/\s+/', ' ', $sql));
}
}