cloudflare_image_style-8.x-1.x-dev/cloudflare_image_style.module
cloudflare_image_style.module
<?php
/**
* @file
* Module file.
*/
use Drupal\Core\Form\FormStateInterface;
use Drupal\image\Entity\ImageStyle;
/**
* Implements hook_form_FORM_ID_alter().
*/
function cloudflare_image_style_form_image_style_edit_form_alter(&$form, FormStateInterface $form_state, $form_id) {
$style = \Drupal::config('image.style.' . $form['name']['#default_value']);
$form['serve_from_cf'] = [
'#type' => 'select',
'#title' => t('Serve from Cloudflare'),
'#description' => t('Service styled images from Cloudflare. Only available for enterprise customers.'),
'#options' => [
1 => t('Yes'),
0 => t('No'),
],
'#default_value' => $style->get('serve_from_cf') ?? 0,
];
$form['cf_effect'] = [
'#type' => 'textfield',
'#title' => t('Cloudflare Effect'),
'#description' => t('Enter the effect to use for serving images via Cloudflare.'),
'#default_value' => $style->get('cf_effect') ?? '',
'#states' => [
'visible' => [
'select[name="serve_from_cf"]' => ['value' => 1],
],
],
];
$form['actions']['submit']['#submit'][] = 'cloudflare_image_style_form_image_style_edit_form_submit';
}
/**
* Submit callback for image style edit form.
*
* Here we will save our custom fields data in config.
*
* @param array $form
* Form array.
* @param \Drupal\Core\Form\FormStateInterface $form_state
* Form state object.
*/
function cloudflare_image_style_form_image_style_edit_form_submit(array &$form, FormStateInterface &$form_state) {
$style = \Drupal::configFactory()->getEditable('image.style.' . $form_state->getValue('name'));
$style->set('serve_from_cf', $form_state->getValue('serve_from_cf'));
$style->set('cf_effect', $form_state->getValue('cf_effect'));
$style->save();
}
/**
* Implements hook_theme_registry_alter().
*/
function cloudflare_image_style_theme_registry_alter(&$theme_registry) {
$theme_registry['image_style']['preprocess functions'][] = 'cloudflare_image_style_preprocess_image_style';
}
/**
* Implements template_preprocess_theme().
*/
function cloudflare_image_style_preprocess_image_style(&$variables) {
/** @var \Drupal\image\Entity\ImageStyle $style */
$style = \Drupal::entityTypeManager()->getStorage('image_style')->load($variables['style_name']);
// Sanity check, do nothing if image style name not valid.
// Error handling will be done by CORE code.
if (!($style instanceof ImageStyle)) {
return;
}
// Get effect from image style if applicable.
$cf_effect = $style->get('serve_from_cf') ? $style->get('cf_effect') : '';
if (!empty($cf_effect)) {
$variables['image']['#uri'] = '/cdn-cgi/image/' . $cf_effect;
$variables['image']['#uri'] .= '/' . \Drupal::service('stream_wrapper_manager')->getTarget($variables['uri']);
}
}
