| 1 |
<?php |
| 2 |
|
| 3 |
namespace MediaWiki\Config; |
| 4 |
|
| 5 |
use InvalidArgumentException; |
| 6 |
use Wikimedia\Assert\Assert; |
| 7 |
use function array_key_exists; |
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
|
| 15 |
|
| 16 |
|
| 17 |
|
| 18 |
|
| 19 |
|
| 20 |
|
| 21 |
|
| 22 |
|
| 23 |
|
| 24 |
|
| 25 |
|
| 26 |
|
| 27 |
class ServiceOptions { |
| 28 |
|
| 29 |
private $keys; |
| 30 |
|
| 31 |
private $options = []; |
| 32 |
|
| 33 |
|
| 34 |
|
| 35 |
|
| 36 |
|
| 37 |
|
| 38 |
|
| 39 |
|
| 40 |
|
| 41 |
|
| 42 |
public function __construct( array $keys, ...$sources ) { |
| 43 |
$this->keys = $keys; |
| 44 |
foreach ( $keys as $key ) { |
| 45 |
foreach ( $sources as $source ) { |
| 46 |
if ( $source instanceof Config ) { |
| 47 |
if ( $source->has( $key ) ) { |
| 48 |
$this->options[$key] = $source->get( $key ); |
| 49 |
continue 2; |
| 50 |
} |
| 51 |
} elseif ( $source instanceof ServiceOptions ) { |
| 52 |
if ( array_key_exists( $key, $source->options ) ) { |
| 53 |
$this->options[$key] = $source->get( $key ); |
| 54 |
continue 2; |
| 55 |
} |
| 56 |
} elseif ( array_key_exists( $key, $source ) ) { |
| 57 |
$this->options[$key] = $source[$key]; |
| 58 |
continue 2; |
| 59 |
} |
| 60 |
} |
| 61 |
throw new InvalidArgumentException( "Key \"$key\" not found in input sources" ); |
| 62 |
} |
| 63 |
} |
| 64 |
|
| 65 |
|
| 66 |
|
| 67 |
|
| 68 |
|
| 69 |
|
| 70 |
|
| 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 |
|
| 89 |
|
| 90 |
|
| 91 |
|
| 92 |
|
| 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 |
} |