Skip to content

Add support for PHP 8+ WeakMaps #110

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
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
39 changes: 33 additions & 6 deletions lib/mysql.php
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,14 @@ function mysql_connect(
return false;
}
MySQL::$last_connection = $conn;
$conn->hash = $hash; // @phpstan-ignore-line
if (class_exists('WeakMap')) {
if (is_null(MySQL::$conn_hash_weakmap)) {
MySQL::$conn_hash_weakmap = new WeakMap();
}
MySQL::$conn_hash_weakmap[$conn] = $hash;
} else {
$conn->hash = $hash; // @phpstan-ignore-line
}
MySQL::$connections[$hash] = array('refcount' => 1, 'conn' => $conn);

return $conn;
Expand Down Expand Up @@ -115,7 +122,14 @@ function mysql_connect(
}
// @codeCoverageIgnoreEnd

$conn->hash = $hash; // @phpstan-ignore-line
if (class_exists('WeakMap')) {
if (is_null(MySQL::$conn_hash_weakmap)) {
MySQL::$conn_hash_weakmap = new WeakMap();
}
MySQL::$conn_hash_weakmap[$conn] = $hash;
} else {
$conn->hash = $hash; // @phpstan-ignore-line
}
MySQL::$connections[$hash] = array('refcount' => 1, 'conn' => $conn);

return $conn;
Expand Down Expand Up @@ -150,14 +164,23 @@ function mysql_close(mysqli $link = null)
// @codeCoverageIgnoreEnd
}

if (isset(MySQL::$connections[$link->hash])) {
MySQL::$connections[$link->hash]['refcount'] -= 1;
if (class_exists('WeakMap')) {
if (is_null(MySQL::$conn_hash_weakmap)) {
MySQL::$conn_hash_weakmap = new WeakMap();
}
$link_hash = MySQL::$conn_hash_weakmap[$link];
} else {
$link_hash = $link->hash;
}

if (isset(MySQL::$connections[$link_hash])) {
MySQL::$connections[$link_hash]['refcount'] -= 1;
}

$return = true;
if (MySQL::$connections[$link->hash]['refcount'] === 0) {
if (MySQL::$connections[$link_hash]['refcount'] === 0) {
$return = mysqli_close($link);
unset(MySQL::$connections[$link->hash]);
unset(MySQL::$connections[$link_hash]);
}

if ($isDefault) {
Expand Down Expand Up @@ -789,6 +812,10 @@ class MySQL
{
public static $last_connection;
public static $connections = array();
/**
* @var null|\WeakMap
*/
public static $conn_hash_weakmap = null;

public static function getConnection($link = null, $func = null)
{
Expand Down