aboutsummaryrefslogtreecommitdiffstats
path: root/includes/Settings/Source/Format
diff options
context:
space:
mode:
Diffstat (limited to 'includes/Settings/Source/Format')
-rw-r--r--includes/Settings/Source/Format/JsonFormat.php57
-rw-r--r--includes/Settings/Source/Format/SettingsFormat.php35
2 files changed, 92 insertions, 0 deletions
diff --git a/includes/Settings/Source/Format/JsonFormat.php b/includes/Settings/Source/Format/JsonFormat.php
new file mode 100644
index 000000000000..1151ab93a2cb
--- /dev/null
+++ b/includes/Settings/Source/Format/JsonFormat.php
@@ -0,0 +1,57 @@
+<?php
+
+namespace MediaWiki\Settings\Source\Format;
+
+use UnexpectedValueException;
+
+/**
+ * Decodes settings data from JSON.
+ */
+class JsonFormat implements SettingsFormat {
+
+ /**
+ * Decodes JSON.
+ *
+ * @param string $data JSON string to decode.
+ *
+ * @return array
+ * @throws UnexpectedValueException
+ */
+ public function decode( string $data ): array {
+ $settings = json_decode( $data, true );
+
+ if ( $settings === null ) {
+ throw new UnexpectedValueException(
+ 'Failed to decode JSON: ' . json_last_error_msg()
+ );
+ }
+
+ if ( !is_array( $settings ) ) {
+ throw new UnexpectedValueException(
+ 'Decoded settings must be an array'
+ );
+ }
+
+ return $settings;
+ }
+
+ /**
+ * Returns true for the file extension 'json'. Case insensitive.
+ *
+ * @param string $ext File extension.
+ *
+ * @return bool
+ */
+ public function supportsFileExtension( string $ext ): bool {
+ return strtolower( $ext ) == 'json';
+ }
+
+ /**
+ * Returns the name/type of this format (JSON).
+ *
+ * @return string
+ */
+ public function __toString(): string {
+ return 'JSON';
+ }
+}
diff --git a/includes/Settings/Source/Format/SettingsFormat.php b/includes/Settings/Source/Format/SettingsFormat.php
new file mode 100644
index 000000000000..943faa88d544
--- /dev/null
+++ b/includes/Settings/Source/Format/SettingsFormat.php
@@ -0,0 +1,35 @@
+<?php
+
+namespace MediaWiki\Settings\Source\Format;
+
+use Stringable;
+use UnexpectedValueException;
+
+/**
+ * A SettingsFormat is meant to detect supported file types and/or decode
+ * source contents into settings arrays.
+ *
+ * @since 1.38
+ * @todo mark as stable before the 1.38 release
+ */
+interface SettingsFormat extends Stringable {
+ /**
+ * Decodes the given settings data and returns an associative array.
+ *
+ * @param string $data Settings data.
+ *
+ * @return array
+ * @throws UnexpectedValueException
+ */
+ public function decode( string $data ): array;
+
+ /**
+ * Whether or not the format claims to support a file with the given
+ * extension.
+ *
+ * @param string $ext File extension.
+ *
+ * @return bool
+ */
+ public function supportsFileExtension( string $ext ): bool;
+}