1<?php 2# PDO test framework utilities 3 4if (getenv('PDOTEST_DSN') === false) { 5 $common = ''; 6 $append = false; 7 foreach(file(dirname($_SERVER['PHP_SELF']).'/common.phpt') as $line) { 8 if ($append) { 9 $common .= $line; 10 } elseif (trim($line) == '--REDIRECTTEST--') { 11 $append = true; 12 } 13 } 14 $conf = eval($common); 15 foreach($conf['ENV'] as $n=>$v) putenv("$n=$v"); 16} 17 18class PDOTest { 19 // create an instance of the PDO driver, based on 20 // the current environment 21 static function factory($classname = PDO::class, bool $useConnectMethod = false) { 22 $dsn = getenv('PDOTEST_DSN'); 23 $user = getenv('PDOTEST_USER'); 24 $pass = getenv('PDOTEST_PASS'); 25 $attr = getenv('PDOTEST_ATTR'); 26 if (is_string($attr) && strlen($attr)) { 27 $attr = unserialize($attr); 28 } else { 29 $attr = null; 30 } 31 32 if ($user === false) $user = NULL; 33 if ($pass === false) $pass = NULL; 34 35 if ($useConnectMethod) { 36 $db = $classname::connect($dsn, $user, $pass, $attr); 37 } else { 38 $db = new $classname($dsn, $user, $pass, $attr); 39 } 40 41 if (!$db) { 42 die("Could not create PDO object (DSN=$dsn, user=$user)\n"); 43 } 44 // Ignore errors about non-existent tables 45 $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_SILENT); 46 47 $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING); 48 $db->setAttribute(PDO::ATTR_CASE, PDO::CASE_LOWER); 49 $db->setAttribute(PDO::ATTR_STRINGIFY_FETCHES, true); 50 return $db; 51 } 52 53 static function skip() { 54 try { 55 $db = PDOTest::factory(); 56 } catch (PDOException $e) { 57 die("skip " . $e->getMessage()); 58 } 59 } 60 61 static function test_factory($file, $classname = PDO::class, bool $useConnectMethod = false) { 62 $config = self::get_config($file); 63 foreach ($config['ENV'] as $k => $v) { 64 putenv("$k=$v"); 65 } 66 return self::factory($classname, $useConnectMethod); 67 } 68 69 static function get_config($file) { 70 $data = file_get_contents($file); 71 $data = preg_replace('/^.*--REDIRECTTEST--/s', '', $data); 72 $config = eval($data); 73 74 return $config; 75 } 76 77 public static function dropTableIfExists(PDO $db, string $tableName): void { 78 if (getenv('PDOTEST_DSN') === "sqlite::memory:") { 79 return; 80 } 81 82 match ($db->getAttribute(PDO::ATTR_DRIVER_NAME)) { 83 "oci" => $db->exec(<<<SQL 84 BEGIN 85 EXECUTE IMMEDIATE 'DROP TABLE $tableName'; 86 EXCEPTION 87 WHEN OTHERS THEN 88 IF SQLCODE != -942 THEN 89 RAISE; 90 END IF; 91 END; 92 SQL 93 ), 94 "firebird" => @$db->exec("DROP TABLE $tableName"), 95 default => $db->exec("DROP TABLE IF EXISTS $tableName"), 96 }; 97 } 98} 99?> 100