| 1 | <?php |
| 2 | |
| 3 | use MediaWiki\Language\Language; |
| 4 | |
| 5 | /** |
| 6 | * Helping class to run tests using a clean language instance. |
| 7 | * |
| 8 | * This is intended for the MediaWiki language class tests under |
| 9 | * tests/phpunit/includes/languages. |
| 10 | * |
| 11 | * Before each tests, a new language object is built which you |
| 12 | * can retrieve in your test using the $this->getLang() method: |
| 13 | * |
| 14 | * @par Using the crafted language object: |
| 15 | * @code |
| 16 | * function testHasLanguageObject() { |
| 17 | * $langObject = $this->getLang(); |
| 18 | * $this->assertInstanceOf( 'LanguageFoo', |
| 19 | * $langObject |
| 20 | * ); |
| 21 | * } |
| 22 | * @endcode |
| 23 | */ |
| 24 | abstract class LanguageClassesTestCase extends MediaWikiIntegrationTestCase { |
| 25 | /** |
| 26 | * @var Language |
| 27 | * |
| 28 | * A new object is created before each tests thanks to PHPUnit |
| 29 | * setUp() method, it is deleted after each test too. To get |
| 30 | * this object you simply use the getLang method. |
| 31 | * |
| 32 | * You must have setup a language code first. See $LanguageClassCode |
| 33 | * @code |
| 34 | * function testWeAreTheChampions() { |
| 35 | * $this->getLang(); # language object |
| 36 | * } |
| 37 | * @endcode |
| 38 | */ |
| 39 | private $languageObject; |
| 40 | |
| 41 | /** |
| 42 | * @return Language |
| 43 | */ |
| 44 | protected function getLang() { |
| 45 | return $this->languageObject; |
| 46 | } |
| 47 | |
| 48 | /** |
| 49 | * Create a new language object before each test. |
| 50 | */ |
| 51 | protected function setUp(): void { |
| 52 | parent::setUp(); |
| 53 | $lang = false; |
| 54 | if ( preg_match( '/Language(.+)Test/', static::class, $m ) ) { |
| 55 | # Normalize language code since classes uses underscores |
| 56 | $lang = strtolower( str_replace( '_', '-', $m[1] ) ); |
| 57 | } |
| 58 | if ( $lang === false || |
| 59 | !$this->getServiceContainer()->getLanguageNameUtils()->isSupportedLanguage( $lang ) |
| 60 | ) { |
| 61 | # Fallback to english language |
| 62 | $lang = 'en'; |
| 63 | wfDebug( |
| 64 | __METHOD__ . ' could not extract a language name ' |
| 65 | . 'out of ' . static::class . ", falling back to 'en'" |
| 66 | ); |
| 67 | } |
| 68 | $this->languageObject = $this->getServiceContainer()->getLanguageFactory() |
| 69 | ->getLanguage( $lang ); |
| 70 | } |
| 71 | |
| 72 | /** |
| 73 | * Delete the internal language object so each test starts |
| 74 | * out with a fresh language instance. |
| 75 | */ |
| 76 | protected function tearDown(): void { |
| 77 | unset( $this->languageObject ); |
| 78 | parent::tearDown(); |
| 79 | } |
| 80 | } |