MediaWiki  master
ServiceOptions.php
Go to the documentation of this file.
1 <?php
2 
3 namespace MediaWiki\Config;
4 
5 use Config;
6 use InvalidArgumentException;
7 use Wikimedia\Assert\Assert;
8 
28  private $keys;
29  private $options = [];
30 
40  public function __construct( array $keys, ...$sources ) {
41  $this->keys = $keys;
42  foreach ( $keys as $key ) {
43  foreach ( $sources as $source ) {
44  if ( $source instanceof Config ) {
45  if ( $source->has( $key ) ) {
46  $this->options[$key] = $source->get( $key );
47  continue 2;
48  }
49  } elseif ( $source instanceof ServiceOptions ) {
50  if ( array_key_exists( $key, $source->options ) ) {
51  $this->options[$key] = $source->get( $key );
52  continue 2;
53  }
54  } else {
55  if ( array_key_exists( $key, $source ) ) {
56  $this->options[$key] = $source[$key];
57  continue 2;
58  }
59  }
60  }
61  throw new InvalidArgumentException( "Key \"$key\" not found in input sources" );
62  }
63  }
64 
71  public function assertRequiredOptions( array $expectedKeys ) {
72  if ( $this->keys !== $expectedKeys ) {
73  $extraKeys = array_diff( $this->keys, $expectedKeys );
74  $missingKeys = array_diff( $expectedKeys, $this->keys );
75  Assert::precondition( !$extraKeys && !$missingKeys,
76  (
77  $extraKeys
78  ? 'Unsupported options passed: ' . implode( ', ', $extraKeys ) . '!'
79  : ''
80  ) . ( $extraKeys && $missingKeys ? ' ' : '' ) . (
81  $missingKeys
82  ? 'Required options missing: ' . implode( ', ', $missingKeys ) . '!'
83  : ''
84  )
85  );
86  }
87  }
88 
93  public function get( $key ) {
94  if ( !array_key_exists( $key, $this->options ) ) {
95  throw new InvalidArgumentException( "Unrecognized option \"$key\"" );
96  }
97  return $this->options[$key];
98  }
99 }
A class for passing options to services.
__construct(array $keys,... $sources)
assertRequiredOptions(array $expectedKeys)
Assert that the list of options provided in this instance exactly match $expectedKeys,...
Interface for configuration instances.
Definition: Config.php:30
$source