Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 34 additions & 0 deletions src/FakePdoStatementTrait.php
Original file line number Diff line number Diff line change
Expand Up @@ -508,6 +508,40 @@ function ($row) use ($fetch_argument, $ctor_args) {
);
}

if ($fetch_style === \PDO::FETCH_KEY_PAIR) {
if (!$this->result) {
return [];
}

/** @var array<array-key, mixed> $output */
$output = [];

foreach ($this->result as $row) {
if ($this->conn->shouldStringifyResult()) {
$row = self::stringify($row);
}

/** @var list<?scalar> $values */
$values = \array_values($row);

if (\count($values) < 2) {
throw new \PDOException('PDO::FETCH_KEY_PAIR requires at least two columns');
}

$key = $values[0];

if (\is_int($key) || \is_string($key)) {
$output[$key] = $values[1];
} elseif ($key === null) {
$output[''] = $values[1];
} else {
$output[(int) $key] = $values[1];
}
}

return $output;
}

throw new \Exception('Fetch style not implemented');
}

Expand Down
40 changes: 40 additions & 0 deletions tests/EndToEndTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -118,6 +118,46 @@ public function testSelectFetchAssoc()
);
}

public function testSelectFetchKeyPair()
{
$pdo = self::getConnectionToFullDB();

$query = $pdo->prepare("SELECT id, name FROM `video_game_characters` WHERE `id` > :id ORDER BY `id` ASC");
$query->bindValue(':id', 14);
$query->execute();

$this->assertSame(
[
'15' => 'link',
'16' => 'dude'
],
$query->fetchAll(\PDO::FETCH_KEY_PAIR)
);
}

public function testSelectFetchKeyPairWithVariousKeyTypes()
{
$pdo = self::getConnectionToFullDB(false);

$query = $pdo->prepare(
"SELECT 1.5, 'foo'
UNION ALL SELECT NULL, 'bar'
UNION ALL SELECT false, 'baz'
UNION ALL SELECT 2, 'qux'"
);
$query->execute();

$this->assertEqualsCanonicalizing(
[
1 => 'foo', // 1.5 -> 1
'' => 'bar', // NULL -> ''
0 => 'baz', // false -> 0
2 => 'qux', // 2 -> 2
],
$query->fetchAll(\PDO::FETCH_KEY_PAIR)
);
}

public function testSelectFetchAssocConverted()
{
$pdo = self::getConnectionToFullDB(false);
Expand Down
Loading