Kufrik/app/Model/Database/KufrikConnectionFactory.php

69 lines
2.0 KiB
PHP

<?php
namespace App\Model\Database;
use Nette\Database\Connection;
use Nette\Database\Explorer;
use Nette\Database\Structure;
use Nette\Caching\Storages\MemoryStorage;
use Nette\Security\User;
class KufrikConnectionFactory
{
private User $user;
private array $baseConfig;
public function __construct(array $baseConfig, User $user)
{
$this->baseConfig = $baseConfig;
$this->user = $user;
}
public function createConnection(): Connection
{
if (!$this->user->isLoggedIn()) {
throw new \LogicException('Uživatel není přihlášen.');
}
$identity = $this->user->getIdentity();
// 1. Dynamické načtení z identity (každý uživatel může mít jiný server i DB!)
$host = $identity->db_host ?? $this->baseConfig['host'];
$databaseName = $identity->db_name ?? $this->baseConfig['default_db'];
$firmaId = $identity->firma_id ?? null;
if (!$firmaId) {
throw new \LogicException('Uživatel nemá zvolenou žádnou aktivní firmu.');
}
// 2. Sestavení DSN pro konkrétní SQL Server a DB
$dsn = "sqlsrv:Server={$host};Database={$databaseName}";
// Přihlašovací údaje k SQL serveru (buď společné ze souboru, nebo dynamické)
$connection = new Connection(
$dsn,
$this->baseConfig['username'],
$this->baseConfig['password'],
[
'lazy' => false,
'driverOptions' => [
\PDO::SQLSRV_ATTR_ENCODING => \PDO::SQLSRV_ENCODING_UTF8,
]
]
);
// 3. Nastavení RLS kontextu pro firmu
$connection->query('EXEC sp_set_session_context @key = N\'FirmaId\', @value = ?', $firmaId);
return $connection;
}
public function createExplorer(): Explorer
{
$connection = $this->createConnection();
$storage = new MemoryStorage();
$structure = new Structure($connection, $storage);
return new Explorer($connection, $structure);
}
}