Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- namespace AppBundle\Services\DbService;
- use Doctrine\ORM\EntityManager;
- use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
- use Doctrine\DBAL\Connection;
- use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;
- use Symfony\Component\Security\Core\Exception\AccessDeniedException;
- class DbFactory
- {
- protected $dynamicEm; //Entity manager for dynamically connected database
- // $dbConnection is the connection from your config, set in the config with blank values.
- // $em is the related entity manager.
- public function __construct(AuthorizationCheckerInterface $authChecker, Connection $dbConnection, EntityManager $em, TokenStorageInterface $tokenStorage)
- {
- if(!$authChecker->isGranted("IS_AUTHENTICATED_FULLY")) {
- throw new AccessDeniedException();
- }
- $connectionDetails = $tokenStorage->getToken()->getUser()->getStuffForConnection();
- $user = $connectionDetails->get("dbUser");
- $dbParams = $dbConnection->getParams();
- // Check to make sure dynamic connection isn't already setup.
- // Might not actually need to check this, since the factory should only be called once.
- if($dbParams["user"] !== $user) {
- $dbParams["user"] = $user;
- $dbParams["host"] = $connectionDetails->getDbHost();
- $dbParams["dbname"] = $connectionDetails->getDbDatabaseName();
- $dbParams["password"] = $connectionDetails->getDbPassword();
- if($connectionDetails->isConnected()) {
- $connectionDetails->close();
- }
- $connectionDetails->__construct(
- $dbParams, $connectionDetails->getDriver(), $connectionDetails->getConfiguration(), $connectionDetails->getEventManager()
- );
- try {
- $connectionDetails->connect();
- }
- catch(Exception $ex) {
- error_log("Failed to connect to DB");
- throw new Exception("Failed to connect to DB");
- // Handle this error however you want.
- }
- }
- $this->dynamicEm = $em;
- }
- public function getSkdbEm()
- {
- return $this->dynamicEm;
- }
- public function getRepository($repName)
- {
- return $this->dynamicEm->getRepository($repName);
- }
- public function getSpecificRepository()
- {
- return $this->dynamicEm->getRepository('Bundle:specific');
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement