aboutsummaryrefslogtreecommitdiffstats
path: root/includes/Settings/LocalSettingsLoader.php
blob: f39b77ae79f63051e0cd976c01fef19da225233c (plain) (blame)
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
<?php

namespace MediaWiki\Settings;

use MediaWiki\Settings\Source\SettingsFileUtils;

/**
 * Utility for loading LocalSettings files.
 *
 * @since 1.38
 */
class LocalSettingsLoader {

	private SettingsBuilder $settingsBuilder;

	private string $baseDir;

	/**
	 * @param SettingsBuilder $settingsBuilder
	 * @param string $baseDir
	 */
	public function __construct( SettingsBuilder $settingsBuilder, string $baseDir ) {
		$this->settingsBuilder = $settingsBuilder;
		$this->baseDir = $baseDir;
	}

	/**
	 * Loads a settings file into the SettingsBuilder provided to the constructor.
	 *
	 * This supports JSON and YAML files, PHP files that return a settings array, as well as
	 * traditional LocalSettings.php files that set variables, for backwards compatibility.
	 *
	 * @warning This does not support setting configuration variables that use a prefix other
	 *          than "wg"!
	 *
	 * @param string $file
	 */
	public function loadLocalSettingsFile( string $file ) {
		// If $file is not a PHP file, just load it as a data file.
		if ( !str_ends_with( $file, '.php' ) ) {
			$this->settingsBuilder->loadFile( $file );
			return;
		}

		// Make config settings available in local scope.
		$config = $this->settingsBuilder->getConfig();
		foreach ( $this->settingsBuilder->getDefinedConfigKeys() as $key ) {
			$var = "wg$key"; // NOTE: broken for extensions that use prefixes other than "wg"!
			$$var = $config->get( $key ); // XXX: slow?! Can we get the entire array in one go?
		}

		// make available some non-config globals available
		// phpcs:ignore MediaWiki.VariableAnalysis.UnusedGlobalVariables.UnusedGlobal$wgCommandLineMode, MediaWiki.Usage.DeprecatedGlobalVariables
		global $wgCommandLineMode;

		// make additional variables available
		// phpcs:ignore MediaWiki.VariableAnalysis.MisleadingGlobalNames.Misleading$wgSettings
		$wgSettings = $this->settingsBuilder;
		$IP = $this->baseDir;

		// pull in the actual settings file
		$file = SettingsFileUtils::resolveRelativeLocation( $file, $this->baseDir );
		$settings = require $file;

		// Capture config variables.
		$overrides = [];
		foreach ( get_defined_vars() as $name => $value ) {
			if ( str_starts_with( $name, 'wg' ) ) {
				$key = substr( $name, 2 );
				$overrides[$key] = $value;
			}
		}

		$this->settingsBuilder->overrideConfigValues( $overrides );

		// If the file returned a settings array, use it.
		// This is especially useful for generated PHP files.
		if ( is_array( $settings ) ) {
			$this->settingsBuilder->loadArray( $settings );
		}
	}
}