Code Coverage |
||||||||||
Lines |
Functions and Methods |
Classes and Traits |
||||||||
Total | |
22.22% |
6 / 27 |
|
20.00% |
1 / 5 |
CRAP | |
0.00% |
0 / 1 |
WikitextGenerator | |
22.22% |
6 / 27 |
|
20.00% |
1 / 5 |
92.52 | |
0.00% |
0 / 1 |
__construct | |
0.00% |
0 / 3 |
|
0.00% |
0 / 1 |
6 | |||
getNextElement | |
0.00% |
0 / 16 |
|
0.00% |
0 / 1 |
56 | |||
toWikitext | |
100.00% |
6 / 6 |
|
100.00% |
1 / 1 |
2 | |||
getQId | |
0.00% |
0 / 1 |
|
0.00% |
0 / 1 |
2 | |||
getFormulae | |
0.00% |
0 / 1 |
|
0.00% |
0 / 1 |
2 |
1 | <?php |
2 | |
3 | namespace MediaWiki\Extension\MathSearch\StackExchange; |
4 | |
5 | use ArrayIterator; |
6 | use XMLReader; |
7 | |
8 | class WikitextGenerator { |
9 | |
10 | /** @var IdMap */ |
11 | private $idGen; |
12 | /** @var Formula[] */ |
13 | private $formulae = []; |
14 | |
15 | /** |
16 | * @param IdMap|null $idGen |
17 | */ |
18 | public function __construct( IdMap $idGen = null ) { |
19 | if ( $idGen === null ) { |
20 | $idGen = IdMap::getInstance(); |
21 | } |
22 | $this->idGen = $idGen; |
23 | } |
24 | |
25 | public function getNextElement( XMLReader $xml, $postQId ): string { |
26 | if ( $xml->nodeType == XMLReader::ELEMENT ) { |
27 | if ( $xml->name === 'a' ) { |
28 | $href = $xml->getAttribute( 'href' ); |
29 | if ( $href ) { |
30 | $xml->read(); |
31 | if ( preg_match( '#http://en\.wikipedia\.org/wiki/(.*)#', $href, $matches ) ) { |
32 | return "[[w:{$matches[1]}|$xml->value]]"; |
33 | } else { |
34 | return "[$href $xml->value]"; |
35 | } |
36 | } |
37 | } |
38 | if ( $xml->name === 'span' && $xml->getAttribute( 'class' ) === 'math-container' ) { |
39 | $fid = (int)$xml->getAttribute( 'id' ); |
40 | $qid = $this->getQId( $fid ); |
41 | $xml->read(); |
42 | $tagText = $xml->value; |
43 | $this->formulae[] = new Formula( $fid, $qid, $tagText, $postQId ); |
44 | return "<math id='$fid' qid='$qid'>$tagText</math>"; |
45 | } |
46 | } |
47 | |
48 | return $xml->value; |
49 | } |
50 | |
51 | public function toWikitext( $html, $postQId = null ) { |
52 | $xml = new XMLReader(); |
53 | $xml->XML( "<text>$html</text>" ); |
54 | $out = ""; |
55 | while ( $xml->read() ) { |
56 | $out .= $this->getNextElement( $xml, $postQId ); |
57 | } |
58 | return $out; |
59 | } |
60 | |
61 | private function getQId( int $fid ) { |
62 | return $this->idGen->addQid( $fid, 0 ); |
63 | } |
64 | |
65 | /** |
66 | * @return ArrayIterator|Formula[] |
67 | */ |
68 | public function getFormulae() { |
69 | return new ArrayIterator( $this->formulae ); |
70 | } |
71 | |
72 | } |