You are here

class AkamaiClientV3 in Akamai 8.3

Defines the CCUv3 client version for Akamai.

Plugin annotation


@AkamaiClient(
  id = "v3",
  title = @Translation("Akamai Client CCUv3")
)

Hierarchy

Expanded class hierarchy of AkamaiClientV3

File

src/Plugin/Client/AkamaiClientV3.php, line 17

Namespace

Drupal\akamai\Plugin\Client
View source
class AkamaiClientV3 extends AkamaiClientBase {

  /**
   * Base url to which API method names are appended.
   *
   * @var string
   */
  protected $apiBaseUrl = '/ccu/v3/';

  /**
   * An action to take, either 'delete' or 'invalidate'.
   *
   * @var string
   */
  protected $action = 'delete';

  /**
   * Type of purge, either 'url', 'tag' or 'cpcode'.
   *
   * @var string
   */
  protected $type = 'url';

  /**
   * Represents whether this client uses a queuing system or not.
   *
   * @var bool
   */
  protected $usesQueue = FALSE;

  /**
   * Ask the API to purge an object.
   *
   * @param string[] $objects
   *   A non-associative array of Akamai objects to clear.
   *
   * @return \GuzzleHttp\Psr7\Response|bool
   *   Response to purge request, or FALSE on failure.
   *
   * @link https://developer.akamai.com/api/purge/ccu/reference.html
   * @link https://github.com/akamai-open/api-kickstart/blob/master/examples/php/ccu.php#L58
   */
  protected function purgeRequest(array $objects) {
    try {
      $response = $this->client
        ->request('POST', "{$this->apiBaseUrl}{$this->action}/{$this->type}/{$this->domain}", [
        'json' => $this
          ->createPurgeBody($objects),
      ]);

      // Note that the response has useful data that we need to record.
      // Example response body:
      // @code
      // {
      //   "httpStatus": 201,
      //   "detail": "Request accepted.",
      //   "estimatedSeconds": 5,
      //   "purgeId": "043f-4af0-843f-aaf0043faaf0",
      //   "supportId": "17PY1321286429616716-211907680"
      // }.
      // @endcode
      return $response;
    } catch (RequestException $e) {
      $this->logger
        ->error($this
        ->formatExceptionMessage($e));
      return FALSE;

      // @todo better error handling
      // Throw $e;.
    }
  }

  /**
   * Create an array to pass to Akamai's purge function.
   *
   * @param string[] $objects
   *   A list of URLs.
   *
   * @return array
   *   An array suitable for sending to the Akamai purge endpoint.
   */
  public function createPurgeBody(array $objects) {
    $body = [
      'objects' => $objects,
    ];
    if ($this->type == 'url') {
      $purge_urls_with_hostname = $this->configFactory
        ->get('akamai.settings')
        ->get('purge_urls_with_hostname');
      if ($purge_urls_with_hostname) {
        $body['hostname'] = $this->baseUrl;
      }
    }
    return (object) $body;
  }

  /**
   * Helper function to validate the actions for purge request.
   *
   * @return $this
   */
  public function validActions() {
    return [
      'delete',
      'invalidate',
    ];
  }

  /**
   * Sets the type of purge.
   *
   * @param string $type
   *   The type of purge, either 'url', 'tag' or 'cpcode'.
   *
   * @return $this
   */
  public function setType($type) {
    $valid_types = [
      'cpcode',
      'tag',
      'url',
    ];
    if (in_array($type, $valid_types)) {
      $this->type = $type;
    }
    else {
      throw new \InvalidArgumentException('Type must be one of: ' . implode(', ', $valid_types));
    }
    return $this;
  }

