-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathtranslator.php
67 lines (63 loc) · 2.11 KB
/
translator.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
<?php
/**
* Hook fired as a filter for the "mock" translation api
*
* @param string[] input strings
* @param Loco_Locale target locale for translations
* @param array our own api configuration
* @return string[] output strings
*/
function mock_translator_process_batch( array $sources, Loco_Locale $Locale, array $config ){
$targets = array();
foreach( $sources as $i => $source ){
$targets[$i] = mock_translator_translate_text($source);
}
return $targets;
}
/**
* @param string
* @return string
*/
function mock_translator_translate_text( $source ){
$target = '';
while( is_string($source) && '' !== $source ){
// Protect URLs, printf formatting and HTML entities
if( preg_match('!^https?://\\S*!',$source,$match) ||
preg_match('/^&(#\\d+|#x[0-9a-f]|[a-z]+);/i',$source,$match) ||
preg_match('!^</?[a-z]+.*>!iU',$source,$match) ||
preg_match('/^%(?:\\d+\\$)?(?:\'.|[-+0 ])*\\d*(?:\\.\\d+)?[suxXbcdeEfFgGo%]/',$source,$match)
){
$target .= $match[0];
}
// else 'translate' if it looks wordy (ascii only here)
else if( preg_match('/^[a-z]+/i',$source,$match) ){
$target .= mock_translator_translate_word($match[0]);
}
// else use whatever this is up to the next unicode character, which is probably punctuation.
else if( preg_match('/^./u',$source,$match) ){
$target .= $match[0];
}
// else bail with whatever's left, which should be impossible unless string isn't utf8
else {
$target .= $source;
break;
}
// truncate source and continue
$length = strlen($match[0]);
$source = substr($source,$length);
}
return $target;
}
/**
* @param string
* @return string
*/
function mock_translator_translate_word( $source ){
// TODO string reverse needs to be utf8-safe
$target = strrev($source);
// reverse title casing if applicable
if( preg_match('/^[A-Z][a-z]+/',$source) ){
$target = mb_convert_case($target,MB_CASE_TITLE,'UTF-8');
}
return $target;
}