Machine translation
The translate plugin gives one API for machine translation engines: Google (the keyless web endpoint or Cloud
Translation), DeepL, Azure AI Translator, and drivers a site adds. The site's configuration decides which engine answers first and
which ones take over when it fails. Placeholders and HTML are protected on the way out and checked on the way back, verified results are
kept in a translation memory, and a monthly budget can cap the spending. There is no global helper: use _class('translate').
Calls
$tr = _class('translate');
$text = $tr->text('Add to cart', 'uk'); // a string, or false
$out = $tr->batch([
'cart' => 'Add to cart',
'buy' => 'Buy {count} items',
], 'de', 'en', ['context' => 'shop buttons', 'formality' => 'less']);
// ['cart' => 'In den Warenkorb', 'buy' => '{count} Artikel kaufen'], false for a string that was not translated
if (in_array(false, $out, true)) {
logger()->warning('not translated: ' . json_encode($tr->_failed));
}
| Method | What it does |
|---|---|
text($text, $to, $from = null, $params = []) | One string: the translation or false. $from
defaults to SOURCE_LANG (en). |
batch(array $texts, $to, $from = null, $params = []) | Several strings, the same keys back. Empty strings come back as they are; the same source and target language return the texts unchanged. |
languages($driver = '') | The language codes a driver supports (default: the first of the chain), cached for a day. |
estimate($texts, $langs, $params = []) | What a run would take: characters per language (memory hits left out), the cost per driver at list price and the budget left this month. No request. |
normalize_lang($code) | The code form the plugin uses: pt_BR → pt-BR, zh-hant →
zh-Hant; '' for anything that is not a language code. |
$params: driver (the first driver of this call) and fallback (the drivers after it,
[] for none); context (what the strings are: part of the memory key, sent to engines that use it);
feature (your name for the caller in the usage table); formality (less / more, where the
engine supports it); tm false (no memory) and tm_write false (read the memory, do not
store).
After a call: _last_error_message, _last_driver (the driver of the last translated string, memory
for a memory hit), _last_stats (items, chars, requests, errors, failed, tm_hits, cost, drivers) and _failed
(key => why, for each string that came back false).
Placeholders and HTML
Template tags ({name}, {if(...)}, {{ twig }}), variables of
t() (%name, @name), printf formats (%s, %1$d) and the site's
KEEP_TERMS are swapped for markup the engine leaves alone, and put back after. HTML is sent as HTML. Then each result is
checked strictly: the same placeholders (their order may change), the same tags in the same order with the same attributes, nothing
of the protection left. A result that fails goes to the next driver of the chain, or comes back false with the reason in
_failed; it is never stored. Escape a translation like any other text when you print it (_prepare_html()):
the check keeps engines from adding tags, but the source may hold HTML of your own.
Translation memory
Verified results are stored by language pair, context and source text, and the next call gets them without a request. Rows an
admin edited or approved are never overwritten by a machine run. Use a context when the same words need different
translations (a "Save" button and "save" money).
Writing a driver
A driver extends yf_translate_driver (classes/translate/yf_translate_driver_<name>.class.php of your app
or one of its plugins) and implements one method; the plugin does the memory, the protection and check, the splitting by limits,
retries, budget, fallback and usage. Name it in DRIVER or FALLBACK_DRIVERS; its settings come from
$PROJECT_CONF['translate_driver_<name>'].
class yf_translate_driver_myengine extends yf_translate_driver
{
public $TITLE = 'My engine';
public $KEY_ENVS = ['MYENGINE_API_KEY'];
public $PROTECT = 'html'; // token (plain text engines), html (span translate="no") or xml (<x id/>)
public $PRICE_PER_MILLION = 15.0;
public $MAX_ITEMS = 100;
public $MAX_CHARS = 10000;
public function translate_batch(array $texts, $from, $to, array $params, &$error = '')
{
$data = $this->_request('POST', 'https://api.example.com/translate', ['Authorization: Bearer ' . $this->key()],
['q' => array_values($texts), 'source' => $from, 'target' => $to, 'format' => $params['format']], $error);
$out = [];
foreach (array_keys($texts) as $i => $key) {
$out[$key] = $data['translations'][$i] ?? false;
}
return $out;
}
}
_request() sends JSON over curl with TLS verified, retries 408 / 429 / 5xx with backoff and masks the key in
$error. Override languages(), test() (the connection test of the admin page) and
lang() (the engine's language codes) when the engine has them.