You are here

function _leaflet_more_maps_get_navionics_navtoken in Leaflet More Maps 2.1.x

Helper function to get Navionics token based on api_key and authorized domain.

Return value

string Navionics token, if successful or empty string on error.

1 call to _leaflet_more_maps_get_navionics_navtoken()
_leaflet_more_maps_assemble_default_map_info in ./leaflet_more_maps.module
Function to add info for all available maps.

File

./leaflet_more_maps.module, line 604

Code

function _leaflet_more_maps_get_navionics_navtoken() {

  // Get Navionics configuration: API key and Authorized Domain.
  $config = Drupal::config('leaflet_more_maps.settings');
  $api_key = trim($config
    ->get('navionics_api_key'));
  $authorized_domain = trim($config
    ->get('navionics_authorized_domain'));
  if (empty($api_key) || empty($authorized_domain)) {
    return '';
  }

  // Prepare url to get the token.
  // With timestamp because Navionics invalidates the token over time.
  $url = '//backend.navionics.com/tile/get_key/' . $api_key . '/' . $authorized_domain . '/?_=' . time();

  // Prepare referer to send it Navionics check on referral also.
  $referer = 'https://' . $authorized_domain;

  // Prepare Client.
  $client = \Drupal::httpClient();
  try {
    $request = $client
      ->get($url, [
      'curl' => [
        CURLOPT_RETURNTRANSFER => TRUE,
        CURLOPT_HEADER => 0,
        CURLOPT_REFERER => $referer,
      ],
    ]);

    // Get the status code of request.
    $status = $request
      ->getStatusCode();
    if ($status == 200) {

      // Get the response.
      return $request
        ->getBody()
        ->getContents();
    }
    \Drupal::logger('leaflet_more_maps')
      ->warning('Could not retrieve Navionics token. Status code: @status_code.', [
      '@status_code' => $status,
    ]);
  } catch (RequestException $e) {
    \Drupal::logger('leaflet_more_maps')
      ->error('Could not retrieve Navionics token: @error', [
      '@error' => $e
        ->getMessage(),
    ]);
  }
  return '';
}