MediaWiki master
ConfigFactory.php
Go to the documentation of this file.
1<?php
2
24namespace MediaWiki\Config;
25
26use InvalidArgumentException;
27use UnexpectedValueException;
28use Wikimedia\Assert\Assert;
29use Wikimedia\Services\SalvageableService;
30
36class ConfigFactory implements SalvageableService {
37
42 protected $factoryFunctions = [];
43
49 protected $configs = [];
50
62 public function salvage( SalvageableService $other ) {
63 Assert::parameterType( self::class, $other, '$other' );
64
66 '@phan-var self $other';
67 foreach ( $other->factoryFunctions as $name => $otherFunc ) {
68 if ( !isset( $this->factoryFunctions[$name] ) ) {
69 continue;
70 }
71
72 // if the callback function is the same, salvage the Cache object
73 // XXX: Closures are never equal!
74 if ( isset( $other->configs[$name] )
75 && $this->factoryFunctions[$name] == $otherFunc
76 ) {
77 $this->configs[$name] = $other->configs[$name];
78 unset( $other->configs[$name] );
79 }
80 }
81
82 // disable $other
83 $other->factoryFunctions = [];
84 $other->configs = [];
85 }
86
90 public function getConfigNames() {
91 return array_keys( $this->factoryFunctions );
92 }
93
103 public function register( $name, $callback ) {
104 if ( !is_callable( $callback ) && !( $callback instanceof Config ) ) {
105 if ( is_array( $callback ) ) {
106 $callback = '[ ' . implode( ', ', $callback ) . ' ]';
107 } elseif ( is_object( $callback ) ) {
108 $callback = 'instanceof ' . get_class( $callback );
109 }
110 throw new InvalidArgumentException( 'Invalid callback \'' . $callback . '\' provided' );
111 }
112
113 unset( $this->configs[$name] );
114 $this->factoryFunctions[$name] = $callback;
115 }
116
126 public function makeConfig( $name ) {
127 if ( !isset( $this->configs[$name] ) ) {
128 $key = $name;
129 if ( !isset( $this->factoryFunctions[$key] ) ) {
130 $key = '*';
131 }
132 if ( !isset( $this->factoryFunctions[$key] ) ) {
133 throw new ConfigException( "No registered builder available for $name." );
134 }
135
136 if ( $this->factoryFunctions[$key] instanceof Config ) {
137 $conf = $this->factoryFunctions[$key];
138 } else {
139 $conf = call_user_func( $this->factoryFunctions[$key], $this );
140 }
141
142 if ( $conf instanceof Config ) {
143 $this->configs[$name] = $conf;
144 } else {
145 throw new UnexpectedValueException( "The builder for $name returned a non-Config object." );
146 }
147 }
148
149 return $this->configs[$name];
150 }
151
152}
153
155class_alias( ConfigFactory::class, 'ConfigFactory' );
Factory class to create Config objects.
array $configs
Config objects that have already been created name => Config object.
array $factoryFunctions
Map of config name => callback.
salvage(SalvageableService $other)
Re-uses existing Cache objects from $other.
Interface for configuration instances.
Definition Config.php:32