| 1 |
<?php |
| 2 |
|
| 3 |
namespace FluentForm\Framework\Database; |
| 4 |
|
| 5 |
use InvalidArgumentException; |
| 6 |
use FluentForm\Framework\Foundation\App; |
| 7 |
use FluentForm\Framework\Database\ConnectionResolverInterface; |
| 8 |
|
| 9 |
class ConnectionResolver implements ConnectionResolverInterface |
| 10 |
{ |
| 11 |
/** |
| 12 |
* All of the registered connections. |
| 13 |
* |
| 14 |
* @var array |
| 15 |
*/ |
| 16 |
protected $connections = []; |
| 17 |
|
| 18 |
/** |
| 19 |
* The default connection name. |
| 20 |
* |
| 21 |
* @var string |
| 22 |
*/ |
| 23 |
protected $default; |
| 24 |
|
| 25 |
/** |
| 26 |
* Create a new connection resolver instance. |
| 27 |
* |
| 28 |
* @param array $connections |
| 29 |
* @return void |
| 30 |
*/ |
| 31 |
public function __construct(array $connections = []) |
| 32 |
{ |
| 33 |
foreach ($connections as $name => $connection) { |
| 34 |
$this->addConnection($name, $connection); |
| 35 |
} |
| 36 |
} |
| 37 |
|
| 38 |
/** |
| 39 |
* Get a database connection instance. |
| 40 |
* |
| 41 |
* @param string|null $name |
| 42 |
* @return \FluentForm\Framework\Database\ConnectionInterface |
| 43 |
*/ |
| 44 |
public function connection($name = null) |
| 45 |
{ |
| 46 |
if ($name instanceof ConnectionInterface) { |
| 47 |
return $name; |
| 48 |
} |
| 49 |
|
| 50 |
if (is_null($name)) { |
| 51 |
$name = $this->getDefaultConnection(); |
| 52 |
} |
| 53 |
|
| 54 |
if (isset($this->connections[$name])) { |
| 55 |
return $this->connections[$name]; |
| 56 |
} |
| 57 |
|
| 58 |
throw new InvalidArgumentException("Connection [{$name}] not found."); |
| 59 |
} |
| 60 |
|
| 61 |
/** |
| 62 |
* Add a connection to the resolver. |
| 63 |
* |
| 64 |
* @param string $name |
| 65 |
* @param \FluentForm\Framework\Database\ConnectionInterface $connection |
| 66 |
* @return void |
| 67 |
*/ |
| 68 |
public function addConnection($name, ConnectionInterface $connection) |
| 69 |
{ |
| 70 |
$this->connections[$name] = $connection; |
| 71 |
} |
| 72 |
|
| 73 |
/** |
| 74 |
* Check if a connection has been registered. |
| 75 |
* |
| 76 |
* @param string $name |
| 77 |
* @return bool |
| 78 |
*/ |
| 79 |
public function hasConnection($name) |
| 80 |
{ |
| 81 |
return isset($this->connections[$name]); |
| 82 |
} |
| 83 |
|
| 84 |
/** |
| 85 |
* Get the default connection name. |
| 86 |
* |
| 87 |
* @return string |
| 88 |
*/ |
| 89 |
public function getDefaultConnection() |
| 90 |
{ |
| 91 |
return $this->default; |
| 92 |
} |
| 93 |
|
| 94 |
/** |
| 95 |
* Set the default connection name. |
| 96 |
* |
| 97 |
* @param string $name |
| 98 |
* @return void |
| 99 |
*/ |
| 100 |
public function setDefaultConnection($name) |
| 101 |
{ |
| 102 |
$this->default = $name; |
| 103 |
} |
| 104 |
} |
| 105 |
|