Files
kiri-databases/DatabasesProviders.php
T

92 lines
2.2 KiB
PHP
Raw Normal View History

2022-01-09 03:49:51 +08:00
<?php
declare(strict_types=1);
namespace Database;
use Exception;
2022-01-14 16:07:57 +08:00
use Kiri;
2022-01-09 03:49:51 +08:00
use Kiri\Abstracts\Providers;
/**
* Class DatabasesProviders
* @package Database
*/
class DatabasesProviders extends Providers
{
2022-07-11 14:15:21 +08:00
2023-08-16 14:30:39 +08:00
/**
2023-11-30 17:02:20 +08:00
* @var array
*/
protected array $connections = [];
/**
2023-08-16 14:30:39 +08:00
* @return void
2023-08-16 14:30:52 +08:00
* @throws
2023-08-16 14:30:39 +08:00
*/
2023-11-30 17:02:20 +08:00
public function onImport(): void
2023-08-16 14:30:39 +08:00
{
$main = Kiri::getDi()->get(Kiri\Application::class);
2023-11-30 17:02:20 +08:00
$main->command(BackupCommand::class, ImplodeCommand::class);
2023-05-26 09:20:29 +08:00
$databases = \config('databases.connections', []);
2023-11-30 17:02:20 +08:00
if (count($databases) < 1) {
2023-08-16 14:30:39 +08:00
return;
}
foreach ($databases as $key => $database) {
2023-11-30 17:02:20 +08:00
$this->set($key, $this->_settings($database));
2023-08-16 14:30:39 +08:00
}
}
2022-07-11 14:15:21 +08:00
2023-05-26 09:22:34 +08:00
2023-08-16 14:30:39 +08:00
/**
2023-12-18 18:11:58 +08:00
* @param string $name
2023-08-16 14:30:39 +08:00
* @return Connection
* @throws Exception
*/
2023-12-18 18:11:58 +08:00
public function get(string $name): Connection
2023-08-16 14:30:39 +08:00
{
2023-11-30 17:02:20 +08:00
return $this->connections[$name];
}
/**
2023-12-18 18:11:58 +08:00
* @param string $key
2023-11-30 17:02:20 +08:00
* @param array $connection
* @return void
* @throws Exception
*/
2023-12-18 18:11:58 +08:00
protected function set(string $key, array $connection): void
2023-11-30 17:02:20 +08:00
{
$this->connections[$key] = Kiri::createObject($connection);
2023-08-16 14:30:39 +08:00
}
2022-07-11 14:15:21 +08:00
2023-08-16 14:30:39 +08:00
/**
2023-12-18 18:11:58 +08:00
* @param array $database
2023-08-16 14:30:39 +08:00
* @return array
*/
2023-12-18 18:11:58 +08:00
private function _settings(array $database): array
2023-08-16 14:30:39 +08:00
{
$clientPool = $database['pool'] ?? ['min' => 1, 'max' => 5, 'tick' => 60];
return [
2023-11-14 15:01:30 +08:00
'id' => $database['id'],
'cds' => $database['cds'],
'class' => Connection::class,
'username' => $database['username'],
'password' => $database['password'],
'tablePrefix' => $database['tablePrefix'],
'database' => $database['database'],
'timeout' => $database['timeout'] ?? 10,
'tick_time' => $database['tick_time'] ?? 60,
'waite_time' => $database['waite_time'] ?? 3,
'pool' => $clientPool,
'attributes' => $database['attributes'] ?? [],
'charset' => $database['charset'] ?? 'utf8mb4'
2023-08-16 14:30:39 +08:00
];
}
2022-01-09 03:49:51 +08:00
}