Code Coverage |
||||||||||
Lines |
Functions and Methods |
Classes and Traits |
||||||||
| Total | |
100.00% |
33 / 33 |
|
100.00% |
2 / 2 |
CRAP | |
100.00% |
1 / 1 |
| DatabaseServiceProvider | |
100.00% |
33 / 33 |
|
100.00% |
2 / 2 |
3 | |
100.00% |
1 / 1 |
| register | |
100.00% |
32 / 32 |
|
100.00% |
1 / 1 |
2 | |||
| exitOnError | |
100.00% |
1 / 1 |
|
100.00% |
1 / 1 |
1 | |||
| 1 | <?php |
| 2 | |
| 3 | declare(strict_types=1); |
| 4 | |
| 5 | namespace Engelsystem\Database; |
| 6 | |
| 7 | use Carbon\Carbon; |
| 8 | use Engelsystem\Config\Config; |
| 9 | use Engelsystem\Container\ServiceProvider; |
| 10 | use Exception; |
| 11 | use Illuminate\Database\Capsule\Manager as CapsuleManager; |
| 12 | use Illuminate\Database\Connection as DatabaseConnection; |
| 13 | use PDOException; |
| 14 | use Throwable; |
| 15 | |
| 16 | class DatabaseServiceProvider extends ServiceProvider |
| 17 | { |
| 18 | public function register(): void |
| 19 | { |
| 20 | /** @var Config $config */ |
| 21 | $config = $this->app->get('config'); |
| 22 | /** @var CapsuleManager $capsule */ |
| 23 | $capsule = $this->app->make(CapsuleManager::class); |
| 24 | $now = Carbon::now($config->get('timezone')); |
| 25 | |
| 26 | $dbConfig = $config->get('database'); |
| 27 | $capsule->addConnection(array_merge([ |
| 28 | 'driver' => 'mysql', |
| 29 | 'host' => '', |
| 30 | 'database' => '', |
| 31 | 'username' => '', |
| 32 | 'password' => '', |
| 33 | 'charset' => 'utf8mb4', |
| 34 | 'collation' => 'utf8mb4_unicode_ci', |
| 35 | 'timezone' => $now->format('P'), |
| 36 | 'prefix' => '', |
| 37 | ], $dbConfig)); |
| 38 | |
| 39 | $capsule->setAsGlobal(); |
| 40 | $capsule->bootEloquent(); |
| 41 | $capsule->getConnection()->useDefaultSchemaGrammar(); |
| 42 | |
| 43 | $pdo = null; |
| 44 | try { |
| 45 | $pdo = $capsule->getConnection()->getPdo(); |
| 46 | } catch (PDOException $e) { |
| 47 | $this->exitOnError($e); |
| 48 | } |
| 49 | |
| 50 | $this->app->instance(CapsuleManager::class, $capsule); |
| 51 | $this->app->instance(Db::class, $capsule); |
| 52 | Db::setDbManager($capsule); |
| 53 | |
| 54 | $connection = $capsule->getConnection(); |
| 55 | $this->app->instance(DatabaseConnection::class, $connection); |
| 56 | |
| 57 | $database = $this->app->make(Database::class); |
| 58 | $this->app->instance(Database::class, $database); |
| 59 | $this->app->instance('db', $database); |
| 60 | $this->app->instance('db.pdo', $pdo); |
| 61 | $this->app->instance('db.connection', $connection); |
| 62 | } |
| 63 | |
| 64 | /** |
| 65 | * |
| 66 | * @throws Exception |
| 67 | */ |
| 68 | protected function exitOnError(Throwable $exception): void |
| 69 | { |
| 70 | throw new Exception('Error: Unable to connect to database', 0, $exception); |
| 71 | } |
| 72 | } |