summaryrefslogtreecommitdiff
path: root/www/wiki/extensions/Scribunto/includes/engines/LuaCommon/MessageLibrary.php
blob: 4d9edbd32316b6c256fe0f89eea69a7e4a7e3e37 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
<?php

// @codingStandardsIgnoreLine Squiz.Classes.ValidClassName.NotCamelCaps
class Scribunto_LuaMessageLibrary extends Scribunto_LuaLibraryBase {
	function register() {
		$lib = [
			'plain' => [ $this, 'messagePlain' ],
			'check' => [ $this, 'messageCheck' ],
		];

		// Get the correct default language from the parser
		if ( $this->getParser() ) {
			$lang = $this->getParser()->getTargetLanguage();
		} else {
			global $wgContLang;
			$lang = $wgContLang;
		}

		return $this->getEngine()->registerInterface( 'mw.message.lua', $lib, [
			'lang' => $lang->getCode(),
		] );
	}

	private function makeMessage( $data, $setParams ) {
		if ( isset( $data['rawMessage'] ) ) {
			$msg = new RawMessage( $data['rawMessage'] );
		} else {
			$msg = Message::newFallbackSequence( $data['keys'] );
		}
		$msg->inLanguage( $data['lang'] )
			->useDatabase( $data['useDB'] );
		if ( $setParams ) {
			$msg->params( array_values( $data['params'] ) );
		}
		return $msg;
	}

	function messagePlain( $data ) {
		try {
			$msg = $this->makeMessage( $data, true );
			return [ $msg->plain() ];
		} catch ( MWException $ex ) {
			throw new Scribunto_LuaError( "msg:plain() failed (" . $ex->getMessage() . ")" );
		}
	}

	function messageCheck( $what, $data ) {
		if ( !in_array( $what, [ 'exists', 'isBlank', 'isDisabled' ] ) ) {
			throw new Scribunto_LuaError( "invalid what for 'messageCheck'" );
		}

		try {
			$msg = $this->makeMessage( $data, false );
			return [ call_user_func( [ $msg, $what ] ) ];
		} catch ( MWException $ex ) {
			throw new Scribunto_LuaError( "msg:$what() failed (" . $ex->getMessage() . ")" );
		}
	}
}