Config::__construct()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 1
Code Lines 0

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 0
nc 1
nop 0
dl 0
loc 1
rs 10
c 0
b 0
f 0
1
<?php declare( strict_types=1 );
2
3
namespace BotRiconferme;
4
5
use BotRiconferme\Exception\ConfigException;
6
7
/**
8
 * Singleton class holding user-defined config
9
 */
10
class Config {
11
	/** @var self */
12
	private static $instance;
13
	/** @var string[] */
14
	private $opts = [];
15
16
	/**
17
	 * Use self::init() and self::getInstance()
18
	 */
19
	private function __construct() {
20
	}
21
22
	/**
23
	 * Initialize a new self instance with CLI params set and retrieve on-wiki config.
24
	 *
25
	 * @param string[] $confValues
26
	 * @throws ConfigException
27
	 */
28
	public static function init( array $confValues ): void {
29
		if ( self::$instance ) {
30
			throw new ConfigException( 'Config was already initialized' );
31
		}
32
33
		$inst = new self();
34
35
		foreach ( $confValues as $key => $val ) {
36
			$inst->set( $key, $val );
37
		}
38
		self::$instance = $inst;
39
	}
40
41
	/**
42
	 * Set a config value.
43
	 *
44
	 * @param string $key
45
	 * @param mixed $value
46
	 */
47
	protected function set( string $key, $value ): void {
48
		$this->opts[ $key ] = $value;
49
	}
50
51
	/**
52
	 * Generic instance getter
53
	 *
54
	 * @return self
55
	 * @throws ConfigException
56
	 */
57
	public static function getInstance(): self {
58
		if ( !self::$instance ) {
59
			throw new ConfigException( 'Config not yet initialized' );
60
		}
61
		return self::$instance;
62
	}
63
64
	/**
65
	 * Get the requested option, or fail if it doesn't exist
66
	 *
67
	 * @param string $opt
68
	 * @return mixed
69
	 * @throws ConfigException
70
	 */
71
	public function get( string $opt ) {
72
		if ( !isset( $this->opts[ $opt ] ) ) {
73
			throw new ConfigException( "Config option '$opt' not set." );
74
		}
75
		return $this->opts[ $opt ];
76
	}
77
}
78