|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace Silviooosilva\CacheerPhp\Core; |
|
4
|
|
|
|
|
5
|
|
|
use PDO; |
|
6
|
|
|
use PDOException; |
|
7
|
|
|
use Silviooosilva\CacheerPhp\Enums\DatabaseDriver; |
|
8
|
|
|
use Silviooosilva\CacheerPhp\Exceptions\ConnectionException; |
|
9
|
|
|
|
|
10
|
|
|
/** |
|
11
|
|
|
* Class ConnectionFactory |
|
12
|
|
|
* @author Sílvio Silva <https://github.com/silviooosilva> |
|
13
|
|
|
* @package Silviooosilva\CacheerPhp |
|
14
|
|
|
*/ |
|
15
|
|
|
class ConnectionFactory |
|
16
|
|
|
{ |
|
17
|
|
|
|
|
18
|
|
|
/** |
|
19
|
|
|
* Creates a new PDO instance based on the specified database configuration. |
|
20
|
|
|
* |
|
21
|
|
|
* @param array|null $database |
|
22
|
|
|
* @return PDO|null |
|
23
|
|
|
* @throws ConnectionException |
|
24
|
|
|
*/ |
|
25
|
|
|
public static function createConnection(?array $database = null): ?PDO |
|
26
|
|
|
{ |
|
27
|
|
|
$connection = Connect::getConnection(); |
|
28
|
|
|
$dbConf = $database ?? CACHEER_DATABASE_CONFIG[$connection->value]; |
|
29
|
|
|
|
|
30
|
|
|
$driver = null; |
|
31
|
|
|
if (isset($dbConf['adapter'])) { |
|
32
|
|
|
$driver = DatabaseDriver::tryFrom($dbConf['adapter']); |
|
33
|
|
|
} |
|
34
|
|
|
if ($driver === null && isset($dbConf['driver'])) { |
|
35
|
|
|
$driver = DatabaseDriver::tryFrom($dbConf['driver']); |
|
36
|
|
|
} |
|
37
|
|
|
$driver ??= $connection; |
|
38
|
|
|
|
|
39
|
|
|
$dsnDriver = $driver->dsnName(); |
|
40
|
|
|
$dbConf['driver'] = $dsnDriver; |
|
41
|
|
|
|
|
42
|
|
|
if ($driver === DatabaseDriver::SQLITE) { |
|
43
|
|
|
$dbName = $dbConf['dbname']; |
|
44
|
|
|
$dbDsn = $dsnDriver . ':' . $dbName; |
|
45
|
|
|
} else { |
|
46
|
|
|
$dbName = "{$dsnDriver}-{$dbConf['dbname']}@{$dbConf['host']}"; |
|
|
|
|
|
|
47
|
|
|
$dbDsn = "{$dsnDriver}:host={$dbConf['host']};dbname={$dbConf['dbname']};port={$dbConf['port']}"; |
|
48
|
|
|
} |
|
49
|
|
|
|
|
50
|
|
|
try { |
|
51
|
|
|
$options = $dbConf['options'] ?? []; |
|
52
|
|
|
foreach ($options as $key => $value) { |
|
53
|
|
|
if (is_string($value) && defined($value)) { |
|
54
|
|
|
$options[$key] = constant($value); |
|
55
|
|
|
} |
|
56
|
|
|
} |
|
57
|
|
|
return new PDO($dbDsn, $dbConf['username'] ?? null, $dbConf['passwd'] ?? null, $options); |
|
58
|
|
|
} catch (PDOException $exception) { |
|
59
|
|
|
throw ConnectionException::create($exception->getMessage(), $exception->getCode(), $exception->getPrevious()); |
|
60
|
|
|
} |
|
61
|
|
|
} |
|
62
|
|
|
} |
|
63
|
|
|
|