| 1 |
<?php |
| 2 |
|
| 3 |
namespace CodesVault\Howdyqb; |
| 4 |
|
| 5 |
final class Connect |
| 6 |
{ |
| 7 |
private static $configs; |
| 8 |
private static $pdo; |
| 9 |
|
| 10 |
public static function config($configs) |
| 11 |
{ |
| 12 |
static::$configs = $configs; |
| 13 |
} |
| 14 |
|
| 15 |
public static function pdo() |
| 16 |
{ |
| 17 |
if (static::$pdo !== null) { |
| 18 |
return static::$pdo; |
| 19 |
} |
| 20 |
|
| 21 |
$configs = static::$configs ? (object)static::$configs : false; |
| 22 |
if (! $configs) { |
| 23 |
global $wpdb; |
| 24 |
$configs = $wpdb; |
| 25 |
} |
| 26 |
if (! $configs) { |
| 27 |
throw new \Exception('Database configuration not found'); |
| 28 |
} |
| 29 |
|
| 30 |
$host = htmlspecialchars($configs->dbhost, ENT_QUOTES); |
| 31 |
$dbname = htmlspecialchars($configs->dbname, ENT_QUOTES); |
| 32 |
$user = htmlspecialchars($configs->dbuser, ENT_QUOTES); |
| 33 |
$password = $configs->dbpassword; |
| 34 |
$dns = "mysql:host=$host;dbname=$dbname"; |
| 35 |
|
| 36 |
try { |
| 37 |
static::$pdo = new \PDO($dns, $user, $password); |
| 38 |
return static::$pdo; |
| 39 |
} catch (\PDOException $exception) { |
| 40 |
Utilities::throughException($exception); |
| 41 |
} |
| 42 |
} |
| 43 |
|
| 44 |
public static function setManualConnection(array $configs = []) |
| 45 |
{ |
| 46 |
$configurations = []; |
| 47 |
if (! defined('DB_HOST')) { |
| 48 |
$path = explode('/wp-content', dirname(__DIR__)); |
| 49 |
if (! empty($path) && ! file_exists($path[0] . '/wp-config.php')) { |
| 50 |
throw new \Exception('wp-config.php file not found'); |
| 51 |
} |
| 52 |
require $path[0] . '/wp-config.php'; |
| 53 |
|
| 54 |
$configurations = [ |
| 55 |
"dbhost" => DB_HOST, |
| 56 |
"dbname" => DB_NAME, |
| 57 |
"dbuser" => DB_USER, |
| 58 |
"dbpassword" => DB_PASSWORD, |
| 59 |
"prefix" => $table_prefix, |
| 60 |
]; |
| 61 |
} |
| 62 |
|
| 63 |
$configurations = array_merge($configurations, $configs); |
| 64 |
static::$configs = (object)$configurations; |
| 65 |
} |
| 66 |
} |
| 67 |
|