You are here

class AspectSwitcherImageEffect in Image Effects 8

Same name and namespace in other branches
  1. 8.3 src/Plugin/ImageEffect/AspectSwitcherImageEffect.php \Drupal\image_effects\Plugin\ImageEffect\AspectSwitcherImageEffect
  2. 8.2 src/Plugin/ImageEffect/AspectSwitcherImageEffect.php \Drupal\image_effects\Plugin\ImageEffect\AspectSwitcherImageEffect

Choose image styles to apply based on source image orientation.

Plugin annotation


@ImageEffect(
  id = "image_effects_aspect_switcher",
  label = @Translation("Aspect switcher"),
  description = @Translation("Choose image styles to use depending on the orientation of the source image (landscape/protrait).")
)

Hierarchy

Expanded class hierarchy of AspectSwitcherImageEffect

File

src/Plugin/ImageEffect/AspectSwitcherImageEffect.php, line 19

Namespace

Drupal\image_effects\Plugin\ImageEffect
View source
class AspectSwitcherImageEffect extends ConfigurableImageEffectBase {

  /**
   * {@inheritdoc}
   */
  public function defaultConfiguration() {
    return [
      'landscape_image_style' => '',
      'portrait_image_style' => '',
      'ratio_adjustment' => 1,
    ];
  }

  /**
   * {@inheritdoc}
   */
  public function getSummary() {
    $data = $this->configuration;
    if ($portrait_image_style = $this
      ->failSafeGetImageStyle($this->configuration['portrait_image_style'])) {
      $data['portrait'] = $portrait_image_style
        ->label();
    }
    else {
      $data['portrait'] = $this
        ->t("(none)");
    }
    if ($landscape_image_style = $this
      ->failSafeGetImageStyle($this->configuration['landscape_image_style'])) {
      $data['landscape'] = $landscape_image_style
        ->label();
    }
    else {
      $data['landscape'] = $this
        ->t("(none)");
    }
    return [
      '#theme' => 'image_effects_aspect_switcher',
      '#data' => $data,
    ] + parent::getSummary();
  }

  /**
   * {@inheritdoc}
   */
  public function calculateDependencies() {
    $image_styles = [];
    if ($portrait_image_style = $this
      ->failSafeGetImageStyle($this->configuration['portrait_image_style'])) {
      $image_styles[] = $portrait_image_style
        ->getConfigDependencyName();
    }
    if ($landscape_image_style = $this
      ->failSafeGetImageStyle($this->configuration['landscape_image_style'])) {
      $image_styles[] = $landscape_image_style
        ->getConfigDependencyName();
    }
    return [
      'config' => $image_styles,
    ];
  }

