Completed
Pull Request — master (#410)
by Elan
01:38
created

PdoStorageProvider   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 46
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 3

Importance

Changes 0
Metric Value
wmc 5
lcom 0
cbo 3
dl 0
loc 46
rs 10
c 0
b 0
f 0

1 Method

Rating   Name   Duplication   Size   Complexity  
B register() 0 43 5
1
<?php
2
3
namespace XHGui\ServiceProvider;
4
5
use PDO;
6
use Pimple\Container;
7
use Pimple\ServiceProviderInterface;
8
use RuntimeException;
9
use XHGui\Db\PdoRepository;
10
use XHGui\Saver\PdoSaver;
11
use XHGui\Searcher\PdoSearcher;
12
13
class PdoStorageProvider implements ServiceProviderInterface
14
{
15
    public function register(Container $app): void
16
    {
17
        $app['pdo'] = static function ($app) {
18
            if (!class_exists(PDO::class)) {
19
                throw new RuntimeException('Required extension ext-pdo is missing');
20
            }
21
22
            $driver = explode(':', $app['config']['pdo']['dsn'], 2)[0];
23
24
            // check the PDO driver is available
25
            if (!in_array($driver, PDO::getAvailableDrivers(), true)) {
26
                $drivers = implode(',', PDO::getAvailableDrivers()) ?: '(none)';
27
                throw new RuntimeException("Required PDO driver $driver is missing, Available drivers: $drivers");
28
            }
29
30
            $options = [
31
                PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
32
            ];
33
34
            if ($driver === 'mysql') {
35
                $options[PDO::MYSQL_ATTR_INIT_COMMAND] = 'SET SQL_MODE=ANSI_QUOTES;';
36
            }
37
38
            return new PDO(
39
                $app['config']['pdo']['dsn'],
40
                $app['config']['pdo']['user'],
41
                $app['config']['pdo']['pass'],
42
                $options
43
            );
44
        };
45
46
        $app[PdoRepository::class] = static function ($app) {
47
            return new PdoRepository($app['pdo'], $app['config']['pdo']['table']);
48
        };
49
50
        $app['searcher.pdo'] = static function ($app) {
51
            return new PdoSearcher($app[PdoRepository::class]);
52
        };
53
54
        $app['saver.pdo'] = static function ($app) {
55
            return new PdoSaver($app[PdoRepository::class]);
56
        };
57
    }
58
}
59