-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathConnectionManager.php
109 lines (91 loc) · 3.17 KB
/
ConnectionManager.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
<?php
namespace WebStream\Database;
use WebStream\Container\Container;
use WebStream\Exception\Extend\ClassNotFoundException;
use WebStream\Exception\Extend\DatabaseException;
use WebStream\IO\File;
/**
* ConnectionManager
* @author Ryuichi TANAKA.
* @since 2014/06/13
* @version 0.4
*/
class ConnectionManager
{
/**
* @var array<string> クラスパス-DSNハッシュマップ
*/
private array $classpathMap;
/**
* @var Container データベース接続項目コンテナ
*/
private Container $connectionContainer;
/**
* constructor
* @param Container $container
*/
public function __construct(Container $container)
{
$this->initialize($container);
}
/**
* destructor
*/
public function __destruct()
{
unset($this->connectionContainer);
}
/**
* DBコネクションを返却する
* @param string Modelクラスファイルパス
* @return DatabaseDriver データベースドライバインスタンス
*/
public function getConnection($filepath)
{
$dsnHash = $this->classpathMap[$filepath];
return $dsnHash !== null ? $this->connectionContainer->{$dsnHash} : null;
}
/**
* 初期処理
* @param Container $container
*/
private function initialize(Container $container)
{
$this->classpathMap = [];
$this->connectionContainer = new Container(false);
$logger = $container->logger;
$innerException = null;
foreach ($container->connectionContainerList as $connectionContainer) {
$config = null;
$configFile = new File($connectionContainer->configPath);
if (!$configFile->exists()) {
throw new DatabaseException("Database configuration file is not found: " . $configFile->getFilePath());
}
$ext = $configFile->getFileExtension();
if ($ext === 'ini') {
$config = parse_ini_file($configFile->getFilePath());
} elseif ($ext === 'yml' || $ext === 'yaml') {
$config = \Spyc::YAMLLoad($configFile->getFilePath());
} else {
throw new DatabaseException("Yaml or ini file only available database configuration file.");
}
$driverClassPath = $connectionContainer->driverClassPath;
if (!class_exists($driverClassPath)) {
throw new ClassNotFoundException("$driverClassPath is not defined.");
}
$dsnHash = "";
$databaseConfigContainer = new Container(false);
foreach ($config as $key => $value) {
$dsnHash .= $key . $value;
$databaseConfigContainer->set($key, $value);
}
$dsnHash = md5($dsnHash);
$this->classpathMap[$connectionContainer->filepath] = $dsnHash;
$this->connectionContainer->{$dsnHash} = function () use ($driverClassPath, $databaseConfigContainer, $logger) {
$driver = new $driverClassPath($databaseConfigContainer);
$driver->inject('logger', $logger);
return $driver;
};
}
}
}