Debian Codegraph @

tests/phpunit/mocks/TestLocalisationCache.php

raw symbols SCIP
1 <?php
2
3 use MediaWiki\MainConfigNames;
4 use MediaWiki\MediaWikiServices;
5 use Wikimedia\TestingAccessWrapper;
6
7 /**
8 * A test-only LocalisationCache that caches all data in memory for test speed.
9 */
10 class TestLocalisationCache extends LocalisationCache {
11
12 /**
13 * A cache of the parsed data for tests. Services are reset between every test, which forces
14 * localization to be recached between every test, which is unreasonably slow. As an
15 * optimization, we cache our data in a static member for tests.
16 */
17 private static MapCacheLRU $testingCache;
18
19 private const PROPERTY_NAMES = [ 'data', 'sourceLanguage' ];
20
21 /** @var self */
22 private $selfAccess;
23
24 public function __construct( ...$params ) {
25 parent::__construct( ...$params );
26
27 // Limit the cache size (entries are approx. 1 MB each) but not too much. Critical for tests
28 // that use e.g. 5 different languages, and then the same 5 languages again, and again, …
29 self::$testingCache ??= new MapCacheLRU( 16 );
30 $this->selfAccess = TestingAccessWrapper::newFromObject( $this );
31 }
32
33 public function recache( $code ) {
34 $hookContainer = MediaWikiServices::getInstance()->getHookContainer();
35 // Test run performance is killed if we have to regenerate l10n for every test
36 $cacheKey = sha1( json_encode( [
37 $code,
38 $this->selfAccess->options->get( MainConfigNames::ExtensionMessagesFiles ),
39 $this->selfAccess->options->get( MainConfigNames::MessagesDirs ),
40 $hookContainer->getHandlerDescriptions( 'LocalisationCacheRecacheFallback' ),
41 $hookContainer->getHandlerDescriptions( 'LocalisationCacheRecache' ),
42 ] ) );
43 $cache = self::$testingCache->get( $cacheKey );
44 if ( $cache ) {
45 foreach ( self::PROPERTY_NAMES as $prop ) {
46 $this->$prop[$code] = $cache[$prop];
47 }
48 $loadedItems = $this->selfAccess->loadedItems;
49 foreach ( $cache['data'] as $key => $_ ) {
50 $loadedItems[$code][$key] = true;
51 }
52 $this->selfAccess->loadedItems = $loadedItems;
53 return;
54 }
55
56 parent::recache( $code );
57
58 $cache = [];
59 foreach ( self::PROPERTY_NAMES as $prop ) {
60 $cache[$prop] = $this->$prop[$code];
61 }
62 self::$testingCache->set( $cacheKey, $cache );
63 }
64 }