mirror of
https://gerrit.wikimedia.org/r/mediawiki/extensions/Math
synced 2024-11-24 23:46:39 +00:00
8b8d91a771
This fixes some warnings in my PHPStorm, gets rid of duplicate code, inlines constants that do not make the code easier to read, and more. Change-Id: I02f446491509043f5d3e51e26e932f76c9ecb6cf
82 lines
2 KiB
PHP
82 lines
2 KiB
PHP
<?php
|
|
|
|
use DataValues\StringValue;
|
|
use ValueFormatters\Exceptions\MismatchingDataValueTypeException;
|
|
use ValueFormatters\ValueFormatter;
|
|
use Wikibase\Lib\SnakFormatter;
|
|
|
|
/*
|
|
* Formats the tex string based on the known formats
|
|
* * text/plain: used in the value input field of Wikidata
|
|
* * text/x-wiki: wikitext
|
|
* * text/html: used in Wikidata to display the value of properties
|
|
* Formats can look like this: "text/html; disposition=widget"
|
|
* or just "text/plain"
|
|
*/
|
|
|
|
class MathFormatter implements ValueFormatter {
|
|
|
|
/**
|
|
* @var string One of the SnakFormatter::FORMAT_... constants.
|
|
*/
|
|
private $format;
|
|
|
|
/**
|
|
* Loads format to distinguish the type of formatting
|
|
*
|
|
* @param string $format One of the SnakFormatter::FORMAT_... constants.
|
|
*
|
|
* @throws InvalidArgumentException
|
|
*/
|
|
public function __construct( $format ) {
|
|
switch ( $format ) {
|
|
case SnakFormatter::FORMAT_PLAIN:
|
|
case SnakFormatter::FORMAT_WIKI:
|
|
case SnakFormatter::FORMAT_HTML:
|
|
case SnakFormatter::FORMAT_HTML_DIFF:
|
|
case SnakFormatter::FORMAT_HTML_WIDGET:
|
|
$this->format = $format;
|
|
break;
|
|
default:
|
|
throw new InvalidArgumentException( 'Unsupported output format: ' . $format );
|
|
}
|
|
}
|
|
|
|
/**
|
|
* @param StringValue $value
|
|
*
|
|
* @throws MismatchingDataValueTypeException
|
|
* @return string
|
|
*/
|
|
public function format( $value ) {
|
|
if ( !( $value instanceof StringValue ) ) {
|
|
throw new MismatchingDataValueTypeException( 'StringValue', get_class( $value ) );
|
|
}
|
|
|
|
$tex = $value->getValue();
|
|
|
|
switch ( $this->format ) {
|
|
case SnakFormatter::FORMAT_PLAIN:
|
|
return $tex;
|
|
case SnakFormatter::FORMAT_WIKI:
|
|
return "<math>$tex</math>";
|
|
default:
|
|
$renderer = new MathMathML( $tex );
|
|
if ( $renderer->checkTex() && $renderer->render() ) {
|
|
return $renderer->getHtmlOutput();
|
|
}
|
|
|
|
// TeX string is not valid or rendering failed
|
|
return $renderer->getLastError();
|
|
}
|
|
}
|
|
|
|
/**
|
|
* @return string One of the SnakFormatter::FORMAT_... constants.
|
|
*/
|
|
public function getFormat() {
|
|
return $this->format;
|
|
}
|
|
|
|
}
|