summaryrefslogtreecommitdiff
path: root/www/wiki/extensions/SemanticMediaWiki/src/Connection/ConnectionManager.php
blob: 4e16ffee211dcb0277c3182002d38b967119d008 (plain)
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
<?php

namespace SMW\Connection;

use RuntimeException;

/**
 * @license GNU GPL v2+
 * @since 2.1
 *
 * @author mwjames
 */
class ConnectionManager {

	/**
	 * By design this variable is static to ensure that ConnectionProvider
	 * instances are only initialized once per request.
	 *
	 * @var array
	 */
	private static $connectionProviders = [];

	/**
	 * @since 2.1
	 *
	 * @param string|null $id
	 *
	 * @return mixed
	 * @throws RuntimeException
	 */
	public function getConnection( $id = null ) {
		return $this->findConnectionProvider( strtolower( $id ) )->getConnection();
	}

	/**
	 * @since 2.1
	 */
	public function releaseConnections() {
		foreach ( self::$connectionProviders as $connectionProvider ) {
			$connectionProvider->releaseConnection();
		}
	}

	/**
	 * @since 2.1
	 *
	 * @param string $id
	 * @param ConnectionProvider $connectionProvider
	 */
	public function registerConnectionProvider( $id, ConnectionProvider $connectionProvider ) {
		self::$connectionProviders[strtolower( $id )] = $connectionProvider;
	}

	/**
	 * @since 3.0
	 *
	 * @param string $id
	 * @param callable $callback
	 */
	public function registerCallbackConnection( $id, callable $callback ) {
		self::$connectionProviders[strtolower( $id )] = new CallbackConnectionProvider( $callback );
	}

	private function findConnectionProvider( $id ) {

		if ( isset( self::$connectionProviders[$id] ) ) {
			return self::$connectionProviders[$id];
		}

		throw new RuntimeException( "{$id} is missing a registered connection provider" );
	}

}