MDL-78266 core: Simplify string treatment in core/templates

The old handling was extremely convoluted, and likely inefficient.

It's much clearer to use a regex with named groups and loop through in a
standard way.
This commit is contained in:
Andrew Nicols 2023-05-18 10:51:59 +08:00
parent 1ef815cd97
commit a438e2c72d
No known key found for this signature in database
GPG Key ID: 6D1E3157C8CFBF14
3 changed files with 18 additions and 49 deletions

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@ -476,57 +476,26 @@ export default class Renderer {
* @returns {String} The treated content.
*/
treatStringsInContent(content, strings) {
var pattern = /\[\[_(s|c)\d+\]\]/;
var treated;
var index;
var strIndex;
var walker;
var char;
var strFinal;
var isClean;
const stringPattern = /(?<placeholder>\[\[_(?<stringType>[cs])(?<stringIndex>\d+)\]\])/g;
let match;
while ((match = stringPattern.exec(content)) !== null) {
const isClean = match.groups.stringType === 'c';
let strFinal = strings[parseInt(match.groups.stringIndex)];
do {
treated = '';
index = content.search(pattern);
while (index > -1) {
// Copy the part prior to the placeholder to the treated string.
treated += content.substring(0, index);
content = content.substring(index);
isClean = content[3] == 'c';
strIndex = '';
walker = 4; // 4 is the length of either '[[_s' or '[[_c'.
// Walk the characters to manually extract the index of the string from the placeholder.
char = content.substring(walker, walker + 1);
do {
strIndex += char;
walker++;
char = content.substring(walker, walker + 1);
} while (char != ']');
// Get the string, add it to the treated result, and remove the placeholder from the content to treat.
strFinal = strings[parseInt(strIndex, 10)];
if (typeof strFinal === 'undefined') {
Log.debug('Could not find string for pattern [[_' + (isClean ? 'c' : 's') + strIndex + ']].');
strFinal = '';
}
if (isClean) {
strFinal = mustache.escape(strFinal);
}
treated += strFinal;
content = content.substring(6 + strIndex.length); // 6 is the length of the placeholder without the index.
// That's either '[[_s]]' or '[[_c]]'.
// Find the next placeholder.
index = content.search(pattern);
if (typeof strFinal === 'undefined') {
Log.debug(`Could not find string for pattern ${match.groups.placeholder}`);
strFinal = '';
}
if (isClean) {
strFinal = mustache.escape(strFinal);
}
// The content becomes the treated part with the rest of the content.
content = treated + content;
let updatedContent = content.slice(0, match.index);
updatedContent += strFinal;
updatedContent += content.slice(match.index + match.groups.placeholder.length);
// Check if we need to walk the content again, in case strings contained placeholders.
index = content.search(pattern);
} while (index > -1);
content = updatedContent;
}
return content;
}