-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathFactory.php
More file actions
115 lines (102 loc) · 2.56 KB
/
Factory.php
File metadata and controls
115 lines (102 loc) · 2.56 KB
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
110
111
112
113
114
115
<?php
namespace Darya\Database;
use Darya\Database\Connection\Sqlite;
use UnexpectedValueException;
/**
* Darya's database connection factory.
*
* @author Chris Andrew <chris@hexus.io>
*/
class Factory
{
/**
* The class name or database type name to use by default
*
* @var string
*/
protected $default = 'mysql';
/**
* A map of database type names to connection implementation classes
*
* @var array
*/
protected $map = array(
'mysql' => 'Darya\Database\Connection\MySql',
'mssql' => 'Darya\Database\Connection\SqlServer',
'sqlserver' => 'Darya\Database\Connection\SqlServer',
'sqlite' => 'Darya\Database\Connection\Sqlite'
);
/**
* Instantiate a new database factory.
*
* @param string $default [optional] The default database type name
*/
public function __construct($default = null)
{
$this->default = $default ?: $this->default;
}
/**
* Prepare an options array by ensuring the existence of expected keys.
*
* @param array $options
* @return array
*/
protected function prepareOptions(array $options)
{
return array_merge(array(
'hostname' => 'localhost',
'username' => null,
'password' => null,
'database' => null,
'port' => null,
'options' => array()
), array_filter($options));
}
/**
* Resolve a database connection class name from the given string.
*
* @param string $string
* @return string
*/
protected function resolveClass($string)
{
if (class_exists($string)) {
return $string;
}
$string = strtolower($string);
if (!isset($this->map[$string])) {
return null;
}
return $this->map[$string];
}
/**
* Create a new database connection using the given name/class and options.
*
* @param string $name The database type name
* @param array $options Expects keys 'hostname', 'username', 'password',
* 'database' and optionally 'port'
* @return Connection
*/
public function create($name = null, array $options = array())
{
$name = $name ?: $this->default;
$class = $this->resolveClass($name);
$options = $this->prepareOptions($options);
if (!class_exists($class) || !is_subclass_of($class, Connection::class)) {
throw new UnexpectedValueException(
"Couldn't resolve a valid database connection instance for type '$name'"
);
}
// TODO: Clean this up
if ($class === Sqlite::class) {
return new $class($options['database'], $options['options']);
}
return new $class(
$options['hostname'],
$options['username'],
$options['password'],
$options['database'],
$options['port']
);
}
}