  /**
   * {@inheritdoc}
   */
  public function buildConfigurationForm(array $form, FormStateInterface $form_state) {
    $config = $this->configFactory
      ->get('akamai.settings');
    $default_action = key(array_filter($config
      ->get('action_v3')));
    $form['action'] = [
      '#type' => 'select',
      '#title' => $this
        ->t('Clearing Action Type Default'),
      '#default_value' => in_array($default_action, $this
        ->validActions()) ? $default_action : 'delete',
      '#options' => [
        'delete' => $this
          ->t('Delete'),
        'invalidate' => $this
          ->t('Invalidate'),
      ],
      '#description' => $this
        ->t('The default clearing action. The options are <em>delete</em> (which deletes the item from the Akamai cache) and <em>invalidate</em> (which leaves the item in the cache, but invalidates it so that the origin will be hit on the next request).'),
      '#required' => TRUE,
    ];
    $form['purge_urls_with_hostname'] = [
      '#type' => 'checkbox',
      '#title' => $this
        ->t('Purge URLs With Common Hostname'),
      '#default_value' => $config
        ->get('purge_urls_with_hostname'),
      '#description' => $this
        ->t('Sends Base Path as "hostname" Fast Purge API request data member when purging URLs'),
    ];
    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function submitConfigurationForm(array &$form, FormStateInterface $form_state) {
    $actions = array_fill_keys($this
      ->validActions(), FALSE);
    $actions[$form_state
      ->getValue([
      'v3',
      'action',
    ])] = TRUE;
    $this->configFactory
      ->getEditable('akamai.settings')
      ->set('action_v3', $actions)
      ->set('purge_urls_with_hostname', $form_state
      ->getValue([
      'v3',
      'purge_urls_with_hostname',
    ]))
      ->save();
  }

  /**
   * {@inheritdoc}
   */
  public static function getSupportedVersions() {
    $versions = [];
    foreach (static::supportedTypes() as $type) {
      $versions[] = Unicode::strtolower($type);
    }
    return $versions;
  }

}

Members

Namesort descending Modifiers Type Description Overrides
AkamaiClientBase::$akamaiClientConfig protected property A config suitable for use with Akamai\Open\EdgeGrid\Client.
AkamaiClientBase::$baseUrl protected property The domain for which Akamai is managing cache.
AkamaiClientBase::$client protected property An instance of an OPEN EdgeGrid Client.
AkamaiClientBase::$configFactory protected property The config factory.
AkamaiClientBase::$domain protected property Domain to clear, either 'production' or 'staging'.
AkamaiClientBase::$logger protected property A logger instance.
AkamaiClientBase::$logRequests protected property Whether or not to log all requests and responses.
AkamaiClientBase::bodyIsBelowLimit public function Verifies that the body of a purge request will be under 50,000 bytes. Overrides AkamaiClientInterface::bodyIsBelowLimit
AkamaiClientBase::create public static function Creates an instance of the plugin. Overrides ContainerFactoryPluginInterface::create
AkamaiClientBase::createClientConfig public function Creates a config array for consumption by Akamai\Open\EdgeGrid\Client.
AkamaiClientBase::enableRequestLogging public function Enables logging of all requests and responses.
AkamaiClientBase::formatExceptionMessage protected function Formats a JSON error response into a string.
AkamaiClientBase::isAkamaiManagedUrl public function Checks whether a fully qualified URL is handled by Akamai.
AkamaiClientBase::normalizeUrl public function Given a URL, make sure it is fully qualified.
AkamaiClientBase::normalizeUrls public function Given a list of URLs, ensure they are fully qualified.
AkamaiClientBase::purgeCpCode public function Purges a single cpcode object.
AkamaiClientBase::purgeCpCodes public function Purges a list of cpcode objects.
AkamaiClientBase::purgeTags public function Purges a list of tag objects.
AkamaiClientBase::purgeUrl public function Purges a single URL object.
AkamaiClientBase::purgeUrls public function Purges a list of URL objects.
AkamaiClientBase::setAction public function Helper function to set the action for purge request. Overrides AkamaiClientInterface::setAction
AkamaiClientBase::setApiBaseUrl public function Sets API base url.
AkamaiClientBase::setBaseUrl public function Sets Akamai base url.
AkamaiClientBase::setDomain public function Sets the domain to clear. Overrides AkamaiClientInterface::setDomain
AkamaiClientBase::setLogRequests public function Sets whether or not to log requests and responses.
AkamaiClientBase::usesQueue public function Returns whether the client uses a queue or not.
AkamaiClientBase::validateConfigurationForm public function Form validation handler. Overrides PluginFormInterface::validateConfigurationForm
AkamaiClientBase::__construct public function AkamaiClient constructor. Overrides PluginBase::__construct
AkamaiClientInterface::MAX_BODY_SIZE constant The maximum size, in bytes, of a request body allowed by the API.
AkamaiClientInterface::NETWORK_PRODUCTION constant String constant for the production network.
AkamaiClientInterface::NETWORK_STAGING constant String constant for the staging network.
AkamaiClientV3::$action protected property An action to take, either 'delete' or 'invalidate'. Overrides AkamaiClientBase::$action
AkamaiClientV3::$apiBaseUrl protected property Base url to which API method names are appended. Overrides AkamaiClientBase::$apiBaseUrl
AkamaiClientV3::$type protected property Type of purge, either 'url', 'tag' or 'cpcode'. Overrides AkamaiClientBase::$type
AkamaiClientV3::$usesQueue protected property Represents whether this client uses a queuing system or not.
AkamaiClientV3::buildConfigurationForm public function Form constructor. Overrides PluginFormInterface::buildConfigurationForm
AkamaiClientV3::createPurgeBody public function Create an array to pass to Akamai's purge function. Overrides AkamaiClientBase::createPurgeBody
AkamaiClientV3::getSupportedVersions public static function
AkamaiClientV3::purgeRequest protected function Ask the API to purge an object.
AkamaiClientV3::setType public function Sets the type of purge. Overrides AkamaiClientBase::setType
AkamaiClientV3::submitConfigurationForm public function Form submission handler. Overrides PluginFormInterface::submitConfigurationForm
AkamaiClientV3::validActions public function Helper function to validate the actions for purge request.
DependencySerializationTrait::$_entityStorages protected property An array of entity type IDs keyed by the property name of their storages.
DependencySerializationTrait::$_serviceIds protected property An array of service IDs keyed by property name used for serialization.
DependencySerializationTrait::__sleep public function 1
DependencySerializationTrait::__wakeup public function 2
MessengerTrait::$messenger protected property The messenger. 29
MessengerTrait::messenger public function Gets the messenger. 29
MessengerTrait::setMessenger public function Sets the messenger.
PluginBase::$configuration protected property Configuration information passed into the plugin. 1
PluginBase::$pluginDefinition protected property The plugin implementation definition. 1
PluginBase::$pluginId protected property The plugin_id.
PluginBase::DERIVATIVE_SEPARATOR constant A string which is used to separate base plugin IDs from the derivative ID.
PluginBase::getBaseId public function Gets the base_plugin_id of the plugin instance. Overrides DerivativeInspectionInterface::getBaseId
PluginBase::getDerivativeId public function Gets the derivative_id of the plugin instance. Overrides DerivativeInspectionInterface::getDerivativeId
PluginBase::getPluginDefinition public function Gets the definition of the plugin implementation. Overrides PluginInspectionInterface::getPluginDefinition 3
PluginBase::getPluginId public function Gets the plugin_id of the plugin instance. Overrides PluginInspectionInterface::getPluginId
PluginBase::isConfigurable public function Determines if the plugin is configurable.
StringTranslationTrait::$stringTranslation protected property The string translation service. 1
StringTranslationTrait::formatPlural protected function Formats a string containing a count of items.
StringTranslationTrait::getNumberOfPlurals protected function Returns the number of plurals supported by a given language.
StringTranslationTrait::getStringTranslation protected function Gets the string translation service.
StringTranslationTrait::setStringTranslation public function Sets the string translation service to use. 2
StringTranslationTrait::t protected function Translates a string to the current language or to a given language.