You are here

final class ReSmushit in Image Optimize reSmush.it 2.x

Same name and namespace in other branches
  1. 8 src/Plugin/ImageAPIOptimizeProcessor/ReSmushit.php \Drupal\imageapi_optimize_resmushit\Plugin\ImageAPIOptimizeProcessor\ReSmushit

Uses the resmush.it webservice to optimize an image.

Plugin annotation


@ImageAPIOptimizeProcessor(
  id = "resmushit",
  label = @Translation("Resmush.it"),
  description = @Translation("Uses the free resmush.it service to optimize images.")
)

Hierarchy

Expanded class hierarchy of ReSmushit

File

src/Plugin/ImageAPIOptimizeProcessor/ReSmushit.php, line 23

Namespace

Drupal\imageapi_optimize_resmushit\Plugin\ImageAPIOptimizeProcessor
View source
final class ReSmushit extends ConfigurableImageAPIOptimizeProcessorBase {

  /**
   * The HTTP client to fetch the feed data with.
   *
   * @var \GuzzleHttp\ClientInterface
   */
  protected $httpClient;

  /**
   * {@inheritdoc}
   */
  public function __construct(array $configuration, $plugin_id, $plugin_definition, LoggerInterface $logger, ImageFactory $image_factory, ClientInterface $http_client) {
    parent::__construct($configuration, $plugin_id, $plugin_definition, $logger, $image_factory);
    $this->httpClient = $http_client;
  }

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

  /**
   * {@inheritdoc}
   */
  public function applyToImage($image_uri) {

    // Need to send the file off to the remote service and await a response.
    $fields[] = [
      'name' => 'files',
      'contents' => fopen($image_uri, 'r'),
    ];
    if (!empty($this->configuration['quality'])) {
      $fields[] = [
        'name' => 'qlty',
        'contents' => $this->configuration['quality'],
      ];
    }
    try {
      $response = $this->httpClient
        ->post('http://api.resmush.it/ws.php', [
        'multipart' => $fields,
      ]);
      $body = $response
        ->getBody();
      $json = json_decode($body);

      // If this has worked, we should get a dest entry in the JSON returned.
      if (isset($json->dest)) {

        // Now go fetch that, and save it locally.
        $smushedFile = $this->httpClient
          ->get($json->dest);
        if ($smushedFile
          ->getStatusCode() == 200) {
          \Drupal::service('file_system')
            ->saveData($smushedFile
            ->getBody(), $image_uri, FileSystemInterface::EXISTS_REPLACE);
          return TRUE;
        }
      }
    } catch (RequestException $e) {
      $this->logger
        ->error('Failed to download optimize image using reSmush.it due to "%error".', [
        '%error' => $e
          ->getMessage(),
      ]);
    }
    return FALSE;
  }

  /**
   * {@inheritdoc}
   */
  public function defaultConfiguration() {
    return [
      'quality' => NULL,
    ];
  }

  /**
   * {@inheritdoc}
   */
  public function buildConfigurationForm(array $form, FormStateInterface $form_state) {
    $form['quality'] = [
      '#type' => 'number',
      '#title' => $this
        ->t('JPEG image quality'),
      '#description' => $this
        ->t('Optionally specify a quality setting when optimizing JPEG images.'),
      '#default_value' => $this->configuration['quality'],
      '#min' => 1,
      '#max' => 100,
    ];
    return $form;
  }

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

}

Members

Namesort descending Modifiers Type Description Overrides
ConfigurableImageAPIOptimizeProcessorBase::validateConfigurationForm public function Form validation handler. Overrides PluginFormInterface::validateConfigurationForm
DependencySerializationTrait::$_entityStorages protected property
DependencySerializationTrait::$_serviceIds protected property
DependencySerializationTrait::__sleep public function 2
DependencySerializationTrait::__wakeup public function 2
ImageAPIOptimizeProcessorBase::$imageFactory protected property The image factory.
ImageAPIOptimizeProcessorBase::$logger protected property A logger instance.
ImageAPIOptimizeProcessorBase::$uuid protected property The image optimize processor ID.
ImageAPIOptimizeProcessorBase::$weight protected property The weight of the image optimize processor.
ImageAPIOptimizeProcessorBase::calculateDependencies public function Calculates dependencies for the configured plugin. Overrides DependentPluginInterface::calculateDependencies
ImageAPIOptimizeProcessorBase::getConfiguration public function Gets this plugin's configuration. Overrides ConfigurableInterface::getConfiguration
ImageAPIOptimizeProcessorBase::getMimeType protected function
ImageAPIOptimizeProcessorBase::getSummary public function Returns a render array summarizing the configuration of the image optimize processor. Overrides ImageAPIOptimizeProcessorInterface::getSummary
ImageAPIOptimizeProcessorBase::getUuid public function Returns the unique ID representing the image optimize processor. Overrides ImageAPIOptimizeProcessorInterface::getUuid
ImageAPIOptimizeProcessorBase::getWeight public function Returns the weight of the image optimize processor. Overrides ImageAPIOptimizeProcessorInterface::getWeight
ImageAPIOptimizeProcessorBase::label public function Returns the image optimize processor label. Overrides ImageAPIOptimizeProcessorInterface::label
ImageAPIOptimizeProcessorBase::setConfiguration public function Sets the configuration for this plugin instance. Overrides ConfigurableInterface::setConfiguration
ImageAPIOptimizeProcessorBase::setWeight public function Sets the weight for this image optimize processor. Overrides ImageAPIOptimizeProcessorInterface::setWeight
MessengerTrait::$messenger protected property The messenger. 27
MessengerTrait::messenger public function Gets the messenger. 27
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 2
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.
ReSmushit::$httpClient protected property The HTTP client to fetch the feed data with.
ReSmushit::applyToImage public function Apply this image optimize processor to the given image. Overrides ImageAPIOptimizeProcessorInterface::applyToImage
ReSmushit::buildConfigurationForm public function Form constructor. Overrides PluginFormInterface::buildConfigurationForm
ReSmushit::create public static function Creates an instance of the plugin. Overrides ImageAPIOptimizeProcessorBase::create
ReSmushit::defaultConfiguration public function Gets default configuration for this plugin. Overrides ImageAPIOptimizeProcessorBase::defaultConfiguration
ReSmushit::submitConfigurationForm public function Form submission handler. Overrides ConfigurableImageAPIOptimizeProcessorBase::submitConfigurationForm
ReSmushit::__construct public function Constructs a \Drupal\Component\Plugin\PluginBase object. Overrides ImageAPIOptimizeProcessorBase::__construct
StringTranslationTrait::$stringTranslation protected property The string translation service. 4
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.