| 1 |
<?php |
| 2 |
|
| 3 |
namespace MediaWiki\Extension\Poem; |
| 4 |
|
| 5 |
use MediaWiki\Hook\ParserFirstCallInitHook; |
| 6 |
use MediaWiki\Html\Html; |
| 7 |
use MediaWiki\Parser\Parser; |
| 8 |
use MediaWiki\Parser\PPFrame; |
| 9 |
use MediaWiki\Parser\Sanitizer; |
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
|
| 15 |
|
| 16 |
|
| 17 |
|
| 18 |
class Poem implements ParserFirstCallInitHook { |
| 19 |
|
| 20 |
|
| 21 |
|
| 22 |
|
| 23 |
public function onParserFirstCallInit( $parser ) { |
| 24 |
$parser->setHook( 'poem', [ $this, 'renderPoem' ] ); |
| 25 |
} |
| 26 |
|
| 27 |
|
| 28 |
|
| 29 |
|
| 30 |
|
| 31 |
|
| 32 |
|
| 33 |
|
| 34 |
|
| 35 |
public function renderPoem( $in, array $param, Parser $parser, PPFrame $frame ) { |
| 36 |
|
| 37 |
|
| 38 |
$newline = isset( $param['compact'] ) ? '' : "\n"; |
| 39 |
|
| 40 |
$tag = $parser->insertStripItem( "<br />" ); |
| 41 |
|
| 42 |
|
| 43 |
$text = preg_replace_callback( |
| 44 |
'/^(:++)(.+)$/m', |
| 45 |
static function ( array $matches ) { |
| 46 |
$indentation = strlen( $matches[1] ) . 'em'; |
| 47 |
return Html::rawElement( |
| 48 |
'span', |
| 49 |
[ |
| 50 |
'class' => 'mw-poem-indented', |
| 51 |
'style' => 'display: inline-block; ' . |
| 52 |
"margin-inline-start: $indentation;", |
| 53 |
], |
| 54 |
$matches[2] |
| 55 |
); |
| 56 |
}, |
| 57 |
$in ?? '' |
| 58 |
); |
| 59 |
|
| 60 |
|
| 61 |
|
| 62 |
|
| 63 |
$text = preg_replace( |
| 64 |
[ '/^\n/', '/\n$/D', '/(?<!^----)\n/m' ], |
| 65 |
[ "", "", "$tag\n" ], |
| 66 |
$text |
| 67 |
); |
| 68 |
|
| 69 |
|
| 70 |
$text = preg_replace_callback( |
| 71 |
'/^ +/m', |
| 72 |
static function ( array $matches ) { |
| 73 |
return str_repeat( ' ', strlen( $matches[0] ) ); |
| 74 |
}, |
| 75 |
$text |
| 76 |
); |
| 77 |
|
| 78 |
$text = $parser->recursiveTagParse( $text, $frame ); |
| 79 |
|
| 80 |
|
| 81 |
|
| 82 |
$text = str_replace( '<hr />' . $tag, '<hr />', $text ); |
| 83 |
|
| 84 |
$attribs = Sanitizer::validateTagAttributes( $param, 'div' ); |
| 85 |
|
| 86 |
|
| 87 |
if ( isset( $attribs['class'] ) ) { |
| 88 |
$attribs['class'] = 'poem ' . $attribs['class']; |
| 89 |
} else { |
| 90 |
$attribs['class'] = 'poem'; |
| 91 |
} |
| 92 |
|
| 93 |
return Html::rawElement( 'div', $attribs, $newline . trim( $text ) . $newline ); |
| 94 |
} |
| 95 |
} |