* @license PHP License * @package WB * @subpackage base */ WBClass::load('WBNLS_Translator_Service'); /** * Native Lanauge Support: Translator Service GoogleAPIs * * * Utilize Google API Cloud Translation * See https://cloud.google.com/translate/docs/basic/translate-text-basic * * @version 0.2.0 * @package WB * @subpackage nls */ class WBNLS_Translator_Service_GoogleAPIs extends WBNLS_Translator_Service { /** * @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->configure(array( 'server' => 'translation.googleapis.com', 'pathprefix' => 'language/translate/v2' )); $this->client->setHeader('Accept', 'application/json'); $this->client->setHeader('Content-Type', 'application/json'); } /** * 2nd Construtor * * @see configure() */ protected function init() { $this->client->setHeader('X-goog-api-key', $this->config['apikey']); $this->client->setHeader('Authorization', '$(gcloud auth print-access-token)'); } /** * 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' => substr($this->getSourceLang(), 0, 2), 'target' => substr($this->getTargetLang(), 0, 2), 'format' => 'text', 'q' => array() ); foreach ($list as $l) { $body['q'][] = $l[$key]; } if(!$this->client->post('/', $body)) { return false; } $res = $this->client->getRespone(); $trans = $res->getContent(); if (empty($trans['data']) || empty($trans['data']['translations'])) { return false; } $trans = $trans['data']['translations']; if (count($list) != count($trans)) { return false; } foreach ($list as $i => &$l) { $l[$key . '_trans'] = $trans[$i]['translatedText']; } return true; } }