You are here

protected function TMGMTGoogleTranslatorPluginController::doRequest in TMGMT Translator Google 7

Local method to do request to Google Translate service.

Parameters

TMGMTTranslator $translator: The translator entity to get the settings from.

string $action: Action to be performed [translate, languages, detect]

array $query: (Optional) Additional query params to be passed into the request.

array $options: (Optional) Additional options that will be passed into drupal_http_request().

Return value

array object Unserialized JSON response from Google.

Throws

TMGMTGoogleException

  • Invalid action provided
  • Unable to connect to the Google Service
  • Error returned by the Google Service
2 calls to TMGMTGoogleTranslatorPluginController::doRequest()
TMGMTGoogleTranslatorPluginController::getSupportedRemoteLanguages in ./tmgmt_google.plugin.inc
Overrides TMGMTDefaultTranslatorPluginController::getSupportedRemoteLanguages().
TMGMTGoogleTranslatorPluginController::googleRequestTranslation in ./tmgmt_google.plugin.inc
Helper method to do translation request.

File

./tmgmt_google.plugin.inc, line 218
Provides Google Translator plugin controller.

Class

TMGMTGoogleTranslatorPluginController
Google translator plugin controller.

Code

protected function doRequest(TMGMTTranslator $translator, $action, array $query = array(), array $options = array()) {
  if (!in_array($action, $this->availableActions)) {
    throw new TMGMTGoogleException('Invalid action requested: @action', array(
      '@action' => $action,
    ));
  }

  // Translate action is requested without this argument.
  if ($action == 'translate') {
    $action = '';
  }
  $query['key'] = $translator
    ->getSetting('api_key');
  $q = NULL;

  // If we have q param for translation as an array, we have to process it
  // in different way as does url() as Google does not accept typical
  // q[0] & q[1] ... syntax.
  if (isset($query[$this->qParamName]) && is_array($query[$this->qParamName])) {
    $q = $query[$this->qParamName];
    unset($query[$this->qParamName]);
  }
  $url = url($this->translatorUrl . '/' . $action, array(
    'query' => $query,
  ));

  // Append q params to the url.
  if (!empty($q)) {
    foreach ($q as $source_text) {
      $url .= "&{$this->qParamName}=" . str_replace('%2F', '/', rawurlencode($source_text));
    }
  }
  $response = drupal_http_request($url, $options);
  if ($response->code != 200) {
    throw new TMGMTGoogleException('Unable to connect to Google Translate service due to following error: @error at @url', array(
      '@error' => $response->error,
      '@url' => $url,
    ));
  }

  // Process the JSON result into array.
  $response = drupal_json_decode($response->data);

  // If we do not have data - we got error.
  if (!isset($response['data'])) {
    throw new TMGMTGoogleException('Google Translate service returned following error: @error', array(
      '@error' => $response['error']['message'],
    ));
  }
  return $response;
}