You are here

ClientService.php in Sparkpost email 8.2

Same filename and directory in other branches
  1. 8 src/ClientService.php

Namespace

Drupal\sparkpost

File

src/ClientService.php
View source
<?php

namespace Drupal\sparkpost;

use Drupal\Core\Config\ConfigFactory;
use GuzzleHttp\Client;
use SparkPost\SparkPost;
use Http\Adapter\Guzzle6\Client as GuzzleAdapter;

/**
 * Client service that sends the mails.
 *
 * @package Drupal\sparkpost
 */
class ClientService implements ClientServiceInterface {

  /**
   * Regex for parsing email.
   */
  const EMAIL_REGEX = '/^\\s*(.+?)\\s*<\\s*([^>]+)\\s*>$/';

  /**
   * Drupal\Core\Config\ConfigFactory definition.
   *
   * @var \Drupal\Core\Config\ConfigFactory
   */
  protected $configFactory;

  /**
   * GuzzleHttp\Client definition.
   *
   * @var \GuzzleHttp\Client
   */
  protected $client;

  /**
   * Constructor.
   */
  public function __construct(Client $client, ConfigFactory $configFactory) {
    $this->client = $client;
    $this->configFactory = $configFactory;
  }

  /**
   * {@inheritdoc}
   */
  public function getClient() {
    $config = $this->configFactory
      ->get('sparkpost.settings');
    $httpClient = new GuzzleAdapter($this->client);
    $options = [
      'key' => $config
        ->get('api_key'),
    ];
    if (!empty($config
      ->get('api_hostname'))) {
      $options['host'] = $config
        ->get('api_hostname');
    }
    return new SparkPost($httpClient, $options);
  }

  /**
   * {@inheritdoc}
   */
  public function sendMessage(array $message) {
    $client = $this
      ->getClient();
    try {
      $promise = $client->transmissions
        ->post($message);
      $response = $promise
        ->wait();
      return $response
        ->getBody();
    } catch (\Exception $e) {
      \Drupal::logger('sparkpost')
        ->error($e
        ->getMessage());
      throw $e;
    }
  }

  /**
   * {@inheritdoc}
   */
  public function sendRequest($endpoint, array $data, $method = 'GET') {
    $client = $this
      ->getClient();
    $promise = $client
      ->request($method, $endpoint, $data);
    $response = $promise
      ->wait();
    return $response
      ->getBody();
  }

}

Classes

Namesort descending Description
ClientService Client service that sends the mails.