1: <?php
2:
3: namespace Charcoal\App\ServiceProvider;
4:
5:
6: use Exception;
7: use PDO;
8:
9:
10: use Pimple\ServiceProviderInterface;
11: use Pimple\Container;
12:
13:
14: use Charcoal\App\Config\DatabaseConfig;
15:
16: 17: 18: 19: 20: 21: 22: 23: 24: 25: 26: 27: 28:
29: class DatabaseServiceProvider implements ServiceProviderInterface
30: {
31: 32: 33: 34: 35: 36: 37: 38: 39:
40: public function register(Container $container)
41: {
42: 43: 44: 45:
46: $container['databases/config'] = function (Container $container) {
47: $config = $container['config'];
48: $databases = $config['databases'];
49: $configs = new Container();
50: foreach ($databases as $dbIdent => $dbOptions) {
51: $configs[$dbIdent] = new DatabaseConfig($dbOptions);
52: }
53: return $configs;
54: };
55:
56: 57: 58: 59:
60: $container['databases'] = function (Container $container) {
61: $config = $container['config'];
62: $databases = $config['databases'];
63: $dbs = new Container();
64: $origContainer = $container;
65: foreach ($databases as $dbIdent => $dbOptions) {
66: unset($dbOptions);
67:
68: 69: 70: 71:
72: $dbs[$dbIdent] = function () use ($dbIdent, $origContainer) {
73: $dbConfigs = $origContainer['databases/config'];
74: $dbConfig = $dbConfigs[$dbIdent];
75:
76: $type = $dbConfig['type'];
77: $host = $dbConfig['hostname'];
78:
79: $database = $dbConfig['database'];
80: $username = $dbConfig['username'];
81: $password = $dbConfig['password'];
82:
83:
84: $extraOptions = null;
85: if (!isset($dbConfig['disable_utf8']) || !$dbConfig['disable_utf8']) {
86: $extraOptions = [PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8mb4'];
87: }
88:
89: if ($type == 'sqlite') {
90: $dsn = $type.':'.$database;
91: } else {
92: $dsn = $type.':host='.$host.';dbname='.$database;
93: }
94: $db = new PDO($dsn, $username, $password, $extraOptions);
95:
96:
97: $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
98: if ($type == 'mysql') {
99: $db->setAttribute(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, true);
100: }
101: return $db;
102: };
103: }
104: return $dbs;
105: };
106:
107: 108: 109: 110:
111: $container['database/config'] = function (Container $container) {
112: $config = $container['config'];
113: $databaseIdent = $config['default_database'];
114: return $container['databases/config'][$databaseIdent];
115: };
116:
117: 118: 119: 120: 121: 122: 123:
124: $container['database'] = function (Container $container) {
125: $config = $container['config'];
126: $databaseIdent = $config['default_database'];
127: $databases = $container['databases'];
128: if (!isset($databases[$databaseIdent])) {
129: throw new Exception(
130: sprintf('The database "%s" is not defined in the "databases" configuration.', $databaseIdent)
131: );
132: }
133: return $databases[$databaseIdent];
134: };
135: }
136: }
137: