Why Gemfury? Push, build, and install  RubyGems npm packages Python packages Maven artifacts PHP packages Go Modules Debian packages RPM packages NuGet packages

Repository URL to install this package:

Details    
novicell/dds_sendgrid / modules / template_list / src / Controller / SendGridTemplateService.php
Size: Mime:
<?php

namespace Drupal\dds_sendgrid_template_list\Controller;

use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Database\Connection;
use Drupal\Core\Database\StatementInterface;
use Drupal\Core\Logger\LoggerChannelFactoryInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;

class SendGridTemplateService extends ControllerBase {

  /**
   * @var \Drupal\Core\Config\ImmutableConfig
   *   The configuration for the sendgrid settings.
   */
  protected $config;

  /**
   * @var \Drupal\Core\Logger\LoggerChannelInterface
   *   The logging channel.
   */
  protected $logger;

  /**
   * @var \Drupal\Core\Database\Connection
   *   The database connection.
   */
  protected $connection;

  /**
   * @inheritDoc
   */
  public static function create(ContainerInterface $container) {
    return new static(
      $container->get('config.factory'),
      $container->get('logger.factory'),
      $container->get('database')
    );
  }

  /**
   * SendGridTemplateService constructor.
   */
  public function __construct(ConfigFactoryInterface $config_factory, LoggerChannelFactoryInterface $logger_factory, Connection $database) {
    $this->configFactory = $config_factory;
    $this->loggerFactory = $logger_factory;
    $this->connection = $database;
    $this->config = $this->configFactory->get('dds_sendgrid.settings');
    $this->logger = $this->loggerFactory->get('DDS SendGrid Template List');
  }

  /**
   * Store new templates in database.
   *
   * This function is responsible for storing the new templates gotten from
   * SendGrid in our database to reduce the API calls we make to the SendGrid
   * API template endpoint.
   *
   * @return array
   *   Returns the array of new templates.
   */
  private function cacheTemplates() : array {
    $cache_id               = 'dds_sendgrid_template_list:templates';
    $cache_data             = $this->getNewTemplates();
    $current_timestamp      = \Drupal::time()->getCurrentTime();
    $expiration_timestamp   = $current_timestamp + 21600;

    $this->cache('data')->set($cache_id, $cache_data, $expiration_timestamp);
    return $cache_data;
  }

  /**
   * Get all templates from SendGrid.
   *
   * Gets all the templates found on SendGrid based on the parameters provided.
   *
   * @param array $types
   *   (Optional, Default = [Array(]'dynamic', 'legacy']) An array containing
   *   the types of templates to load.
   *   Accepted types are "dynamic" and "legacy", as the parameter is an array
   *   you can specify both or just one of them.
   * @param int $batch_size
   *   (Optional, Default = 200) The number of results to list per page.
   * @param string|NULL $page_token
   *   (Optional, Default = NULL) The token that defines what page we are on.
   *
   * @return array
   *   Returns an array of all the templates found.
   */
  private function getNewTemplates($types = ['dynamic', 'legacy'], $batch_size = 200, $page_token = NULL) : array {
    $api_key = $this->config->get('api_key');

    // Set log messages and return an empty array if no api key is set.
    if (empty($api_key)) {
      $this->logger->error('Missing API Key!');
      return [];
    }

    // Instantiate a new sendgrid instance.
    $sendgrid = new \SendGrid($api_key);

    // Define the parameters so that we can be sure we get the proper list of
    // templates.
    $parameters = [
      'generations' => implode(',', $types),
      'page_size' => $batch_size
    ];

    // If we have a page token, add that to the parameters to make sure we get
    // the correct page.
    if (!empty($page_token)) {
      $parameters['page_token'] = $page_token;
    }

    // Make the request for the template list.
    $response = $sendgrid->client->templates()->get(NULL, $parameters);

    // Decode the response body as JSON so we can easily process the templates.
    $body = json_decode($response->body(), TRUE);
    $templates_raw = $body['result'];

    $templates = [];
    // Run through all templates and add them keyed by their template ID.
    foreach ($templates_raw as $template) {
      $templates[$template['id']] = $template;
    }

    // If the response body contains metadata for the next page, get the
    // templates from that as well.
    if (!empty($body['_metadata']['next'])) {
      $url = parse_url($body['_metadata']['next']);
      parse_str($url['query'], $query);

      // Merge the templates together into one array.
      array_merge(
        $templates,
        $this->getNewTemplates($types, $batch_size, $query['page_token'])
      );
    }

    return $templates;
  }

  /**
   * Get all stored templates.
   *
   * Gets all the templates that are stored in the database.
   *
   * @return array
   *   An array containing all the stored templates.
   */
  public function getTemplates() : array {
    $cache_id   = 'dds_sendgrid_template_list:templates';
    $cache_data = $this->cache('data')->get($cache_id);

    if ($cache_data) {
      $templates = $cache_data->data;
    }
    else {
      $templates = $this->cacheTemplates();
    }

    return $templates;
  }

  /**
   * Gets all template names.
   *
   * This gets an array of all template names keyed by their template id.
   * This is useful for use in select, radio or checkbox form elements.
   *
   * @return array
   *   Returns an array of template names, keyed with the template id.
   */
  public function getTemplateNames() : array {
    $templates = $this->getTemplates();
    foreach ($templates as $id => $values) {
      // If the template doesn't have a name, we do not include it.
      if (empty($values['name'])) {
        unset($templates[$id]);
        continue;
      }
      $templates[$id] = $values['name'];
    }
    return $templates;
  }

  /**
   * Refresh the cached templates.
   *
   * This removes all cached templates and gets a new list from SendGrid and
   * adds that to the cache.
   */
  public function refreshCachedTemplates() : void {
    $cache_id   = 'dds_sendgrid_template_list:templates';
    $this->cache('data')->delete($cache_id);
    $this->cacheTemplates();
  }
}