Debian Codegraph @

includes/Settings/Config/GlobalConfigBuilder.php

raw symbols SCIP
1 <?php
2
3 namespace MediaWiki\Settings\Config;
4
5 use MediaWiki\Config\Config;
6 use MediaWiki\Config\GlobalVarConfig;
7 use function array_key_exists;
8
9 class GlobalConfigBuilder extends ConfigBuilderBase {
10
11 public const DEFAULT_PREFIX = 'wg';
12
13 /** @var string */
14 private $prefix;
15
16 /**
17 * @param string $prefix
18 */
19 public function __construct( string $prefix = self::DEFAULT_PREFIX ) {
20 $this->prefix = $prefix;
21 }
22
23 protected function has( string $key ): bool {
24 $var = $this->getVarName( $key );
25 // (T317951) Don't call array_key_exists unless we have to, as it's slow
26 // on PHP 8.1+ for $GLOBALS. When the key is set but is explicitly set
27 // to null, we still need to fall back to array_key_exists, but that's
28 // rarer.
29 return isset( $GLOBALS[$var] ) || array_key_exists( $var, $GLOBALS );
30 }
31
32 public function get( string $key ) {
33 $var = $this->getVarName( $key );
34 return $GLOBALS[ $var ] ?? null;
35 }
36
37 protected function update( string $key, $value ) {
38 $var = $this->getVarName( $key );
39 $GLOBALS[ $var ] = $value;
40 }
41
42 public function setMulti( array $values, array $mergeStrategies = [] ): ConfigBuilder {
43 // NOTE: It is tempting to do $GLOBALS = array_merge( $GLOBALS, $values ).
44 // But that no longer works in PHP 8.1!
45 // See https://wiki.php.net/rfc/restrict_globals_usage
46
47 foreach ( $values as $key => $newValue ) {
48 $var = $this->prefix . $key; // inline getVarName() to avoid function call
49
50 // Optimization: Inlined logic from set() for performance
51 if ( isset( $GLOBALS[$var] ) && array_key_exists( $key, $mergeStrategies ) ) {
52 $mergeStrategy = $mergeStrategies[$key];
53 if ( $mergeStrategy && is_array( $newValue ) ) {
54 $oldValue = $GLOBALS[$var];
55 if ( $oldValue && is_array( $oldValue ) ) {
56 $newValue = $mergeStrategy->merge( $oldValue, $newValue );
57 }
58 }
59 }
60
61 $GLOBALS[$var] = $newValue;
62 }
63 return $this;
64 }
65
66 private function getVarName( string $key ): string {
67 return $this->prefix . $key;
68 }
69
70 public function build(): Config {
71 return new GlobalVarConfig( $this->prefix );
72 }
73 }