You are here

protected function GoogleTranslator::doRequest in TMGMT Translator Google 8

Local method to do request to Google Translate service.

Parameters

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

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

array $request_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

TMGMTException

  • Invalid action provided
  • Unable to connect to the Google Service
  • Error returned by the Google Service
2 calls to GoogleTranslator::doRequest()
GoogleTranslator::getSupportedRemoteLanguages in src/Plugin/tmgmt/Translator/GoogleTranslator.php
Overrides TMGMTDefaultTranslatorPluginController::getSupportedRemoteLanguages().
GoogleTranslator::googleRequestTranslation in src/Plugin/tmgmt/Translator/GoogleTranslator.php
Helper method to do translation request.

File

src/Plugin/tmgmt/Translator/GoogleTranslator.php, line 253
Contains \Drupal\tmgmt_microsoft\Plugin\tmgmt\Translator\MicrosoftTranslator.

Class

GoogleTranslator
Google translator plugin.

Namespace

Drupal\tmgmt_google\Plugin\tmgmt\Translator

Code

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

  // Translate action is requested without this argument.
  if ($action == 'translate') {
    $action = '';
  }

  // Get custom URL for testing purposes, if available.
  $custom_url = $translator
    ->getSetting('url');
  $url = ($custom_url ? $custom_url : $this->translatorUrl) . '/' . $action;

  // Prepare Guzzle Object.
  $request = new Request('GET', $url);

  // Build the query.
  $query_string .= '&key=' . $translator
    ->getSetting('api_key');
  if (isset($request_query['q'])) {
    foreach ($request_query['q'] as $source_text) {
      $query_string .= '&q=' . urlencode($source_text);
    }
  }
  if (isset($request_query['source'])) {
    $query_string .= '&source=' . $request_query['source'];
  }
  if (isset($request_query['target'])) {
    $query_string .= '&target=' . $request_query['target'];
  }

  // Send the request with the query.
  try {
    $response = $this->client
      ->send($request, [
      'query' => $query_string,
    ]);
  } catch (BadResponseException $e) {
    $error = json_decode($e
      ->getResponse()
      ->getBody(), TRUE);
    throw new TMGMTException('Google Translate service returned following error: @error', [
      '@error' => $error['error']['message'],
    ]);
  }

  // Process the JSON result into array.
  return json_decode($response
    ->getBody(), TRUE);
}