You are here

class CloudFlarePurger in CloudFlare 8

CloudFlare purger.

Plugin annotation


@PurgePurger(
  id = "cloudflare",
  label = @Translation("CloudFlare"),
  description = @Translation("Purger for CloudFlare."),
  types = {"tag", "url", "everything"},
  multi_instance = FALSE,
)

Hierarchy

Expanded class hierarchy of CloudFlarePurger

File

modules/cloudflarepurger/src/Plugin/Purge/Purger/CloudFlarePurger.php, line 28

Namespace

Drupal\cloudflarepurger\Plugin\Purge\Purger
View source
class CloudFlarePurger extends PurgerBase implements PurgerInterface {

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

  /**
   * A logger instance.
   *
   * @var \Psr\Log\LoggerInterface
   */
  protected $logger;

  /**
   * Tracks rate limits associated with CloudFlare Api.
   *
   * @var \Drupal\cloudflare\CloudFlareStateInterface
   */
  protected $state;

  /**
   * ZoneApi object for interfacing with CloudFlare Php Sdk.
   *
   * @var \CloudFlarePhpSdk\ApiEndpoints\ZoneApi
   */
  protected $zoneApi;

  /**
   * The current cloudflare ZoneId.
   *
   * @var string
   */
  protected $zone;

  /**
   * TRUE if composer dependencies are met.  False otherwise.
   *
   * @var bool
   */
  protected $areCloudflareComposerDepenciesMet;

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    return new static($configuration, $plugin_id, $plugin_definition, $container
      ->get('config.factory'), $container
      ->get('cloudflare.state'), $container
      ->get('logger.factory')
      ->get('cloudflare'), $container
      ->get('cloudflare.composer_dependency_check'));
  }

  /**
   * Constructs a \Drupal\Component\Plugin\CloudFlarePurger.
   *
   * @param array $configuration
   *   A configuration array containing information about the plugin instance.
   * @param string $plugin_id
   *   The plugin_id for the plugin instance.
   * @param mixed $plugin_definition
   *   The plugin implementation definition.
   * @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
   *   The factory for configuration objects.
   * @param \Drupal\cloudflare\CloudFlareStateInterface $state
   *   Tracks limits associated with CloudFlare Api.
   * @param \Psr\Log\LoggerInterface $logger
   *   A logger instance.
   * @param \Drupal\cloudflare\CloudFlareComposerDependenciesCheckInterface $checker
   *   Tests that composer dependencies are met.
   *
   * @throws \LogicException
   *   Thrown if $configuration['id'] is missing, see Purger\Service::createId.
   */
  public function __construct(array $configuration, $plugin_id, $plugin_definition, ConfigFactoryInterface $config_factory, CloudFlareStateInterface $state, LoggerInterface $logger, CloudFlareComposerDependenciesCheckInterface $checker) {
    parent::__construct($configuration, $plugin_id, $plugin_definition);
    $this->config = $config_factory
      ->get('cloudflare.settings');
    $this->state = $state;
    $this->logger = $logger;
    $this->areCloudflareComposerDepenciesMet = $checker
      ->check();
  }

  /**
   * {@inheritdoc}
   */
  public function routeTypeToMethod($type) {
    $methods = [
      'everything' => 'invalidate',
      'tag' => 'invalidate',
      'url' => 'invalidate',
    ];
    return isset($methods[$type]) ? $methods[$type] : 'invalidate';
  }

  /**
   * {@inheritdoc}
   */
  public function invalidate(array $invalidations) {
    $chunks = array_chunk($invalidations, CloudFlareAPI::MAX_TAG_PURGES_PER_REQUEST);
    $has_invalidations = count($invalidations) > 0;
    if (!$has_invalidations) {
      return;
    }
    foreach ($chunks as $chunk) {
      $this
        ->purgeChunk($chunk);
    }
  }

  /**
   * {@inheritdoc}
   */
  public function hasRuntimeMeasurement() {
    return TRUE;
  }

  /**
   * Purges a chunk of tags.
   *
   * Integration point between purge and CloudFlareAPI.  Purge requires state
   * tracking on each item purged.  This function provides that accounting and
   * calls CloudflareApi.
   *
   * CloudFlare only allows us to purge 30 tags at once.
   *
   * @param array $invalidations
   *   Chunk of purge module invalidation objects to purge via CloudFlare.
   */
  private function purgeChunk(array &$invalidations) {

    // This is a unique case where the ApiSdk is being accessed directly and not
    // via a service.  Purging should only ever happen through the purge module
    // which is why this is NOT in a service.
    $api_key = $this->config
      ->get('apikey');
    $email = $this->config
      ->get('email');
    $this->zone = $this->config
      ->get('zone_id');
    $this->zoneApi = new ZoneApi($api_key, $email);
    $api_targets_to_purge = [];

    // This method is unfortunately a bit verbose due to the fact that we
    // need to update the purge states as we proceed.
    foreach ($invalidations as $invalidation) {
      $invalidation
        ->setState(InvalidationInterface::PROCESSING);
      $api_targets_to_purge[] = $invalidation
        ->getExpression();
    }
    if (!$this->areCloudflareComposerDepenciesMet) {
      foreach ($invalidations as $invalidation) {
        $invalidation
          ->setState(InvalidationInterface::FAILED);
      }
    }
    try {

      // Interface with the CloudFlarePhpSdk.
      $invalidation_type = $invalidations[0]
        ->getPluginId();
      if ($invalidation_type == 'tag') {

        // @todo Remove this wrapper once CloudFlare supports 16k headers.
        // Also invalidate the cache tags as hashes, to automatically also work
        // for responses that exceed CloudFlare's Cache-Tag header limit.
        $hashes = CloudFlareCacheTagHeaderGenerator::cacheTagsToHashes($api_targets_to_purge);
        $this->zoneApi
          ->purgeTags($this->zone, $hashes);
        $this->state
          ->incrementTagPurgeDailyCount();
      }
      elseif ($invalidation_type == 'url') {
        $this->zoneApi
          ->purgeIndividualFiles($this->zone, $api_targets_to_purge);
      }
      elseif ($invalidation_type == 'everything') {
        $this->zoneApi
          ->purgeAllFiles($this->zone);
      }
      foreach ($invalidations as $invalidation) {
        $invalidation
          ->setState(InvalidationInterface::SUCCEEDED);
      }
    } catch (\Exception $e) {
      foreach ($invalidations as $invalidation) {
        $invalidation
          ->setState(InvalidationInterface::FAILED);
      }

      // We only want to log a single watchdog error per request. This prevents
      // the log from being flooded.
      $this->logger
        ->error($e
        ->getMessage());
    } finally {
      $this->state
        ->incrementApiRateCount();
    }
  }

}

