# phpDox - Source of ConnectionManager.php

# Source of file ConnectionManager.php

Size: 5,219 Bytes - Last Modified: 2020-04-17T14:56:27-04:00

## src/ConnectionManager.php

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242

    <?php declare(strict_types=1);

    /**

     * Query

     *

     * SQL Query Builder / Database Abstraction Layer

     *

     * PHP version 7.4

     *

     * @package     Query

     * @author      Timothy J. Warren <tim@timshomepage.net>

     * @copyright   2012 - 2020 Timothy J. Warren

     * @license     http://www.opensource.org/licenses/mit-license.html  MIT License

     * @link        https://git.timshomepage.net/aviat/Query

     * @version     3.0.0

     */

    namespace Query;

    use DomainException;

    use stdClass;

    /**

     * Connection manager class to manage connections for the

     * Query method

     */

    final class ConnectionManager {

    	/**

    	 * Map of named database connections

    	 * @var array

    	 */

    	private array $connections = [];

    	/**

    	 * Class instance variable

    	 * @var ConnectionManager|null

    	 */

    	private static ?ConnectionManager $instance = NULL;

    	/**

    	 * Private constructor to prevent multiple instances

    	 * @codeCoverageIgnore

    	 */

    	private function __construct()

    	{

    	}

    	/**

    	 * Private clone method to prevent cloning

    	 *

    	 * @throws DomainException

    	 * @return void

    	 */

    	public function __clone()

    	{

    		throw new DomainException("Can't clone singleton");

    	}

    	/**

    	 * Prevent serialization of this object

    	 *

    	 * @throws DomainException

    	 * @return void

    	 */

    	public function __sleep(): void

    	{

    		throw new DomainException('No serializing of singleton');

    	}

    	/**

    	 * Make sure serialize/deserialize doesn't work

    	 *

    	 * @throws DomainException

    	 * @return void

    	 */

    	public function __wakeup(): void

    	{

    		throw new DomainException("Can't unserialize singleton");

    	}

    	/**

    	 * Return  a connection manager instance

    	 *

    	 * @staticvar null $instance

    	 * @return ConnectionManager

    	 */

    	public static function getInstance(): ConnectionManager

    	{

    		if (self::$instance === NULL)

    		{

    			self::$instance = new self();

    		}

    		return self::$instance;

    	}

    	/**

    	 * Returns the connection specified by the name given

    	 *

    	 * @param string|array|object $name

    	 * @return QueryBuilderInterface

    	 * @throws Exception\NonExistentConnectionException

    	 */

    	public function getConnection($name = ''): QueryBuilderInterface

    	{

    		// If the parameter is a string, use it as an array index

    		if (is_scalar($name) && isset($this->connections[$name]))

    		{

    			return $this->connections[$name];

    		}

    		if (empty($name) && ! empty($this->connections)) // Otherwise, return the last one

    		{

    			return end($this->connections);

    		}

    		// You should actually connect before trying to get a connection...

    		throw new Exception\NonExistentConnectionException('The specified connection does not exist');

    	}

    	/**

    	 * Parse the passed parameters and return a connection

    	 *

    	 * @param array|object $params

    	 * @throws Exception\BadDBDriverException

    	 * @return QueryBuilderInterface

    	 */

    	public function connect($params): QueryBuilderInterface

    	{

    		[$dsn, $dbType, $params, $options] = $this->parseParams($params);

    		$dbType = ucfirst($dbType);

    		$driver = "\\Query\\Drivers\\{$dbType}\\Driver";

    		// Create the database connection

    		$db =  ! empty($params->user)

    			? new $driver($dsn, $params->user, $params->pass, $options)

    			: new $driver($dsn, '', '', $options);

    		// Set the table prefix, if it exists

    		if (isset($params->prefix))

    		{

    			$db->setTablePrefix($params->prefix);

    		}

    		// Create Query Builder object

    		$conn = new QueryBuilder($db, new QueryParser($db));

    		// Save it for later

    		if (isset($params->alias))

    		{

    			$this->connections[$params->alias] = $conn;

    		}

    		else

    		{

    			$this->connections[] = $conn;

    		}

    		return $conn;

    	}

    	/**

    	 * Parses params into a dsn and option array

    	 *

    	 * @param array|object $rawParams

    	 * @return array

    	 * @throws Exception\BadDBDriverException

    	 */

    	public function parseParams($rawParams): array

    	{

    		$params = (object) $rawParams;

    		$params->type = strtolower($params->type);

    		$dbType = ($params->type === 'postgresql') ? 'pgsql' : $params->type;

    		$dbType = ucfirst($dbType);

    		// Make sure the class exists

    		if ( ! class_exists("\\Query\\Drivers\\{$dbType}\\Driver"))

    		{

    			throw new Exception\BadDBDriverException('Database driver does not exist, or is not supported');

    		}

    		// Set additional PDO options

    		$options = [];

    		if (isset($params->options))

    		{

    			$options = (array) $params->options;

    		}

    		// Create the dsn for the database to connect to

    		if(strtolower($dbType) === 'sqlite')

    		{

    			$dsn = $params->file;

    		}

    		else

    		{

    			$dsn = $this->createDsn($dbType, $params);

    		}

    		return [$dsn, $dbType, $params, $options];

    	}

    	/**

    	 * Create the dsn from the db type and params

    	 *

    	 * @codeCoverageIgnore

    	 * @param string $dbType

    	 * @param stdClass $params

    	 * @return string

    	 */

    	private function createDsn(string $dbType, stdClass $params): string

    	{

    		$pairs = [];

    		if ( ! empty($params->database))

    		{

    			$pairs[] = implode('=', ['dbname', $params->database]);

    		}

    		$skip = [

    			'name' => 'name',

    			'pass' => 'pass',

    			'user' => 'user',

    			'type' => 'type',

    			'prefix' => 'prefix',

    			'options' => 'options',

    			'database' => 'database',

    			'alias' => 'alias'

    		];

    		foreach($params as $key => $val)

    		{

    			if (( ! array_key_exists($key, $skip)) &&  ! empty($val))

    			{

    				$pairs[] = implode('=', [$key, $val]);

    			}

    		}

    		return strtolower($dbType) . ':' . implode(';', $pairs);

    	}

    }