Translate extension for MediaWiki
 
Loading...
Searching...
No Matches
MessageBundleTranslationLoader.php
1<?php
2declare( strict_types = 1 );
3
4namespace MediaWiki\Extension\Translate\MessageBundleTranslation;
5
8use MediaWiki\Language\LanguageFallback;
9use RuntimeException;
10
12
13 public function __construct(
14 private readonly LanguageFallback $languageFallback,
15 ) {
16 }
17
25 public function get(
26 MessageBundle $messageBundle,
27 string $languageCode,
28 bool $skipFallbacks
29 ): array {
30 $translations = $this->getTranslationsWithFallback( $messageBundle, $languageCode, $skipFallbacks );
31 $normalizedTranslations = [];
32 $prefixToReplace = '/^' . preg_quote( $messageBundle->getTitle()->getPrefixedDBkey() . '/', '/' ) . '/';
33 foreach ( $translations as $key => $translation ) {
34 $normalizedTranslations[
35 preg_replace( $prefixToReplace, '', $key )
36 ] = $translation;
37 }
38
39 return $normalizedTranslations;
40 }
41
42 private function getTranslationsWithFallback(
43 MessageBundle $messageBundle,
44 string $languageCode,
45 bool $skipFallbacks
46 ): array {
47 $messageBundleGroup = MessageGroups::getGroup( $messageBundle->getMessageGroupId() );
48 if ( !$messageBundleGroup ) {
49 throw new RuntimeException(
50 "Did not find message group for message bundle: {$messageBundle->getTitle()->getPrefixedText()}"
51 );
52 }
53
54 if ( $skipFallbacks ) {
55 $fallbackChain = [ $languageCode ];
56 } else {
57 $fallbackChain = [
58 $languageCode,
59 ...$this->languageFallback->getAll( $languageCode ),
60 $messageBundleGroup->getSourceLanguage()
61 ];
62 }
63
64 $collection = $messageBundleGroup->initCollection( $fallbackChain[0] );
65 $translations = [];
66
67 foreach ( $fallbackChain as $fallbackLanguageCode ) {
68 $collection->resetForNewLanguage( $fallbackLanguageCode );
69 // TODO use custom tag after fixing MessageCollection::filter
70 $collection->setTags( 'ignored', array_keys( $translations ) );
71 $collection->filter( MessageCollection::FILTER_IGNORED, MessageCollection::EXCLUDE_MATCHING );
72 if ( count( $collection ) === 0 ) {
73 break;
74 }
75
76 $collection->loadTranslations();
77 $collection->filter( MessageCollection::FILTER_HAS_TRANSLATION, MessageCollection::INCLUDE_MATCHING );
78 foreach ( $collection as $key => $message ) {
79 if ( $message->translation() !== null ) {
80 $translations[ $key ] = $message->translation();
81 }
82 }
83 }
84
85 return $translations;
86 }
87}
Factory class for accessing message groups individually by id or all of them as a list.
This file contains the class for core message collections implementation.