Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
100.00% covered (success)
100.00%
33 / 33
100.00% covered (success)
100.00%
2 / 2
CRAP
100.00% covered (success)
100.00%
1 / 1
DatabaseServiceProvider
100.00% covered (success)
100.00%
33 / 33
100.00% covered (success)
100.00%
2 / 2
3
100.00% covered (success)
100.00%
1 / 1
 register
100.00% covered (success)
100.00%
32 / 32
100.00% covered (success)
100.00%
1 / 1
2
 exitOnError
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
1<?php
2
3declare(strict_types=1);
4
5namespace Engelsystem\Database;
6
7use Carbon\Carbon;
8use Engelsystem\Config\Config;
9use Engelsystem\Container\ServiceProvider;
10use Exception;
11use Illuminate\Database\Capsule\Manager as CapsuleManager;
12use Illuminate\Database\Connection as DatabaseConnection;
13use PDO;
14use PDOException;
15use Throwable;
16
17class DatabaseServiceProvider extends ServiceProvider
18{
19    public function register(): void
20    {
21        /** @var Config $config */
22        $config = $this->app->get('config');
23        /** @var CapsuleManager $capsule */
24        $capsule = $this->app->make(CapsuleManager::class);
25        $now = Carbon::now($config->get('timezone'));
26
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        ], $config->get('database', [])));
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(PDO::class, $pdo);
51        $this->app->instance(CapsuleManager::class, $capsule);
52        $this->app->instance(Db::class, $capsule);
53        Db::setDbManager($capsule);
54
55        $connection = $capsule->getConnection();
56        $this->app->instance(DatabaseConnection::class, $connection);
57
58        $database = $this->app->make(Database::class);
59        $this->app->instance(Database::class, $database);
60        $this->app->instance('db', $database);
61        $this->app->instance('db.pdo', $pdo);
62        $this->app->instance('db.connection', $connection);
63    }
64
65    /**
66     *
67     * @throws Exception
68     */
69    protected function exitOnError(Throwable $exception): void
70    {
71        throw new Exception('Error: Unable to connect to database', 0, $exception);
72    }
73}