* @license PHP License * @package WB * @subpackage base */ WBClass::load('WBNLS_Translator_Service'); /** * Native Lanauge Support: Translator Service DeepL * * Use DeepL service to translate * https://developers.deepl.com/docs/getting-started/readme * * @version 0.1.1 * @package WB * @subpackage nls */ class WBNLS_Translator_Service_DeepL extends WBNLS_Translator_Service { /** * My Configuration Parameter * * Required parameter: apikey * @var array */ protected $config = array( 'apikey' => '', 'formality' => 'default' ); /** * @var WBRest_Client */ private $client; /** * Construtor * * @param array configation parameters */ public function __construct($parameter = array()) { /** @var WBRest_Client */ $this->client = WBClass::create('WBRest_Client'); $this->client->setHeader('Accept', 'application/json'); $this->client->setHeader('Content-Type', 'application/json'); } /** * 2nd Construtor * * Set API-key and choose server for free API calls * @see configure() */ protected function init() { if (empty($this->config['apikey'])) { $ex = array( 'msg' => 'Configuration parameter apikey is missing', 'code' => 1, 'class' => __CLASS__ ); throw WBClass::create('WBException_Config', $ex); } $config = array( 'server' => 'api.deepl.com', 'pathprefix' => 'v2' ); $free = substr($this->config['apikey'], -3); if (':fx' == $free) { $config['server'] = 'api-free.deepl.com'; } $this->client->configure($config); $this->client->setHeader('Authorization', 'DeepL-Auth-Key ' . $this->config['apikey']); } /** * Translate List of String * * @param array list of associative arrays * @param string key in associative array * @return bool true on success */ public function translateList(&$list, $key = 'msg') { $body = array( 'source_lang' => substr($this->getSourceLang(), 0, 2), 'target_lang' => substr($this->getTargetLang(), 0, 2), // 'target_lang' => substr($this->getSourceLang(), 0, 2), 'tag_handling' => 'xml', 'text' => array(), 'formality' => $this->config['formality'] ); foreach ($list as $l) { $body['text'][] = $l[$key]; } // debug print to be improved if (10 <= WBParam::get('wb/debug', 0)) { echo __CLASS__ . ' Request /translate ' . print_r($body, true) . "\n"; } if(!$this->client->post('/translate', $body)) { return false; } $res = $this->client->getRespone(); $trans = $res->getContent(); if (empty($trans['translations'])) { // debug print to be improved if (10 <= WBParam::get('wb/debug', 0)) { echo __CLASS__ . ' Response /translate There are not translations' . "\n"; } return false; } $trans = $trans['translations']; if (count($list) != count($trans)) { // debug print to be improved if (10 <= WBParam::get('wb/debug', 0)) { echo __CLASS__ . ' Response /translate Wrong number of translations' . "\n"; } return false; } foreach ($list as $i => &$l) { $l[$key . '_trans'] = $trans[$i]['text']; } return true; } }