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
|
|
|
|