Members

Namesort descending Modifiers Type Description Overrides
CloudFlarePurger::$areCloudflareComposerDepenciesMet protected property TRUE if composer dependencies are met. False otherwise.
CloudFlarePurger::$config protected property The settings configuration.
CloudFlarePurger::$logger protected property A logger instance. Overrides PurgeLoggerAwareTrait::$logger
CloudFlarePurger::$state protected property Tracks rate limits associated with CloudFlare Api.
CloudFlarePurger::$zone protected property The current cloudflare ZoneId.
CloudFlarePurger::$zoneApi protected property ZoneApi object for interfacing with CloudFlare Php Sdk.
CloudFlarePurger::create public static function Creates an instance of the plugin. Overrides PurgerBase::create
CloudFlarePurger::hasRuntimeMeasurement public function Indicates whether your purger utilizes dynamic runtime measurement. Overrides PurgerCapacityDataInterface::hasRuntimeMeasurement
CloudFlarePurger::invalidate public function Invalidate content from external caches. Overrides PurgerInterface::invalidate
CloudFlarePurger::purgeChunk private function Purges a chunk of tags.
CloudFlarePurger::routeTypeToMethod public function Route certain type of invalidations to other methods. Overrides PurgerBase::routeTypeToMethod
CloudFlarePurger::__construct public function Constructs a \Drupal\Component\Plugin\CloudFlarePurger. Overrides PurgerBase::__construct
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.
PurgeLoggerAwareTrait::logger public function
PurgerBase::$id protected property Unique instance ID for this purger.
PurgerBase::$runtimeMeasurement protected property The runtime measurement counter.
PurgerBase::delete public function The current instance of this purger plugin is about to be deleted. Overrides PurgerInterface::delete 1
PurgerBase::getCooldownTime public function Get the time in seconds to wait after invalidation. Overrides PurgerCapacityDataInterface::getCooldownTime
PurgerBase::getId public function Retrieve the unique instance ID for this purger instance. Overrides PurgerInterface::getId
PurgerBase::getIdealConditionsLimit public function Get the maximum number of invalidations that this purger can process. Overrides PurgerCapacityDataInterface::getIdealConditionsLimit 1
PurgerBase::getLabel public function Retrieve the user-readable label for this purger instance. Overrides PurgerInterface::getLabel
PurgerBase::getRuntimeMeasurement public function Get the runtime measurement counter. Overrides PurgerCapacityDataInterface::getRuntimeMeasurement
PurgerBase::getTimeHint public function Get the maximum number of seconds, processing a single invalidation takes. Overrides PurgerCapacityDataInterface::getTimeHint
PurgerBase::getTypes public function Retrieve the list of supported invalidation types. Overrides PurgerInterface::getTypes
PurgerBase::setRuntimeMeasurement public function Inject the runtime measurement counter. Overrides PurgerCapacityDataInterface::setRuntimeMeasurement
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.