| 1 |
<?php |
| 2 |
|
| 3 |
namespace MediaWiki\Extension\Math; |
| 4 |
|
| 5 |
use DataValues\StringValue; |
| 6 |
use InvalidArgumentException; |
| 7 |
use MediaWiki\Html\Html; |
| 8 |
use ValueFormatters\ValueFormatter; |
| 9 |
use Wikibase\Lib\Formatters\SnakFormatter; |
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
|
| 15 |
|
| 16 |
|
| 17 |
|
| 18 |
|
| 19 |
|
| 20 |
class MathFormatter implements ValueFormatter { |
| 21 |
|
| 22 |
|
| 23 |
|
| 24 |
|
| 25 |
private $format; |
| 26 |
|
| 27 |
|
| 28 |
|
| 29 |
|
| 30 |
|
| 31 |
|
| 32 |
public function __construct( $format ) { |
| 33 |
$this->format = $format; |
| 34 |
} |
| 35 |
|
| 36 |
|
| 37 |
|
| 38 |
|
| 39 |
|
| 40 |
|
| 41 |
|
| 42 |
public function format( $value ) { |
| 43 |
if ( !( $value instanceof StringValue ) ) { |
| 44 |
throw new InvalidArgumentException( '$value must be a StringValue' ); |
| 45 |
} |
| 46 |
|
| 47 |
$tex = $value->getValue(); |
| 48 |
|
| 49 |
switch ( $this->format ) { |
| 50 |
case SnakFormatter::FORMAT_PLAIN: |
| 51 |
return $tex; |
| 52 |
case SnakFormatter::FORMAT_WIKI: |
| 53 |
return "<math>$tex</math>"; |
| 54 |
|
| 55 |
|
| 56 |
default: |
| 57 |
$renderer = new MathMathML( $tex ); |
| 58 |
|
| 59 |
if ( $renderer->checkTeX() && $renderer->render() ) { |
| 60 |
$html = $renderer->getHtmlOutput(); |
| 61 |
} else { |
| 62 |
$html = $renderer->getLastError(); |
| 63 |
} |
| 64 |
|
| 65 |
if ( $this->format === SnakFormatter::FORMAT_HTML_DIFF ) { |
| 66 |
$html = $this->formatDetails( $html, $tex ); |
| 67 |
} |
| 68 |
|
| 69 |
return $html; |
| 70 |
} |
| 71 |
} |
| 72 |
|
| 73 |
|
| 74 |
|
| 75 |
|
| 76 |
|
| 77 |
|
| 78 |
|
| 79 |
|
| 80 |
|
| 81 |
private function formatDetails( $valueHtml, $tex ) { |
| 82 |
$html = Html::rawElement( 'h4', |
| 83 |
[ 'class' => 'wb-details wb-math-details wb-math-rendered' ], |
| 84 |
$valueHtml |
| 85 |
); |
| 86 |
|
| 87 |
$html .= Html::rawElement( 'div', |
| 88 |
[ 'class' => 'wb-details wb-math-details' ], |
| 89 |
Html::element( 'code', [], $tex ) |
| 90 |
); |
| 91 |
|
| 92 |
return $html; |
| 93 |
} |
| 94 |
|
| 95 |
|
| 96 |
|
| 97 |
|
| 98 |
public function getFormat() { |
| 99 |
return $this->format; |
| 100 |
} |
| 101 |
|
| 102 |
} |