final class CdnWarmer in Warmer 2.x
Same name and namespace in other branches
- 8 modules/warmer_cdn/src/Plugin/warmer/CdnWarmer.php \Drupal\warmer_cdn\Plugin\warmer\CdnWarmer
The cache warmer for the built-in entity cache.
Plugin annotation
@Warmer(
id = "cdn",
label = @Translation("CDN"),
description = @Translation("Executes HTTP requests to warm the edge caches. It is useful without a CDN as well, as it will also warm Varnish and Page Cache.")
)
Hierarchy
- class \Drupal\Component\Plugin\PluginBase implements DerivativeInspectionInterface, PluginInspectionInterface
- class \Drupal\Core\Plugin\PluginBase uses DependencySerializationTrait, MessengerTrait, StringTranslationTrait
- class \Drupal\warmer\Plugin\WarmerPluginBase implements ConfigurableInterface, DependentPluginInterface, ContainerFactoryPluginInterface, PluginFormInterface, WarmerInterface
- class \Drupal\warmer_cdn\Plugin\warmer\CdnWarmer uses LoggerChannelTrait, UserInputParserTrait
- class \Drupal\warmer\Plugin\WarmerPluginBase implements ConfigurableInterface, DependentPluginInterface, ContainerFactoryPluginInterface, PluginFormInterface, WarmerInterface
- class \Drupal\Core\Plugin\PluginBase uses DependencySerializationTrait, MessengerTrait, StringTranslationTrait
Expanded class hierarchy of CdnWarmer
File
- modules/
warmer_cdn/ src/ Plugin/ warmer/ CdnWarmer.php, line 23
Namespace
Drupal\warmer_cdn\Plugin\warmerView source
final class CdnWarmer extends WarmerPluginBase {
use UserInputParserTrait;
use LoggerChannelTrait;
/**
* The HTTP client.
*
* @var \GuzzleHttp\ClientInterface
*/
private $httpClient;
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
$instance = parent::create($container, $configuration, $plugin_id, $plugin_definition);
assert($instance instanceof CdnWarmer);
$instance
->setHttpClient($container
->get('http_client'));
return $instance;
}
/**
* {@inheritdoc}
*/
public function loadMultiple(array $ids = []) {
// Ensure items are fully loaded URLs.
$urls = array_map([
$this,
'resolveUri',
], $ids);
return array_filter($urls, [
UrlHelper::class,
'isValid',
]);
}
/**
* {@inheritdoc}
*/
public function warmMultiple(array $items = []) {
$headers = $this
->parseHeaders();
$verify = (bool) $this
->getConfiguration()['verify'];
$max_concurrent_requests = (int) $this
->getConfiguration()['maxConcurrentRequests'];
// Default to one request at a time.
if ($max_concurrent_requests <= 0) {
$max_concurrent_requests = 1;
}
$promises = [];
$success = 0;
foreach ($items as $key => $url) {
// Fire async request.
$promises[] = $this->httpClient
->requestAsync('GET', $url, [
'headers' => $headers,
'verify' => $verify,
])
->then(function (ResponseInterface $response) use (&$success) {
if ($response
->getStatusCode() < 399) {
$success++;
}
}, function (\Exception $e) {
$this
->getLogger('warmer')
->warning($e
->getMessage());
});
// Wait for all fired requests if max number is reached.
$item_keys = array_keys($items);
if ($key % $max_concurrent_requests == 0 || $key == end($item_keys)) {
\GuzzleHttp\Promise\all($promises)
->wait();
$promises = [];
}
}
return $success;
}
/**
* Parses the configuration to extract the headers to inject in every request.
*
* @return array
* The array of headers as expected by Guzzle.
*/
private function parseHeaders() {
$configuration = $this
->getConfiguration();
$header_lines = $configuration['headers'];
// Parse headers.
return array_reduce($header_lines, function ($carry, $header_line) {
list($name, $value_line) = array_map('trim', explode(':', $header_line));
$values = array_map('trim', explode(';', $value_line));
$values = array_filter($values);
$values = count($values) === 1 ? reset($values) : $values;
$carry[$name] = $values;
return $carry;
}, []);
}
/**
* {@inheritdoc}
*/
public function buildIdsBatch($cursor) {
// Parse the sitemaps and extract the URLs.
$config = $this
->getConfiguration();
$urls = empty($config['urls']) ? [] : $config['urls'];
$cursor_position = is_null($cursor) ? -1 : array_search($cursor, $urls);
if ($cursor_position === FALSE) {
return [];
}
return array_slice($urls, $cursor_position + 1, (int) $this
->getBatchSize());
}
/**
* {@inheritdoc}
*/
public function validateConfigurationForm(array &$form, FormStateInterface $form_state) {
parent::validateConfigurationForm($form, $form_state);
$this
->validateHeaders($form, $form_state);
}
/**
* {@inheritdoc}
*/
public function addMoreConfigurationFormElements(array $form, SubformStateInterface $form_state) {
$configuration = $this
->getConfiguration();
$form['urls'] = [
'#type' => 'textarea',
'#title' => $this
->t('URLs'),
'#description' => $this
->t('Enter the list of URLs. One on each line. Examples: https://example.org/foo/bar, /foo/bar.'),
'#default_value' => empty($configuration['urls']) ? '' : implode("\n", $configuration['urls']),
];
$form['headers'] = [
'#type' => 'textarea',
'#title' => $this
->t('Headers'),
'#description' => $this
->t('Specific headers to use when making HTTP requests. Format: <code>Header-Name: value1; value2</code>'),
'#default_value' => empty($configuration['headers']) ? '' : implode("\n", $configuration['headers']),
];
$form['verify'] = [
'#type' => 'checkbox',
'#title' => $this
->t('Enable SSL verification'),
'#description' => $this
->t('Enable SSL verification. Recommended to keep it checked for security reasons.'),
'#default_value' => isset($configuration['verify']) ? $configuration['verify'] : TRUE,
];
$form['maxConcurrentRequests'] = [
'#type' => 'number',
'#min' => 1,
'#step' => 1,
'#title' => $this
->t('Maximum number of concurrent Requests.'),
'#description' => $this
->t('The maximum number of concurrent requests.'),
'#default_value' => empty($configuration['maxConcurrentRequests']) ? 10 : $configuration['maxConcurrentRequests'],
];
return $form;
}
/**
* {@inheritdoc}
*/
public function submitConfigurationForm(array &$form, FormStateInterface $form_state) {
$configuration = $form_state
->getValues() + $this->configuration;
$configuration['urls'] = $this
->extractTextarea($configuration, 'urls');
$configuration['headers'] = $this
->extractTextarea($configuration, 'headers');
$this
->setConfiguration($configuration);
}
/**
* Set the HTTP client.
*
* @param \GuzzleHttp\ClientInterface $client
* The client.
*/
public function setHttpClient(ClientInterface $client) {
$this->httpClient = $client;
}
/**
* {@inheritdoc}
*/
public function defaultConfiguration() {
return [
'maxConcurrentRequests' => 10,
] + parent::defaultConfiguration();
}
}
Members
Name | Modifiers | Type | Description | Overrides |
---|---|---|---|---|
CdnWarmer:: |
private | property | The HTTP client. | |
CdnWarmer:: |
public | function |
Adds additional form elements to the configuration form. Overrides WarmerInterface:: |
|
CdnWarmer:: |
public | function |
Builds the next batch of IDs based on a position cursor. Overrides WarmerInterface:: |
|
CdnWarmer:: |
public static | function |
Creates an instance of the plugin. Overrides WarmerPluginBase:: |
|
CdnWarmer:: |
public | function |
Gets default configuration for this plugin. Overrides WarmerPluginBase:: |
|
CdnWarmer:: |
public | function |
Loads multiple items based on their IDs. Overrides WarmerInterface:: |
|
CdnWarmer:: |
private | function | Parses the configuration to extract the headers to inject in every request. | |
CdnWarmer:: |
public | function | Set the HTTP client. | |
CdnWarmer:: |
public | function |
Form submission handler. Overrides WarmerPluginBase:: |
|
CdnWarmer:: |
public | function |
Form validation handler. Overrides WarmerPluginBase:: |
|
CdnWarmer:: |
public | function |
Warms multiple items. Overrides WarmerInterface:: |
|
DependencySerializationTrait:: |
protected | property | ||
DependencySerializationTrait:: |
protected | property | ||
DependencySerializationTrait:: |
public | function | 2 | |
DependencySerializationTrait:: |
public | function | 2 | |
LoggerChannelTrait:: |
protected | property | The logger channel factory service. | |
LoggerChannelTrait:: |
protected | function | Gets the logger for a specific channel. | |
LoggerChannelTrait:: |
public | function | Injects the logger channel factory. | |
MessengerTrait:: |
protected | property | The messenger. | 27 |
MessengerTrait:: |
public | function | Gets the messenger. | 27 |
MessengerTrait:: |
public | function | Sets the messenger. | |
PluginBase:: |
protected | property | Configuration information passed into the plugin. | 1 |
PluginBase:: |
protected | property | The plugin implementation definition. | 1 |
PluginBase:: |
protected | property | The plugin_id. | |
PluginBase:: |
constant | A string which is used to separate base plugin IDs from the derivative ID. | ||
PluginBase:: |
public | function |
Gets the base_plugin_id of the plugin instance. Overrides DerivativeInspectionInterface:: |
|
PluginBase:: |
public | function |
Gets the derivative_id of the plugin instance. Overrides DerivativeInspectionInterface:: |
|
PluginBase:: |
public | function |
Gets the definition of the plugin implementation. Overrides PluginInspectionInterface:: |
2 |
PluginBase:: |
public | function |
Gets the plugin_id of the plugin instance. Overrides PluginInspectionInterface:: |
|
PluginBase:: |
public | function | Determines if the plugin is configurable. | |
StringTranslationTrait:: |
protected | property | The string translation service. | 4 |
StringTranslationTrait:: |
protected | function | Formats a string containing a count of items. | |
StringTranslationTrait:: |
protected | function | Returns the number of plurals supported by a given language. | |
StringTranslationTrait:: |
protected | function | Gets the string translation service. | |
StringTranslationTrait:: |
public | function | Sets the string translation service to use. | 2 |
StringTranslationTrait:: |
protected | function | Translates a string to the current language or to a given language. | |
UserInputParserTrait:: |
private | function | Parses the string under $key in the $values collection. | |
UserInputParserTrait:: |
private | function | Resolves a URI into a fully loaded URL. | |
UserInputParserTrait:: |
private | function | Validate the input for the headers. | |
WarmerPluginBase:: |
protected | property | The state service. | |
WarmerPluginBase:: |
protected | property | The time service. | |
WarmerPluginBase:: |
final public | function |
Form constructor. Overrides PluginFormInterface:: |
|
WarmerPluginBase:: |
public | function |
Calculates dependencies for the configured plugin. Overrides DependentPluginInterface:: |
|
WarmerPluginBase:: |
public | function |
Returns the batch size for the warming operation. Overrides WarmerInterface:: |
|
WarmerPluginBase:: |
public | function |
Gets this plugin's configuration. Overrides ConfigurableInterface:: |
|
WarmerPluginBase:: |
public | function |
Returns the frequency for the warming operation. Overrides WarmerInterface:: |
|
WarmerPluginBase:: |
public | function |
Checks if the plugin should warm in this particular moment. Overrides WarmerInterface:: |
|
WarmerPluginBase:: |
public | function |
Marks a warmer as enqueued. Overrides WarmerInterface:: |
|
WarmerPluginBase:: |
public | function |
Sets the configuration for this plugin instance. Overrides ConfigurableInterface:: |
|
WarmerPluginBase:: |
public | function |
Constructs a \Drupal\Component\Plugin\PluginBase object. Overrides PluginBase:: |