64 lines
1.8 KiB
PHP
64 lines
1.8 KiB
PHP
<?php
|
|
|
|
namespace App\Providers;
|
|
|
|
use App\Database\Db2\Db2Connection;
|
|
use Illuminate\Support\Facades\DB;
|
|
use Illuminate\Support\ServiceProvider;
|
|
use PDO;
|
|
|
|
class AppServiceProvider extends ServiceProvider
|
|
{
|
|
public function register(): void
|
|
{
|
|
DB::extend('odbc', function (array $config, string $name): Db2Connection {
|
|
$pdo = new PDO(
|
|
'odbc:'.($config['dsn'] ?? 'MEDIUK'),
|
|
$config['username'] ?? '',
|
|
$config['password'] ?? '',
|
|
[
|
|
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
|
|
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_OBJ,
|
|
]
|
|
);
|
|
|
|
$config['schema'] = $this->resolveDb2Schema($pdo, $config['schema'] ?? null);
|
|
$config['name'] = $name;
|
|
|
|
return new Db2Connection(
|
|
$pdo,
|
|
$config['database'] ?? '',
|
|
$config['prefix'] ?? '',
|
|
$config
|
|
);
|
|
});
|
|
}
|
|
|
|
/**
|
|
* Apply an explicit schema and read the effective schema for catalog queries.
|
|
*/
|
|
private function resolveDb2Schema(PDO $pdo, ?string $configuredSchema): string
|
|
{
|
|
$schema = trim($configuredSchema ?? '');
|
|
|
|
if ($schema !== '') {
|
|
if (! preg_match('/^[A-Za-z_][A-Za-z0-9_]*$/D', $schema)) {
|
|
throw new \InvalidArgumentException('Invalid Db2 schema');
|
|
}
|
|
|
|
$pdo->exec('SET CURRENT SCHEMA '.$schema);
|
|
|
|
return strtoupper($schema);
|
|
}
|
|
|
|
$currentSchema = $pdo->query('VALUES CURRENT SCHEMA')->fetchColumn();
|
|
if (! is_string($currentSchema) || trim($currentSchema) === '') {
|
|
throw new \RuntimeException('Unable to resolve the current Db2 schema.');
|
|
}
|
|
|
|
return rtrim($currentSchema);
|
|
}
|
|
|
|
public function boot(): void {}
|
|
}
|