Skip to content

Commit becf558

Browse files
committed
feat: Support PDO::FETCH_KEY_PAIR
1 parent 839b2fb commit becf558

File tree

2 files changed

+74
-0
lines changed

2 files changed

+74
-0
lines changed

src/FakePdoStatementTrait.php

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -508,6 +508,40 @@ function ($row) use ($fetch_argument, $ctor_args) {
508508
);
509509
}
510510

511+
if ($fetch_style === \PDO::FETCH_KEY_PAIR) {
512+
if (!$this->result) {
513+
return [];
514+
}
515+
516+
/** @var array<array-key, mixed> $output */
517+
$output = [];
518+
519+
foreach ($this->result as $row) {
520+
if ($this->conn->shouldStringifyResult()) {
521+
$row = self::stringify($row);
522+
}
523+
524+
/** @var list<?scalar> $values */
525+
$values = \array_values($row);
526+
527+
if (\count($values) < 2) {
528+
throw new \PDOException('PDO::FETCH_KEY_PAIR requires at least two columns');
529+
}
530+
531+
$key = $values[0];
532+
533+
if (\is_int($key) || \is_string($key)) {
534+
$output[$key] = $values[1];
535+
} elseif ($key === null) {
536+
$output[''] = $values[1];
537+
} elseif (\is_float($key) || \is_bool($key)) {
538+
$output[(int) $key] = $values[1];
539+
}
540+
}
541+
542+
return $output;
543+
}
544+
511545
throw new \Exception('Fetch style not implemented');
512546
}
513547

tests/EndToEndTest.php

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -95,6 +95,46 @@ public function testSelectFetchAssoc()
9595
);
9696
}
9797

98+
public function testSelectFetchKeyPair()
99+
{
100+
$pdo = self::getConnectionToFullDB();
101+
102+
$query = $pdo->prepare("SELECT id, name FROM `video_game_characters` WHERE `id` > :id ORDER BY `id` ASC");
103+
$query->bindValue(':id', 14);
104+
$query->execute();
105+
106+
$this->assertSame(
107+
[
108+
'15' => 'link',
109+
'16' => 'dude'
110+
],
111+
$query->fetchAll(\PDO::FETCH_KEY_PAIR)
112+
);
113+
}
114+
115+
public function testSelectFetchKeyPairWithVariousKeyTypes()
116+
{
117+
$pdo = self::getConnectionToFullDB(false);
118+
119+
$query = $pdo->prepare(
120+
"SELECT 1.5, 'foo'
121+
UNION ALL SELECT NULL, 'bar'
122+
UNION ALL SELECT false, 'baz'
123+
UNION ALL SELECT 2, 'qux'"
124+
);
125+
$query->execute();
126+
127+
$this->assertEqualsCanonicalizing(
128+
[
129+
1 => 'foo', // 1.5 -> 1
130+
'' => 'bar', // NULL -> ''
131+
0 => 'baz', // false -> 0
132+
2 => 'qux', // 2 -> 2
133+
],
134+
$query->fetchAll(\PDO::FETCH_KEY_PAIR)
135+
);
136+
}
137+
98138
public function testSelectFetchAssocConverted()
99139
{
100140
$pdo = self::getConnectionToFullDB(false);

0 commit comments

Comments
 (0)