Version 1
[yaffs-website] / web / core / modules / image / src / Plugin / ImageEffect / ConvertImageEffect.php
1 <?php
2
3 namespace Drupal\image\Plugin\ImageEffect;
4
5 use Drupal\Component\Utility\Unicode;
6 use Drupal\Core\Form\FormStateInterface;
7 use Drupal\Core\Image\ImageInterface;
8 use Drupal\image\ConfigurableImageEffectBase;
9
10 /**
11  * Converts an image resource.
12  *
13  * @ImageEffect(
14  *   id = "image_convert",
15  *   label = @Translation("Convert"),
16  *   description = @Translation("Converts an image between extensions (e.g. from PNG to JPEG).")
17  * )
18  */
19 class ConvertImageEffect extends ConfigurableImageEffectBase {
20
21   /**
22    * {@inheritdoc}
23    */
24   public function applyEffect(ImageInterface $image) {
25     if (!$image->convert($this->configuration['extension'])) {
26       $this->logger->error('Image convert failed using the %toolkit toolkit on %path (%mimetype)', ['%toolkit' => $image->getToolkitId(), '%path' => $image->getSource(), '%mimetype' => $image->getMimeType()]);
27       return FALSE;
28     }
29     return TRUE;
30   }
31
32   /**
33    * {@inheritdoc}
34    */
35   public function getDerivativeExtension($extension) {
36     return $this->configuration['extension'];
37   }
38
39   /**
40    * {@inheritdoc}
41    */
42   public function getSummary() {
43     $summary = [
44       '#markup' => Unicode::strtoupper($this->configuration['extension']),
45     ];
46     $summary += parent::getSummary();
47
48     return $summary;
49   }
50
51   /**
52    * {@inheritdoc}
53    */
54   public function defaultConfiguration() {
55     return [
56       'extension' => NULL,
57     ];
58   }
59
60   /**
61    * {@inheritdoc}
62    */
63   public function buildConfigurationForm(array $form, FormStateInterface $form_state) {
64     $extensions = \Drupal::service('image.toolkit.manager')->getDefaultToolkit()->getSupportedExtensions();
65     $options = array_combine(
66       $extensions,
67       array_map(['\Drupal\Component\Utility\Unicode', 'strtoupper'], $extensions)
68     );
69     $form['extension'] = [
70       '#type' => 'select',
71       '#title' => t('Extension'),
72       '#default_value' => $this->configuration['extension'],
73       '#required' => TRUE,
74       '#options' => $options,
75     ];
76     return $form;
77   }
78
79   /**
80    * {@inheritdoc}
81    */
82   public function submitConfigurationForm(array &$form, FormStateInterface $form_state) {
83     parent::submitConfigurationForm($form, $form_state);
84     $this->configuration['extension'] = $form_state->getValue('extension');
85   }
86
87 }