You are here

public function BrowscapEndpoint::getBrowscapData in Browscap 8.3

Gets latest Browscap data.

Parameters

bool $cron: Whether this method is being invoked by cron.

Return value

int|string Either an error code (BROWSCAP_IMPORT_DATA_ERROR) or the Browscap data.

1 method overrides BrowscapEndpoint::getBrowscapData()
MockBrowscapEndpoint::getBrowscapData in src/Tests/MockBrowscapEndpoint.php
Gets latest Browscap data.

File

src/BrowscapEndpoint.php, line 59

Class

BrowscapEndpoint
Browscap endpoint.

Namespace

Drupal\browscap

Code

public function getBrowscapData($cron = TRUE) {
  $config = \Drupal::config('browscap.settings');
  $client = \Drupal::httpClient();

  // Set options for downloading data with or without compression.
  if (function_exists('gzdecode')) {
    $options = [
      'headers' => [
        'Accept-Encoding' => 'gzip',
      ],
    ];
  }
  else {

    // The download takes over ten times longer without gzip, and may exceed
    // the default timeout of 30 seconds, so we increase the timeout.
    $options = [
      'timeout' => 600,
    ];
  }

  // Retrieve the browscap data using HTTP.
  try {
    $browscapDataURL = $config
      ->get('data_url');
    $response = $client
      ->get($browscapDataURL, $options);

    // getBody will decompress gzip if need be.
    $browscap_data = (string) $response
      ->getBody();

    // Expected result.
  } catch (RequestException $e) {
    watchdog_exception('browscap', $e
      ->getMessage());
  }

  // Log an error if the browscap data could not be retrieved.
  if (isset($response->error) || empty($response)) {

    // Log a message with the watchdog.
    \Drupal::logger('browscap')
      ->error("Couldn't retrieve updated browscap: %error", [
      '%error' => $browscap_data->error,
    ]);

    // Display a message to the user if the update process was triggered
    // manually.
    if ($cron == FALSE) {
      drupal_set_message(t("Couldn't retrieve updated browscap: %error", [
        '%error' => $response->error,
      ]), 'error');
    }
    return BrowscapImporter::BROWSCAP_IMPORT_DATA_ERROR;
  }
  return $browscap_data;
}