Debian Codegraph @

extensions/DiscussionTools/tests/phpunit/TestUtils.php

raw symbols SCIP
1 <?php
2
3 namespace MediaWiki\Extension\DiscussionTools\Tests;
4
5 use MediaWiki\Cache\GenderCache;
6 use MediaWiki\Config\HashConfig;
7 use MediaWiki\Config\MultiConfig;
8 use MediaWiki\Config\ServiceOptions;
9 use MediaWiki\Extension\DiscussionTools\CommentParser;
10 use MediaWiki\Interwiki\NullInterwikiLookup;
11 use MediaWiki\Json\FormatJson;
12 use MediaWiki\Languages\LanguageConverterFactory;
13 use MediaWiki\Languages\LanguageFactory;
14 use MediaWiki\MainConfigNames;
15 use MediaWiki\MediaWikiServices;
16 use MediaWiki\Title\MediaWikiTitleCodec;
17 use MediaWiki\Title\NamespaceInfo;
18 use MediaWiki\User\Options\StaticUserOptionsLookup;
19 use Wikimedia\Parsoid\DOM\Document;
20 use Wikimedia\Parsoid\DOM\Element;
21 use Wikimedia\Parsoid\Utils\DOMCompat;
22 use Wikimedia\Parsoid\Utils\DOMUtils;
23
24 trait TestUtils {
25
26 /**
27 * Create a Document from a string.
28 */
29 protected static function createDocument( string $html ): Document {
30 return DOMUtils::parseHTML( $html );
31 }
32
33 /**
34 * Return the node that is expected to contain thread items.
35 */
36 protected static function getThreadContainer( Document $doc ): Element {
37 // In tests created from Parsoid output, comments are contained directly in <body>.
38 // In tests created from old parser output, comments are contained in <div class="mw-parser-output">.
39 $body = DOMCompat::getBody( $doc );
40 $wrapper = DOMCompat::querySelector( $body, 'div.mw-parser-output' );
41 return $wrapper ?: $body;
42 }
43
44 /**
45 * Get text from path
46 */
47 protected static function getText( string $relativePath ): string {
48 return file_get_contents( __DIR__ . '/../' . $relativePath );
49 }
50
51 /**
52 * Write text to path
53 */
54 protected static function overwriteTextFile( string $relativePath, string $text ): void {
55 file_put_contents( __DIR__ . '/../' . $relativePath, $text );
56 }
57
58 /**
59 * Get parsed JSON from path
60 *
61 * @param string $relativePath
62 * @param bool $assoc See json_decode()
63 * @return array
64 */
65 protected static function getJson( string $relativePath, bool $assoc = true ): array {
66 $json = json_decode(
67 file_get_contents( __DIR__ . '/' . $relativePath ),
68 $assoc
69 );
70 return $json;
71 }
72
73 /**
74 * Write JSON to path
75 */
76 protected static function overwriteJsonFile( string $relativePath, array $data ): void {
77 $json = FormatJson::encode( $data, "\t", FormatJson::ALL_OK );
78 file_put_contents( __DIR__ . '/' . $relativePath, $json . "\n" );
79 }
80
81 /**
82 * Get HTML from path
83 */
84 protected static function getHtml( string $relativePath ): string {
85 return file_get_contents( __DIR__ . '/../' . $relativePath );
86 }
87
88 /**
89 * Write HTML to path
90 */
91 protected static function overwriteHtmlFile( string $relPath, Element $container, string $origRelPath ): void {
92 // Do not use $doc->saveHtml(), it outputs an awful soup of HTML entities for documents with
93 // non-ASCII characters
94 $html = file_get_contents( __DIR__ . '/../' . $origRelPath );
95
96 $newInnerHtml = DOMCompat::getInnerHTML( $container );
97
98 if ( strtolower( $container->tagName ) === 'body' ) {
99 // Apparently <body> innerHTML always has a trailing newline, even if the source HTML did not,
100 // and we need to preserve whatever whitespace was there to avoid test failures
101 preg_match( '`(\s*)(</body>|\z)`s', $html, $matches );
102 $newInnerHtml = rtrim( $newInnerHtml ) . $matches[1];
103 }
104
105 // Quote \ and $ in the replacement text
106 $quotedNewInnerHtml = strtr( $newInnerHtml, [ '\\' => '\\\\', '$' => '\\$' ] );
107
108 if ( strtolower( $container->tagName ) === 'body' ) {
109 if ( str_contains( $html, '<body' ) ) {
110 $html = preg_replace(
111 '`(<body[^>]*>)(.*)(</body>)`s',
112 '$1' . $quotedNewInnerHtml . '$3',
113 $html
114 );
115 } else {
116 $html = $newInnerHtml;
117 }
118 } else {
119 $html = preg_replace(
120 '`(<div class="mw-parser-output">)(.*)(</div>)`s',
121 '$1' . $quotedNewInnerHtml . '$3',
122 $html
123 );
124 }
125
126 file_put_contents( __DIR__ . '/../' . $relPath, $html );
127 }
128
129 private static function prepareConfig( array $config, array $data ): array {
130 return [
131 MainConfigNames::LanguageCode => $config['wgContentLanguage'],
132 MainConfigNames::ArticlePath => $config['wgArticlePath'],
133 // TODO: Move this to $config
134 MainConfigNames::Localtimezone => $data['localTimezone'],
135
136 // Defaults for NamespaceInfo
137 MainConfigNames::CanonicalNamespaceNames => NamespaceInfo::CANONICAL_NAMES,
138 MainConfigNames::CapitalLinkOverrides => [],
139 MainConfigNames::CapitalLinks => true,
140 MainConfigNames::ContentNamespaces => [ NS_MAIN ],
141 MainConfigNames::ExtraSignatureNamespaces => [],
142 MainConfigNames::NamespaceContentModels => [],
143 MainConfigNames::NamespacesWithSubpages => [
144 NS_TALK => true,
145 NS_USER => true,
146 NS_USER_TALK => true,
147 NS_PROJECT => true,
148 NS_PROJECT_TALK => true,
149 NS_FILE_TALK => true,
150 NS_MEDIAWIKI => true,
151 NS_MEDIAWIKI_TALK => true,
152 NS_TEMPLATE => true,
153 NS_TEMPLATE_TALK => true,
154 NS_HELP => true,
155 NS_HELP_TALK => true,
156 NS_CATEGORY_TALK => true
157 ],
158 MainConfigNames::NonincludableNamespaces => [],
159
160 // Defaults for LanguageFactory
161 MainConfigNames::DummyLanguageCodes => [],
162
163 // Defaults for LanguageConverterFactory
164 MainConfigNames::UsePigLatinVariant => false,
165 MainConfigNames::DisableLangConversion => false,
166 MainConfigNames::DisableTitleConversion => false,
167
168 // Defaults for Language
169 MainConfigNames::ExtraGenderNamespaces => [],
170
171 // Overrides
172 MainConfigNames::ExtraNamespaces => array_diff_key(
173 $config['wgFormattedNamespaces'], NamespaceInfo::CANONICAL_NAMES ),
174 MainConfigNames::MetaNamespace => strtr( $config['wgFormattedNamespaces'][NS_PROJECT], ' ', '_' ),
175 MainConfigNames::MetaNamespaceTalk => strtr( $config['wgFormattedNamespaces'][NS_PROJECT_TALK], ' ', '_' ),
176 MainConfigNames::NamespaceAliases => $config['wgNamespaceIds'],
177 ];
178 }
179
180 public function createParser( array $config, array $data ): CommentParser {
181 // TODO: Derive everything from $config and $data without using global services
182 $services = MediaWikiServices::getInstance();
183
184 $config = self::prepareConfig( $config, $data );
185
186 $langConvFactory = new LanguageConverterFactory(
187 new ServiceOptions( LanguageConverterFactory::CONSTRUCTOR_OPTIONS, $config ),
188 $services->getObjectFactory(),
189 static function () use ( $services ) {
190 return $services->getLanguageFactory()->getLanguage( $config['LanguageCode'] );
191 }
192 );
193
194 return new CommentParser(
195 new HashConfig( $config ),
196 $services->getLanguageFactory()->getLanguage( $config['LanguageCode'] ),
197 $langConvFactory,
198 new MockLanguageData( $data ),
199 $this->createTitleParser( $config )
200 );
201 }
202
203 public function createTitleParser( array $config ): MediaWikiTitleCodec {
204 // TODO: Derive everything from $config and $data without using global services
205 $services = MediaWikiServices::getInstance();
206
207 if ( isset( $config['wgArticlePath'] ) ) {
208 $config = self::prepareConfig( $config, [ 'localTimezone' => '' ] );
209 }
210
211 $nsInfo = new NamespaceInfo(
212 new ServiceOptions( NamespaceInfo::CONSTRUCTOR_OPTIONS, $config ),
213 $services->getHookContainer(),
214 [],
215 []
216 );
217
218 $langFactory = new LanguageFactory(
219 new ServiceOptions( LanguageFactory::CONSTRUCTOR_OPTIONS, $config ),
220 $nsInfo,
221 $services->getLocalisationCache(),
222 $services->getLanguageNameUtils(),
223 $services->getLanguageFallback(),
224 $services->getLanguageConverterFactory(),
225 $services->getHookContainer(),
226 new MultiConfig( [ new HashConfig( $config ), $services->getMainConfig() ] )
227 );
228
229 $contLang = $langFactory->getLanguage( $config['LanguageCode'] );
230
231 return new MediaWikiTitleCodec(
232 $contLang,
233 new GenderCache( $nsInfo, null, new StaticUserOptionsLookup( [] ) ),
234 [],
235 new NullInterwikiLookup(),
236 $nsInfo
237 );
238 }
239 }