You are here

public function DrupalMandrill::call in Mandrill 8

Override call method to user Drupal's HTTP handling.

File

src/DrupalMandrill.php, line 71

Class

DrupalMandrill
Overrides default Mandrill library to provide custom API call function.

Namespace

Drupal\mandrill

Code

public function call($url, $params) {
  $params['key'] = $this->apikey;
  $params = \Drupal\Component\Serialization\Json::encode($params);

  /* @var $client \GuzzleHttp\Client */
  $client = \Drupal::httpClient();
  $options = array(
    'headers' => array(
      'Content-Type' => 'application/json',
      'User-Agent',
      $this->userAgent,
    ),
    'body' => $params,
  );
  try {
    $response = $client
      ->post($this->root . $url . '.json', $options);

    // Expected result.
    $data = $response
      ->getBody(TRUE);
    $result = \Drupal\Component\Serialization\Json::decode($data);
  } catch (RequestException $e) {
    watchdog_exception('my_module', $e
      ->getMessage());
    throw new Mandrill_HttpError(t('Mandrill API call to %url failed: %msg', array(
      '%url' => $url,
      '%msg' => $response->error,
    )));
  }
  if ($result === NULL) {
    throw new Mandrill_Error('We were unable to decode the JSON response from the Mandrill API: ' . $response->data);
  }
  if (floor($response
    ->getStatusCode() / 100) >= 4) {
    throw $this
      ->castError($result);
  }
  return $result;
}