  /**
   * {@inheritdoc}
   */
  public function buildConfigurationForm(array $form, FormStateInterface $form_state) {
    $form['info'] = [
      '#type' => 'details',
      '#title' => $this
        ->t('Information'),
    ];
    $form['info']['help'] = [
      '#markup' => $this
        ->t("'Convert' effects included in the image style specified will not be effective. It is not possible to change the image format based on the aspect. If you need to change the image format, you will have to add a 'Convert' effect in this image style."),
    ];
    $form['landscape_image_style'] = [
      '#type' => 'entity_autocomplete',
      '#title' => $this
        ->t('Landscape image style'),
      '#target_type' => 'image_style',
      '#default_value' => $this
        ->failSafeGetImageStyle($this->configuration['landscape_image_style']),
      '#description' => $this
        ->t("Leave empty to avoid switching."),
    ];
    $form['portrait_image_style'] = [
      '#type' => 'entity_autocomplete',
      '#title' => $this
        ->t('Portrait image style'),
      '#target_type' => 'image_style',
      '#default_value' => $this
        ->failSafeGetImageStyle($this->configuration['portrait_image_style']),
      '#description' => $this
        ->t("Leave empty to avoid switching."),
    ];
    $form['ratio_adjustment'] = [
      '#type' => 'number',
      '#title' => t('Ratio adjustment (advanced)'),
      '#required' => TRUE,
      '#size' => 7,
      '#min' => 0,
      '#max' => 5,
      '#step' => 0.01,
      '#default_value' => $this->configuration['ratio_adjustment'],
      '#description' => $this
        ->t("This allows you to bend the rules for how different the proportions need to be to trigger the switch.") . "<br/>" . $this
        ->t("If n = (width/height)*ratio is greater than 1, use 'landscape', otherwise use 'portrait'.") . "<br/>" . $this
        ->t("When ratio = 1 (the default) it will just switch between portrait and landscape modes."),
    ];
    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function validateConfigurationForm(array &$form, FormStateInterface $form_state) {
    parent::validateConfigurationForm($form, $form_state);
    if ($form_state
      ->getValue('portrait_image_style') === NULL && $form_state
      ->getValue('landscape_image_style') === NULL) {
      $form_state
        ->setErrorByName('portrait_image_style', $this
        ->t("At least one of 'Landscape image style' or 'Portrait image style' must be selected."));
      $form_state
        ->setErrorByName('landscape_image_style', $this
        ->t("At least one of 'Landscape image style' or 'Portrait image style' must be selected."));
    }
    if ($this
      ->failSafeGetImageStyle($form_state
      ->getValue('portrait_image_style')) === FALSE) {
      $form_state
        ->setErrorByName('portrait_image_style', $this
        ->t("The image style does not exist."));
    }
    if ($this
      ->failSafeGetImageStyle($form_state
      ->getValue('landscape_image_style')) === FALSE) {
      $form_state
        ->setErrorByName('landscape_image_style', $this
        ->t("The image style does not exist."));
    }

    // @todo at the moment it is not possible to validate the style selected
    // not being a circular reference to the current style itself.
    // @see https://www.drupal.org/node/1826362
  }

  /**
   * {@inheritdoc}
   */
  public function submitConfigurationForm(array &$form, FormStateInterface $form_state) {
    parent::submitConfigurationForm($form, $form_state);
    $this->configuration['portrait_image_style'] = $form_state
      ->getValue('portrait_image_style');
    $this->configuration['landscape_image_style'] = $form_state
      ->getValue('landscape_image_style');
    $this->configuration['ratio_adjustment'] = $form_state
      ->getValue('ratio_adjustment');
  }

  /**
   * {@inheritdoc}
   */
  public function applyEffect(ImageInterface $image) {
    $style_name = $this
      ->getChildImageStyleToExecute($image
      ->getWidth(), $image
      ->getHeight());
    $style = $this
      ->failSafeGetImageStyle($style_name);

    // No child style to process.
    if ($style === NULL) {
      return TRUE;
    }

    // Child style to process missing.
    if ($style === FALSE) {
      return FALSE;
    }
    foreach ($style
      ->getEffects() as $effect) {
      $effect
        ->applyEffect($image);
    }
    return TRUE;
  }

  /**
   * {@inheritdoc}
   */
  public function transformDimensions(array &$dimensions, $uri) {
    $style_name = $this
      ->getChildImageStyleToExecute($dimensions['width'], $dimensions['height']);
    $style = $this
      ->failSafeGetImageStyle($style_name);

    // No or missing child style to process.
    if (!$style) {
      return;
    }
    foreach ($style
      ->getEffects() as $effect) {
      $effect
        ->transformDimensions($dimensions, $uri);
    }
  }

  /**
   * Gets the name of the child image style to process based on image aspect.
   *
   * @param int $width
   *   The width of the image.
   * @param int $height
   *   The height of the image.
   *
   * @return string
   *   The name of the image style to process.
   */
  protected function getChildImageStyleToExecute($width, $height) {
    $ratio_adjustment = isset($this->configuration['ratio_adjustment']) ? floatval($this->configuration['ratio_adjustment']) : 1;

    // Width / height * adjustment. If > 1, it's wide.
    return $width / $height * $ratio_adjustment > 1 ? $this->configuration['landscape_image_style'] : $this->configuration['portrait_image_style'];
  }

  /**
   * Gets an image style object.
   *
   * @param string $image_style_name
   *   The name of the image style to get.
   *
   * @return \Drupal\image\Entity\ImageStyle|null|false
   *   The image style object, or NULL if the name is NULL, or FALSE if the
   *   image style went missing from the db.
   */
  protected function failSafeGetImageStyle($image_style_name) {
    if ($image_style_name === NULL) {
      return NULL;
    }
    $image_style = ImageStyle::load($image_style_name);
    if ($image_style === NULL) {

      // Required style has gone missing?
      $this->logger
        ->error("Cannot find image style '%style_name' to execute an 'aspect switcher' effect.", [
        '%style_name' => $image_style_name,
      ]);
      return FALSE;
    }
    return $image_style;
  }

}

Members

Namesort descending Modifiers Type Description Overrides
AspectSwitcherImageEffect::applyEffect public function Applies an image effect to the image object. Overrides ImageEffectInterface::applyEffect
AspectSwitcherImageEffect::buildConfigurationForm public function Form constructor. Overrides PluginFormInterface::buildConfigurationForm
AspectSwitcherImageEffect::calculateDependencies public function Calculates dependencies for the configured plugin. Overrides ImageEffectBase::calculateDependencies
AspectSwitcherImageEffect::defaultConfiguration public function Gets default configuration for this plugin. Overrides ImageEffectBase::defaultConfiguration
AspectSwitcherImageEffect::failSafeGetImageStyle protected function Gets an image style object.
AspectSwitcherImageEffect::getChildImageStyleToExecute protected function Gets the name of the child image style to process based on image aspect.
AspectSwitcherImageEffect::getSummary public function Returns a render array summarizing the configuration of the image effect. Overrides ImageEffectBase::getSummary
AspectSwitcherImageEffect::submitConfigurationForm public function Form submission handler. Overrides ConfigurableImageEffectBase::submitConfigurationForm
AspectSwitcherImageEffect::transformDimensions public function Determines the dimensions of the styled image. Overrides ImageEffectBase::transformDimensions
AspectSwitcherImageEffect::validateConfigurationForm public function Form validation handler. Overrides ConfigurableImageEffectBase::validateConfigurationForm
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
ImageEffectBase::$logger protected property A logger instance.
ImageEffectBase::$uuid protected property The image effect ID.
ImageEffectBase::$weight protected property The weight of the image effect.
ImageEffectBase::create public static function Creates an instance of the plugin. Overrides ContainerFactoryPluginInterface::create
ImageEffectBase::getConfiguration public function Gets this plugin's configuration. Overrides ConfigurableInterface::getConfiguration
ImageEffectBase::getDerivativeExtension public function Returns the extension of the derivative after applying this image effect. Overrides ImageEffectInterface::getDerivativeExtension 1
ImageEffectBase::getUuid public function Returns the unique ID representing the image effect. Overrides ImageEffectInterface::getUuid
ImageEffectBase::getWeight public function Returns the weight of the image effect. Overrides ImageEffectInterface::getWeight
ImageEffectBase::label public function Returns the image effect label. Overrides ImageEffectInterface::label
ImageEffectBase::setConfiguration public function Sets the configuration for this plugin instance. Overrides ConfigurableInterface::setConfiguration
ImageEffectBase::setWeight public function Sets the weight for this image effect. Overrides ImageEffectInterface::setWeight
ImageEffectBase::__construct public function Constructs a \Drupal\Component\Plugin\PluginBase object. Overrides PluginBase::__construct
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.