| 1 |
<?php |
| 2 |
|
| 3 |
namespace MediaWiki\OutputTransform\Stages; |
| 4 |
|
| 5 |
use MediaWiki\Config\ServiceOptions; |
| 6 |
use MediaWiki\Html\Html; |
| 7 |
use MediaWiki\Language\Language; |
| 8 |
use MediaWiki\Languages\LanguageFactory; |
| 9 |
use MediaWiki\OutputTransform\ContentTextTransformStage; |
| 10 |
use MediaWiki\Parser\ParserOptions; |
| 11 |
use MediaWiki\Parser\ParserOutput; |
| 12 |
use Psr\Log\LoggerInterface; |
| 13 |
|
| 14 |
|
| 15 |
|
| 16 |
|
| 17 |
|
| 18 |
class AddWrapperDivClass extends ContentTextTransformStage { |
| 19 |
|
| 20 |
private LanguageFactory $langFactory; |
| 21 |
private Language $contentLang; |
| 22 |
|
| 23 |
public function __construct( |
| 24 |
ServiceOptions $options, LoggerInterface $logger, LanguageFactory $langFactory, |
| 25 |
Language $contentLang |
| 26 |
) { |
| 27 |
parent::__construct( $options, $logger ); |
| 28 |
$this->langFactory = $langFactory; |
| 29 |
$this->contentLang = $contentLang; |
| 30 |
} |
| 31 |
|
| 32 |
public function shouldRun( ParserOutput $po, ?ParserOptions $popts, array $options = [] ): bool { |
| 33 |
return ( $options['wrapperDivClass'] ?? $po->getWrapperDivClass() ) !== '' && !( $options['unwrap'] ?? false ); |
| 34 |
} |
| 35 |
|
| 36 |
protected function transformText( string $text, ParserOutput $po, ?ParserOptions $popts, array &$options ): string { |
| 37 |
$wrapperDivClass = $options['wrapperDivClass'] ?? $po->getWrapperDivClass(); |
| 38 |
$pageLang = $this->getLanguageWithFallbackGuess( $po ); |
| 39 |
$extraAttrs = []; |
| 40 |
$parsoidVersion = $po->getExtensionData( 'core:parsoid-version' ); |
| 41 |
$htmlVersion = $po->getExtensionData( 'core:html-version' ); |
| 42 |
if ( $parsoidVersion !== null ) { |
| 43 |
$extraAttrs['data-mw-parsoid-version'] = $parsoidVersion; |
| 44 |
} |
| 45 |
if ( $htmlVersion !== null ) { |
| 46 |
$extraAttrs['data-mw-html-version'] = $htmlVersion; |
| 47 |
} |
| 48 |
return Html::rawElement( 'div', [ |
| 49 |
'class' => 'mw-content-' . $pageLang->getDir() . ' ' . $wrapperDivClass, |
| 50 |
'lang' => $pageLang->toBcp47Code(), |
| 51 |
'dir' => $pageLang->getDir(), |
| 52 |
] + $extraAttrs, $text ); |
| 53 |
} |
| 54 |
|
| 55 |
private function getLanguageWithFallbackGuess( ParserOutput $po ): Language { |
| 56 |
$pageLang = $po->getLanguage(); |
| 57 |
if ( $pageLang ) { |
| 58 |
return $this->langFactory->getLanguage( $pageLang ); |
| 59 |
} |
| 60 |
return $this->contentLang; |
| 61 |
} |
| 62 |
} |