Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
100.00% covered (success)
100.00%
34 / 34
100.00% covered (success)
100.00%
2 / 2
CRAP
100.00% covered (success)
100.00%
1 / 1
DatabaseServiceProvider
100.00% covered (success)
100.00%
34 / 34
100.00% covered (success)
100.00%
2 / 2
3
100.00% covered (success)
100.00%
1 / 1
 register
100.00% covered (success)
100.00%
33 / 33
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        $dbConfig = $config->get('database');
28        $capsule->addConnection(array_merge([
29            'driver'    => 'mysql',
30            'host'      => '',
31            'database'  => '',
32            'username'  => '',
33            'password'  => '',
34            'charset'   => 'utf8mb4',
35            'collation' => 'utf8mb4_unicode_ci',
36            'timezone'  => $now->format('P'),
37            'prefix'    => '',
38        ], $dbConfig));
39
40        $capsule->setAsGlobal();
41        $capsule->bootEloquent();
42        $capsule->getConnection()->useDefaultSchemaGrammar();
43
44        $pdo = null;
45        try {
46            $pdo = $capsule->getConnection()->getPdo();
47        } catch (PDOException $e) {
48            $this->exitOnError($e);
49        }
50
51        $this->app->instance(PDO::class, $pdo);
52        $this->app->instance(CapsuleManager::class, $capsule);
53        $this->app->instance(Db::class, $capsule);
54        Db::setDbManager($capsule);
55
56        $connection = $capsule->getConnection();
57        $this->app->instance(DatabaseConnection::class, $connection);
58
59        $database = $this->app->make(Database::class);
60        $this->app->instance(Database::class, $database);
61        $this->app->instance('db', $database);
62        $this->app->instance('db.pdo', $pdo);
63        $this->app->instance('db.connection', $connection);
64    }
65
66    /**
67     *
68     * @throws Exception
69     */
70    protected function exitOnError(Throwable $exception): void
71    {
72        throw new Exception('Error: Unable to connect to database', 0, $exception);
73    }
74}