MediaWiki master
ConfigFactory.php
Go to the documentation of this file.
1<?php
2
10namespace MediaWiki\Config;
11
12use InvalidArgumentException;
13use UnexpectedValueException;
14use Wikimedia\Assert\Assert;
15use Wikimedia\Services\SalvageableService;
16
22class ConfigFactory implements SalvageableService {
23
28 protected $factoryFunctions = [];
29
35 protected $configs = [];
36
48 public function salvage( SalvageableService $other ) {
49 Assert::parameterType( self::class, $other, '$other' );
50
52 '@phan-var self $other';
53 foreach ( $other->factoryFunctions as $name => $otherFunc ) {
54 if ( !isset( $this->factoryFunctions[$name] ) ) {
55 continue;
56 }
57
58 // if the callback function is the same, salvage the Cache object
59 // XXX: Closures are never equal!
60 if ( isset( $other->configs[$name] )
61 && $this->factoryFunctions[$name] == $otherFunc
62 ) {
63 $this->configs[$name] = $other->configs[$name];
64 unset( $other->configs[$name] );
65 }
66 }
67
68 // disable $other
69 $other->factoryFunctions = [];
70 $other->configs = [];
71 }
72
76 public function getConfigNames() {
77 return array_keys( $this->factoryFunctions );
78 }
79
89 public function register( $name, $callback ) {
90 if ( !is_callable( $callback ) && !( $callback instanceof Config ) ) {
91 if ( is_array( $callback ) ) {
92 $callback = '[ ' . implode( ', ', $callback ) . ' ]';
93 } elseif ( is_object( $callback ) ) {
94 $callback = 'instanceof ' . get_class( $callback );
95 }
96 throw new InvalidArgumentException( 'Invalid callback \'' . $callback . '\' provided' );
97 }
98
99 unset( $this->configs[$name] );
100 $this->factoryFunctions[$name] = $callback;
101 }
102
112 public function makeConfig( $name ) {
113 if ( !isset( $this->configs[$name] ) ) {
114 $key = $name;
115 if ( !isset( $this->factoryFunctions[$key] ) ) {
116 $key = '*';
117 }
118 if ( !isset( $this->factoryFunctions[$key] ) ) {
119 throw new ConfigException( "No registered builder available for $name." );
120 }
121
122 $factory = $this->factoryFunctions[$key];
123 if ( is_callable( $factory ) ) {
124 $conf = $factory( $this );
125 } else {
126 $conf = $factory;
127 }
128
129 if ( $conf instanceof Config ) {
130 $this->configs[$name] = $conf;
131 } else {
132 throw new UnexpectedValueException( "The builder for $name returned a non-Config object." );
133 }
134 }
135
136 return $this->configs[$name];
137 }
138
139}
140
142class_alias( ConfigFactory::class, 'ConfigFactory' );
Factory class to create Config objects.
Config callable[] $factoryFunctions
Map of config name => Config or callback.
array $configs
Config objects that have already been created name => Config object.
salvage(SalvageableService $other)
Re-uses existing Cache objects from $other.
Interface for configuration instances.
Definition Config.php:18