summaryrefslogtreecommitdiff
path: root/www/wiki/extensions/SemanticMediaWiki/src/Query/QuerySourceFactory.php
blob: 8c4a4f0c0f6770732946cbf114885d83d72c21aa (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
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
<?php

namespace SMW\Query;

use RuntimeException;
use SMW\QueryEngine;
use SMW\Store;
use SMW\StoreAware;

/**
 * @private
 *
 * @license GNU GPL v2+
 * @since 2.5
 *
 * @author mwjames
 */
class QuerySourceFactory {

	/**
	 * @var Store
	 */
	private $store;

	/**
	 * @var array
	 */
	private $querySources = [];

	/**
	 * @since 2.5
	 *
	 * @param Store $store
	 * @param array $querySources
	 */
	public function __construct( Store $store, $querySources = [] ) {
		$this->store = $store;
		$this->querySources = $querySources;

		// Standard store
		$this->querySources['sql_store'] = 'SMW\SQLStore\SQLStore';
	}

	/**
	 * @see DefaultSettings::$smwgQuerySources
	 *
	 * @since 2.5
	 *
	 * @param string|null $source
	 *
	 * @return QueryEngine|Store
	 * @throws RuntimeException
	 */
	public function get( $source = null ) {

		$params = [];

		if ( $source !== '' && isset( $this->querySources[$source] ) ) {

			$querySource = $this->querySources[$source];

			// [ '\SMW\FooHandler', ... parameters ],
			if ( is_array( $querySource ) ) {
				$source = array_shift( $querySource );
				$params = $querySource;
			} else {
				$source = $this->querySources[$source];
			}
		}

		// Fallback to the default store
		if ( $source === null || !class_exists( $source ) ) {
			$source = $this->store;
		} elseif ( $params !== [] ) {
			$source = new $source( $params );
		} else {
			$source = new $source;
		}

		if ( !$source instanceof QueryEngine && !$source instanceof Store ) {
			throw new RuntimeException(  get_class( $source ) . " does not match the expected QueryEngine interface." );
		}

		if ( $source instanceof StoreAware ) {
			$source->setStore( $this->store );
		}

		return $source;
	}

	/**
	 * @since 2.5
	 *
	 * @param string|null $source
	 *
	 * @return string
	 */
	public function toString( $source = null ) {

		if ( $source === 'sql_store' ) {
			return 'SMWSQLStore';
		}

		if ( $source !== '' && $source !== null ) {
			return $source;
		}

		return json_encode( $this->store->getInfo( 'store' ) );
	}

}