You are here

protected function GoogleAnalyticsCounterFeed::request in Google Analytics Counter 8.3

Execute a query.

Parameters

string $url: URL value.

array $params: Array of parameters.

array $headers: Array of headers.

string $method: HTTM method.

Return value

\Symfony\Component\HttpFoundation\RedirectResponse

Throws

\GuzzleHttp\Exception\GuzzleException

1 call to GoogleAnalyticsCounterFeed::request()
GoogleAnalyticsCounterFeed::query in src/GoogleAnalyticsCounterFeed.php
Public query method for all Core Reporting API features.

File

src/GoogleAnalyticsCounterFeed.php, line 398

Class

GoogleAnalyticsCounterFeed
Authorize access and request data from Google Analytics Core Reporting API.

Namespace

Drupal\google_analytics_counter

Code

protected function request($url, $params = array(), $headers = array(), $method = 'GET') {
  $options = [
    'method' => $method,
    'headers' => $headers,
  ];
  if (count($params) > 0) {
    if ($method == 'GET') {
      $url .= '?' . UrlHelper::buildQuery($params);
    }
    else {
      $options['body'] = UrlHelper::buildQuery($params);
    }
  }
  $client = \Drupal::httpClient();
  try {
    $this->response = $client
      ->request($method, $url, $options);
  } catch (\Exception $e) {
    if ($e
      ->getCode() == 403) {
      return new RedirectResponse(Url::fromRoute('google_analytics_counter.admin_auth_form', [], [
        'absolute' => TRUE,
      ])
        ->toString());
    }
  }

  // If there is no response because the profile_id is unauthenticated,
  // drush cron will fail with 'Call to a member function getBody() on null.'
  // Todo: In that case, make drush fail more elegantly.
  if (!empty($this->response
    ->getBody()) && $this->response
    ->getStatusCode() == '200') {
    $this->results = json_decode($this->response
      ->getBody()
      ->__toString());
  }
  else {

    // Data is undefined if the connection failed.
    if (isset($this->response) && empty($this->response
      ->getBody()
      ->__toString())) {

      // @todo check it!!! it's temp code.
      $this->response
        ->setBody('');
    }
    $error_vars = [
      '@code' => $this->response
        ->getStatusCode(),
      '@message' => $this->response
        ->getReasonPhrase(),
      '@details' => strip_tags($this->response
        ->getBody()
        ->__toString()),
    ];
    $this->error = $this
      ->t('Code: @code.  Error: @message.  Message: @details', $error_vars);
    \Drupal::logger('google_analytics_counter')
      ->error('Code: @code.  Error: @message.  Message: @details', $error_vars);
  }
}