wiki.techinc.nl/includes/Settings/Source/ReflectionSchemaSource.php
daniel f2df03704e Add support for nested property schemas in MainConfigSchema.
This adds support for JSONSchema style property declarations with nested
schemas. This is a step towards using more nested structured for
configuration, rather than adding to the over 700 keys already defined
in the main config schema.

Defaults from property schemas are aggregated into a default value in
the top level schema. Descriptions are however not yet aggregated.

Change-Id: Iaf46a9ecc83bee3566098c56137a1be66bff2ab9
2022-06-29 16:34:43 +10:00

100 lines
1.9 KiB
PHP

<?php
namespace MediaWiki\Settings\Source;
use MediaWiki\Settings\SettingsBuilderException;
use ReflectionClass;
use ReflectionException;
/**
* Constructs a settings array based on a PHP class by inspecting class
* members to construct a schema.
*
* @since 1.39
*/
class ReflectionSchemaSource implements SettingsSource {
use JsonSchemaTrait;
/**
* Name of a PHP class
* @var string
*/
private $class;
/**
* @var bool
*/
private $includeDoc;
/**
* @param string $class
* @param bool $includeDoc
*/
public function __construct( string $class, bool $includeDoc = false ) {
$this->class = $class;
$this->includeDoc = $includeDoc;
}
/**
* @throws SettingsBuilderException
* @return array
*/
public function load(): array {
$schemas = [];
try {
$class = new ReflectionClass( $this->class );
foreach ( $class->getReflectionConstants() as $const ) {
if ( !$const->isPublic() ) {
continue;
}
$name = $const->getName();
$schema = $const->getValue();
if ( !is_array( $schema ) ) {
continue;
}
if ( $this->includeDoc ) {
$doc = $const->getDocComment();
if ( $doc ) {
$schema['description'] = $this->normalizeComment( $doc );
}
}
$schema = self::normalizeJsonSchema( $schema );
$schemas[ $name ] = $schema;
}
} catch ( ReflectionException $e ) {
throw new SettingsBuilderException(
'Failed to load schema from class {class}',
[ 'class' => $this->class ],
0,
$e
);
}
return [
'config-schema' => $schemas
];
}
/**
* Returns this file source as a string.
*
* @return string
*/
public function __toString(): string {
return 'class ' . $this->class;
}
private function normalizeComment( string $doc ) {
$doc = preg_replace( '/^\s*\/\*+\s*|\s*\*+\/\s*$/s', '', $doc );
$doc = preg_replace( '/^\s*\**$/m', " ", $doc );
$doc = preg_replace( '/^\s*\**[ \t]?/m', '', $doc );
return $doc;
}
}