Kufrik/app/Model/Database/KufrikConnectionFactory.php

70 lines
2.1 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 string $dbUser;
private string $dbPassword;
public function __construct(string $dbUser, string $dbPassword, User $user)
{
$this->dbUser = $dbUser;
$this->dbPassword = $dbPassword;
$this->user = $user;
}
public function createConnection(): Connection
{
if (!$this->user->isLoggedIn()) {
throw new \LogicException('Uživatel není přihlášen.');
}
$identity = $this->user->getIdentity();
// Server, Databáze i FirmaId se načtou z Identity přihlášeného uživatele
$host = $identity->server ?? null;
$databaseName = $identity->database ?? null;
$firmaId = $identity->firma_id ?? null;
if (empty($host) || empty($databaseName) || empty($firmaId)) {
throw new \LogicException('Přihlášený uživatel nemá v tabulce LOGIN definovaný SERVER, DATABASE nebo FIRMA_ID.');
}
// Dynamický DSN řetězec
$dsn = "sqlsrv:Server={$host};Database={$databaseName};LoginTimeout=3;";
$connection = new Connection(
$dsn,
$this->dbUser,
$this->dbPassword,
[
'lazy' => false, // Spojení musí vzniknout ihned
'driverOptions' => [
\PDO::SQLSRV_ATTR_ENCODING => \PDO::SQLSRV_ENCODING_UTF8,
]
]
);
// NASTAVENÍ RLS KONTEXTU PRO MS SQL SERVER
$connection->query('EXEC sp_set_session_context @key = N\'FirmaId\', @value = ?', (int)$firmaId);
return $connection;
}
public function createExplorer(): Explorer
{
$connection = $this->createConnection();
$storage = new MemoryStorage();
$structure = new Structure($connection, $storage);
return new Explorer($connection, $structure);
}
}