-
Notifications
You must be signed in to change notification settings - Fork 0
/
translations-cache.php
193 lines (161 loc) · 7.01 KB
/
translations-cache.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
<?php // phpcs:disable PSR1.Files.SideEffects.FoundWithSymbols
/**
* Plugin Name: Translations Cache
* Plugin URI: https://github.com/wearerequired/translations-cache
* Description: Reduces file reads for translations by caching the first read via APCu.
* Version: 2.0.0
* Requires at least: 6.3
* Requires PHP: 8.0
* Author: required
* Author URI: https://required.com/
* License: GPL v2 or later
* License URI: http://www.gnu.org/licenses/gpl-2.0.txt
* Update URI: false
*/
declare( strict_types=1 );
namespace Required\TranslationsCache;
// Default cache expiration time in seconds.
// Note: There's currently no cache invalidation but you can set the
// `TRANSLATIONS_CACHE_KEY_SALT` environment variable to invalidate the cache.
const DEFAULT_EXPIRE = 6 * HOUR_IN_SECONDS;
/**
* Adds the APCu PHP module to the list of required modules.
*
* @param array<string,mixed> $modules An associative array of modules to test for.
* @return array<string,mixed> An associative array of modules to test for.
*/
function site_status_test_apcu_php_module( array $modules ): array {
$modules['apcu'] = [
'extension' => 'apcu',
'function' => 'apcu_enabled',
'required' => true,
];
return $modules;
}
add_filter( 'site_status_test_php_modules', __NAMESPACE__ . '\site_status_test_apcu_php_module' );
// Bail early if APCu is not available.
if ( ! \function_exists( 'apcu_enabled' ) || ! apcu_enabled() ) {
return;
}
/**
* Caches reading JSON translation files.
*
* @param string|false|null $translations JSON-encoded translation data. Default null.
* @param string|false $file Path to the translation file to load. False if there isn't one.
* @param string $handle Name of the script to register a translation domain to.
* @param string $domain The text domain.
* @return string|false The JSON-encoded translated strings for the given script handle and text domain.
* False if there are none.
*/
function load_script_translations( $translations, $file, string $handle, string $domain ) { // phpcs:ignore SlevomatCodingStandard.TypeHints
// Another plugin has already overridden the translations.
if ( null !== $translations ) {
return $translations;
}
$locale = determine_locale();
$cache_key_salt = getenv( 'TRANSLATIONS_CACHE_KEY_SALT' ) ?: '';
$cache_key = 'load_script_translations:' . md5( $cache_key_salt . $locale . $file . $handle . $domain );
$found = false;
$translations = cache_fetch( $cache_key, $found );
if ( ! $found ) {
// Call the core function to load the translations without the pre-filter.
remove_filter( 'pre_load_script_translations', __NAMESPACE__ . '\load_script_translations', 9999 );
$translations = \load_script_translations( $file, $handle, $domain );
add_filter( 'pre_load_script_translations', __NAMESPACE__ . '\load_script_translations', 9999, 4 );
// Cache the result.
cache_add( $cache_key, $translations, false === $translations ? HOUR_IN_SECONDS : DEFAULT_EXPIRE );
}
return $translations;
}
add_filter( 'pre_load_script_translations', __NAMESPACE__ . '\load_script_translations', 9999, 4 );
/**
* Caches reading gettext translation files.
*
* @param bool|null $loaded The result of loading a .mo file. Default null.
* @param string $domain Text domain. Unique identifier for retrieving translated strings.
* @param string $mofile Path to the MO file.
* @param string|null $locale Locale.
* @return bool True if the .mo file was loaded, false otherwise.
*/
function load_textdomain( ?bool $loaded, string $domain, string $mofile, ?string $locale = null ): bool {
// Another plugin has already overridden the loading.
if ( null !== $loaded ) {
return $loaded;
}
/** @var \WP_Textdomain_Registry $wp_textdomain_registry */
global $l10n, $wp_textdomain_registry;
if ( ! $locale ) {
$locale = determine_locale();
}
$cache_key_salt = getenv( 'TRANSLATIONS_CACHE_KEY_SALT' ) ?: '';
$cache_key = 'load_textdomain:' . md5( $cache_key_salt . $locale . $domain . $mofile );
$found = false;
$data = cache_fetch( $cache_key, $found );
if ( ! $found ) {
// Allow plugins to change the .mo file.
$mofile = apply_filters( 'load_textdomain_mofile', $mofile, $domain ); // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals -- Core filter.
if ( ! is_readable( $mofile ) ) {
cache_add( $cache_key, false, DEFAULT_EXPIRE );
// Return false so the default fallback loading can apply.
return false;
}
$mo = new \MO();
if ( ! $mo->import_from_file( $mofile ) ) {
$wp_textdomain_registry->set( $domain, $locale, false );
// Use a short cache time to avoid repeated failed lookups.
cache_add( $cache_key, false, HOUR_IN_SECONDS );
return true;
}
$wp_textdomain_registry->set( $domain, $locale, \dirname( $mofile ) );
// Cache the translations.
$data = [
'entries' => $mo->entries,
'headers' => $mo->headers,
];
cache_add( $cache_key, $data, DEFAULT_EXPIRE );
if ( isset( $l10n[ $domain ] ) ) {
$mo->merge_with( $l10n[ $domain ] );
}
$l10n[ $domain ] = &$mo; // phpcs:ignore WordPress.WP.GlobalVariablesOverride.Prohibited
} elseif ( \is_array( $data ) ) { // false if a mo file was not read/found.
$mo = new \MO();
$mo->entries = $data['entries'];
$mo->headers = $data['headers'];
if ( isset( $l10n[ $domain ] ) ) {
$mo->merge_with( $l10n[ $domain ] );
}
$l10n[ $domain ] = &$mo; // phpcs:ignore WordPress.WP.GlobalVariablesOverride.Prohibited
} elseif ( false === $data ) {
// Return false so the default fallback loading can apply.
return false;
}
return true;
}
add_filter( 'pre_load_textdomain', __NAMESPACE__ . '\load_textdomain', 9999, 4 );
/**
* Caches data to APCu, only if it's not already stored.
*
* @param string $key The cache key to use for retrieval later.
* @param mixed $data The contents to store in the cache.
* @param int $expire Optional. When to expire the cache contents, in seconds.
* Default 0 (no expiration).
* @return bool|array<string,mixed> Returns true if something has effectively been added into the cache,
* false otherwise. Second syntax returns array with error keys.
*/
function cache_add( string $key, mixed $data, int $expire = 0 ): bool|array {
// Alter provided expire values to be within -10%/+20% of the provided time,
// to spread expires over a wider window.
$expire = rand( \intval( $expire * 0.9 ), \intval( $expire * 1.2 ) ); // phpcs:ignore WordPress.WP.AlternativeFunctions.rand_rand
return apcu_add( $key, $data, $expire );
}
/**
* Retrieves the cache contents from APCu by key.
*
* @param string $key The key under which the cache contents are stored.
* @param bool|null $found Optional. Whether the key was found in the cache (passed by reference).
* Disambiguates a return of false, a storable value. Default null.
* @return mixed The stored variable or array of variables on success; false on failure.
*/
function cache_fetch( string $key, ?bool &$found = null ): mixed {
return apcu_fetch( $key, $found );
}