1: <?php
2: /**
3: * This file is part of the Autarky package.
4: *
5: * (c) Andreas Lutro <anlutro@gmail.com>
6: *
7: * For the full copyright and license information, please view the LICENSE
8: * file that was distributed with this source code.
9: */
10:
11: namespace Autarky\Database;
12:
13: use Autarky\Config\ConfigInterface;
14:
15: /**
16: * Manager for multiple database connections in the form of PDO instances and
17: * configuration data.
18: */
19: class ConnectionManager
20: {
21: /**
22: * @var ConfigInterface
23: */
24: protected $config;
25:
26: /**
27: * @var ConnectionFactory
28: */
29: protected $factory;
30:
31: /**
32: * The default connection to use
33: *
34: * @var string
35: */
36: protected $defaultConnection;
37:
38: /**
39: * PDO instances.
40: *
41: * @var \PDO[]
42: */
43: protected $instances = [];
44:
45: /**
46: * Constructor.
47: *
48: * @param ConfigInterface $config
49: * @param ConnectionFactoryInterface $factory
50: * @param string|null $defaultConnection If null, "database.connection" is
51: * retrieved from $config
52: */
53: public function __construct(
54: ConfigInterface $config,
55: ConnectionFactoryInterface $factory,
56: $defaultConnection = null
57: ) {
58: $this->config = $config;
59: $this->factory = $factory;
60: $this->defaultConnection = $defaultConnection ?: $config->get('database.connection');
61: }
62:
63: /**
64: * Get a PDO instance.
65: *
66: * @param string|null $connection Null fetches the default connection.
67: *
68: * @return \PDO
69: */
70: public function getPdo($connection = null)
71: {
72: if ($connection === null) {
73: $connection = $this->defaultConnection;
74: }
75:
76: if (isset($this->instances[$connection])) {
77: return $this->instances[$connection];
78: }
79:
80: $config = $this->getConnectionConfig($connection);
81:
82: return $this->instances[$connection] = $this->factory->makePdo($config, $connection);
83: }
84:
85: /**
86: * Get the configuration array for a specific connection.
87: *
88: * @param string $connection The name of the connection.
89: *
90: * @return array
91: *
92: * @throws \InvalidArgumentException If connection is not defined
93: */
94: public function getConnectionConfig($connection = null)
95: {
96: if ($connection === null) {
97: $connection = $this->defaultConnection;
98: }
99:
100: $config = $this->config->get("database.connections.$connection");
101:
102: if (!$config) {
103: if (!is_string($connection)) {
104: $connection = gettype($connection);
105: }
106:
107: throw new \InvalidArgumentException("No config found for connection: $connection");
108: }
109:
110: return $config;
111: }
112: }
113: