You are here

tinypng.module in TinyPNG 8

Same filename and directory in other branches
  1. 7 tinypng.module

TinyPng module.

File

tinypng.module
View source
<?php

/**
 * @file
 * TinyPng module.
 */
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\image\ImageStyleInterface;

/**
 * Implements hook_entity_presave().
 *
 * Process the image with TinyPNG service.
 */
function tinypng_entity_presave(EntityInterface $entity) {

  /** @var \Drupal\tinypng\TinyPngImageHandlerInterface $service */
  $service = \Drupal::service('tinypng.image_handler');
  $service
    ->hookEntityPresave($entity);
}

/**
 * Implements hook_form_FORM_ID_alter().
 */
function tinypng_form_image_style_edit_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  $config = \Drupal::config('tinypng.settings');
  if (empty($config
    ->get('api_key')) || empty($config
    ->get('image_action'))) {
    return;
  }

  /** @var \Drupal\image\Form\ImageStyleEditForm $form_object */
  $form_object = $form_state
    ->getFormObject();

  /** @var \Drupal\image\Entity\ImageStyle $image_style */
  $image_style = $form_object
    ->getEntity();
  $form['tinypng_compress'] = [
    '#type' => 'checkbox',
    '#title' => t('Compress with TinyPNG', [], [
      'context' => 'tinypng',
    ]),
    '#default_value' => $image_style
      ->getThirdPartySetting('tinypng', 'tinypng_compress'),
    '#weight' => $form['effects']['#weight'] + 0.1,
  ];
  $form['#entity_builders'][] = 'tinypng_image_style_edit_form_builder';
}

/**
 * Entity form builder to add the TinyPNG settings to ImageStyle.
 *
 * @param string $entity_type_id
 *   Entity type ID.
 * @param \Drupal\image\ImageStyleInterface $image_style
 *   Edited ImageStyle instance.
 * @param array $form
 *   Entity form to alter.
 * @param \Drupal\Core\Form\FormStateInterface $form_state
 *   Form state.
 *
 * @throws \Drupal\Core\Entity\EntityStorageException
 */
function tinypng_image_style_edit_form_builder($entity_type_id, ImageStyleInterface $image_style, array &$form, FormStateInterface $form_state) {
  $image_style
    ->setThirdPartySetting('tinypng', 'tinypng_compress', $form_state
    ->getValue('tinypng_compress'));
  $image_style
    ->save();
}

Functions

Namesort descending Description
tinypng_entity_presave Implements hook_entity_presave().
tinypng_form_image_style_edit_form_alter Implements hook_form_FORM_ID_alter().
tinypng_image_style_edit_form_builder Entity form builder to add the TinyPNG settings to ImageStyle.