Updated all the contrib modules to their latest versions.
[yaffs-website] / web / modules / contrib / image_widget_crop / src / Plugin / Field / FieldWidget / ImageCropWidget.php
1 <?php
2
3 namespace Drupal\image_widget_crop\Plugin\Field\FieldWidget;
4
5 use Drupal\Core\Ajax\AjaxResponse;
6 use Drupal\Core\Ajax\ReplaceCommand;
7 use Drupal\Core\Config\ConfigFactoryInterface;
8 use Drupal\Core\Config\Entity\ConfigEntityStorageInterface;
9 use Drupal\Core\Entity\EntityStorageInterface;
10 use Drupal\Core\Field\FieldDefinitionInterface;
11 use Drupal\Core\Field\FieldItemListInterface;
12 use Drupal\Core\Form\FormStateInterface;
13 use Drupal\Core\Link;
14 use Drupal\Core\Render\ElementInfoManagerInterface;
15 use Drupal\image\Plugin\Field\FieldWidget\ImageWidget;
16 use Drupal\image_widget_crop\ImageWidgetCropInterface;
17 use Symfony\Component\DependencyInjection\ContainerInterface;
18 use Drupal\crop\Entity\CropType;
19 use Drupal\Core\Render\Element\Select;
20
21 /**
22  * Plugin implementation of the 'image_widget_crop' widget.
23  *
24  * @FieldWidget(
25  *   id = "image_widget_crop",
26  *   label = @Translation("ImageWidget crop"),
27  *   field_types = {
28  *     "image"
29  *   }
30  * )
31  */
32 class ImageCropWidget extends ImageWidget {
33
34   /**
35    * Instance of ImageWidgetCropManager object.
36    *
37    * @var \Drupal\image_widget_crop\ImageWidgetCropInterface
38    */
39   protected $imageWidgetCropManager;
40
41   /**
42    * The image style storage.
43    *
44    * @var \Drupal\image\ImageStyleStorageInterface
45    */
46   protected $imageStyleStorage;
47
48   /**
49    * The crop type storage.
50    *
51    * @var \Drupal\Core\Config\Entity\ConfigEntityStorageInterface
52    */
53   protected $cropTypeStorage;
54
55   /**
56    * The config factory.
57    *
58    * Subclasses should use the self::config() method, which may be overridden to
59    * address specific needs when loading config, rather than this property
60    * directly. See \Drupal\Core\Form\ConfigFormBase::config() for an example of
61    * this.
62    *
63    * @var \Drupal\Core\Config\ConfigFactoryInterface
64    */
65   protected $configFactory;
66
67   /**
68    * {@inheritdoc}
69    */
70   public function __construct($plugin_id, $plugin_definition, FieldDefinitionInterface $field_definition, array $settings, array $third_party_settings, ElementInfoManagerInterface $element_info, ImageWidgetCropInterface $iwc_manager, EntityStorageInterface $image_style_storage, ConfigEntityStorageInterface $crop_type_storage, ConfigFactoryInterface $config_factory) {
71     parent::__construct($plugin_id, $plugin_definition, $field_definition, $settings, $third_party_settings, $element_info);
72     $this->imageWidgetCropManager = $iwc_manager;
73     $this->imageStyleStorage = $image_style_storage;
74     $this->cropTypeStorage = $crop_type_storage;
75     $this->configFactory = $config_factory;
76   }
77
78   /**
79    * {@inheritdoc}
80    */
81   public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
82     return new static(
83       $plugin_id,
84       $plugin_definition,
85       $configuration['field_definition'],
86       $configuration['settings'],
87       $configuration['third_party_settings'],
88       $container->get('element_info'),
89       $container->get('image_widget_crop.manager'),
90       $container->get('entity_type.manager')->getStorage('image_style'),
91       $container->get('entity_type.manager')->getStorage('crop_type'),
92       $container->get('config.factory')
93     );
94   }
95
96   /**
97    * {@inheritdoc}
98    */
99   public static function defaultSettings() {
100     return [
101       'crop_preview_image_style' => 'crop_thumbnail',
102       'crop_list' => [],
103       'crop_types_required' => [],
104       'show_crop_area' => FALSE,
105       'show_default_crop' => TRUE,
106       'warn_multiple_usages' => TRUE,
107     ] + parent::defaultSettings();
108   }
109
110   /**
111    * Form API callback: Processes a crop_image field element.
112    *
113    * Expands the image_image type to include the alt and title fields.
114    *
115    * This method is assigned as a #process callback in formElement() method.
116    *
117    * @return array
118    *   The elements with parents fields.
119    */
120   public static function process($element, FormStateInterface $form_state, $form) {
121     if ($element['#files']) {
122       foreach ($element['#files'] as $file) {
123         $element['image_crop'] = [
124           '#type' => 'image_crop',
125           '#file' => $file,
126           '#crop_type_list' => $element['#crop_list'],
127           '#crop_preview_image_style' => $element['#crop_preview_image_style'],
128           '#show_default_crop' => $element['#show_default_crop'],
129           '#show_crop_area' => $element['#show_crop_area'],
130           '#warn_multiple_usages' => $element['#warn_multiple_usages'],
131           '#crop_types_required' => $element['#crop_types_required'],
132         ];
133       }
134     }
135
136     return parent::process($element, $form_state, $form);
137   }
138
139   /**
140    * Verify if the element have an image file.
141    *
142    * @param array $element
143    *   A form element array containing basic properties for the widget.
144    * @param array $variables
145    *   An array with all existent variables for render.
146    *
147    * @return array[]
148    *   The variables with width & height image informations.
149    */
150   public static function getFileImageVariables(array $element, array &$variables) {
151     // Determine image dimensions.
152     if (isset($element['#value']['width']) && isset($element['#value']['height'])) {
153       $variables['width'] = $element['#value']['width'];
154       $variables['height'] = $element['#value']['height'];
155     }
156     else {
157       /** @var \Drupal\Core\Image\Image $image */
158       $image = \Drupal::service('image.factory')->get($variables['uri']);
159       if ($image->isValid()) {
160         $variables['width'] = $image->getWidth();
161         $variables['height'] = $image->getHeight();
162       }
163       else {
164         $variables['width'] = $variables['height'] = NULL;
165       }
166     }
167
168     return $variables;
169   }
170
171   /**
172    * {@inheritdoc}
173    */
174   public function settingsForm(array $form, FormStateInterface $form_state) {
175     if (!$crop_types_options = $this->imageWidgetCropManager->getAvailableCropType(CropType::getCropTypeNames())) {
176       $element['message'] = [
177         '#type' => 'container',
178         '#markup' => $this->t('No image style using the "manual crop" effect found. Please first go @link and attach the "manual crop" effect and then return to configure the field widget settings.', ['@link' => Link::createFromRoute('configure one here', 'entity.image_style.collection')->toString()]),
179         '#attributes' => [
180           'class' => ['messages messages--error'],
181         ],
182       ];
183
184       // Stop process and display error message,
185       // if any available Image Style is set.
186       return $element;
187     }
188
189     $element = parent::settingsForm($form, $form_state);
190     $element['crop_preview_image_style'] = [
191       '#title' => $this->t('Crop preview image style'),
192       '#type' => 'select',
193       '#options' => image_style_options(FALSE),
194       '#default_value' => $this->getSetting('crop_preview_image_style'),
195       '#description' => $this->t('The preview image will be shown while editing the content.'),
196       '#weight' => 15,
197     ];
198
199     $element['crop_list'] = [
200       '#title' => $this->t('Crop Type'),
201       '#type' => 'select',
202       '#options' => $crop_types_options,
203       '#default_value' => $this->getSetting('crop_list'),
204       '#multiple' => TRUE,
205       '#required' => TRUE,
206       '#description' => $this->t('The type of crop to apply to your image. If your Crop Type not appear here, set an image style use your Crop Type'),
207       '#weight' => 16,
208       '#ajax' => [
209         'callback' => [static::class, 'updateCropTypeRequiredOptions'],
210         'event' => 'change',
211       ],
212     ];
213
214     $element['crop_types_required'] = [
215       '#title' => $this->t('Required crop types'),
216       '#type' => 'select',
217       '#options' => $crop_types_options,
218       '#default_value' => $this->getSetting('crop_types_required'),
219       '#multiple' => TRUE,
220       '#description' => $this->t('Crop types that should be required.'),
221       '#weight' => 17,
222     ];
223
224     $element['show_crop_area'] = [
225       '#title' => $this->t('Always expand crop area'),
226       '#type' => 'checkbox',
227       '#default_value' => $this->getSetting('show_crop_area'),
228     ];
229
230     $element['show_default_crop'] = [
231       '#title' => $this->t('Show default crop area'),
232       '#type' => 'checkbox',
233       '#default_value' => $this->getSetting('show_default_crop'),
234     ];
235
236     $element['warn_multiple_usages'] = [
237       '#title' => $this->t('Warn the user if the crop is used more than once.'),
238       '#type' => 'checkbox',
239       '#default_value' => $this->getSetting('warn_multiple_usages'),
240     ];
241
242     $element['crop_types_required']['#process'] = [
243       // We mandatory to re-attach 'processSelect'.
244       [Select::class, 'processSelect'],
245       [static::class, 'processCropTypesRequired'],
246     ];
247
248     return $element;
249   }
250
251   /**
252    * Render API callback: retrieve options for current form element.
253    *
254    * @param array $element
255    *   An associative array containing the properties and children of the
256    *   form actions container.
257    * @param \Drupal\Core\Form\FormStateInterface $form_state
258    *   The current state of the form.
259    * @param array $complete_form
260    *   The complete form structure.
261    *
262    * @return array
263    *   The processed element.
264    */
265   public static function processCropTypesRequired(array &$element, FormStateInterface $form_state, array &$complete_form) {
266     if (!$form_state->getTriggeringElement()) {
267       return $element;
268     }
269
270     // Only display options chosen on 'crop_list',
271     // element in current form element.
272     $crop_list_form_element = self::getImageCropWidgetElement($form_state, 'crop_list');
273     if (empty($crop_list_form_element)) {
274       return $element;
275     }
276
277     $crop_list_options = $crop_list_form_element['#options'];
278     $crop_list_default_value = array_flip($crop_list_form_element['#default_value']);
279
280     // Populate element options with crop_list selected options.
281     $element['#options'] = array_intersect_key($crop_list_options, $crop_list_default_value);
282
283     return $element;
284   }
285
286   /**
287    * Ajax callback for 'crop_list' select element.
288    *
289    * This ajax callback takes care of the following things:
290    *  - Fetching selected options on the 'crop_list' element.
291    *
292    * @param array $form
293    *   An associative array containing the structure of the form.
294    * @param \Drupal\Core\Form\FormStateInterface $form_state
295    *   The current state of the form.
296    *
297    * @return \Drupal\Core\Ajax\AjaxResponse
298    *   The Ajax response.
299    */
300   public static function updateCropTypeRequiredOptions(array $form, FormStateInterface $form_state) {
301     $response = new AjaxResponse();
302     $triggering_element = $form_state->getTriggeringElement();
303     if (isset($triggering_element['#value'])) {
304       $crop_type_required_form = self::getImageCropWidgetElement($form_state, 'crop_types_required');
305       $crop_type_required_form['#options'] = array_intersect_key($triggering_element['#options'], $triggering_element['#value']);
306
307       /** @var \Drupal\Core\Render\RendererInterface $renderer */
308       $renderer = \Drupal::service('renderer');
309       $output = $renderer->renderRoot($crop_type_required_form);
310
311       // Transform field name onto field name class.
312       $field_name_class = str_replace('_', '-', $triggering_element['#parents'][1]);
313
314       // Re-construct triggered crop required form element class.
315       $element_fragments = [
316         'form-item-',
317         'fields-',
318         $field_name_class,
319         '-settings-edit-form-settings-',
320         'crop-types-required',
321       ];
322
323       // Replace existing element with selected `crop_list` options.
324       $response->addCommand(new ReplaceCommand('.' . implode($element_fragments), $output));
325     }
326
327     return $response;
328   }
329
330   /**
331    * Return a specific of ImageCropWidget form element.
332    *
333    * @param \Drupal\Core\Form\FormStateInterface $form_state
334    *   The current state of the form.
335    * @param string $key
336    *   Name of element needed.
337    *
338    * @return array
339    *   The form element needed by $key parameter.
340    */
341   public static function getImageCropWidgetElement(FormStateInterface $form_state, $key) {
342     $triggering_element = $form_state->getTriggeringElement();
343     $children = $triggering_element['#parents'][0];
344     $field_name = $triggering_element['#parents'][1];
345     $field_element_form = $form_state->getCompleteForm()[$children][$field_name];
346
347     return $field_element_form['plugin']['settings_edit_form']['settings'][$key] ?: [];
348   }
349
350   /**
351    * {@inheritdoc}
352    *
353    * @return \Drupal\Core\StringTranslation\TranslatableMarkup[]
354    *   A short summary of the widget settings.
355    */
356   public function settingsSummary() {
357     $preview = [];
358
359     $image_styles = image_style_options(FALSE);
360     // Unset possible 'No defined styles' option.
361     unset($image_styles['']);
362
363     $crop_list = $this->getSetting('crop_list');
364     if (empty($crop_list)) {
365       return [$this->t('No crop types selected.')];
366     }
367
368     $image_style_setting = $this->getSetting('preview_image_style');
369     $crop_preview = $image_styles[$this->getSetting('crop_preview_image_style')];
370     $crop_show_button = $this->getSetting('show_crop_area');
371     $show_default_crop = $this->getSetting('show_default_crop');
372     $warn_multiple_usages = $this->getSetting('warn_multiple_usages');
373     $crop_required = $this->getSetting('crop_types_required');
374
375     $preview[] = $this->t('Always expand crop area: @bool', ['@bool' => ($crop_show_button) ? 'Yes' : 'No']);
376     $preview[] = $this->t('Show default crop area: @bool', ['@bool' => ($show_default_crop) ? 'Yes' : 'No']);
377     $preview[] = $this->t('Warn the user if the crop is used more than once: @bool', ['@bool' => ($warn_multiple_usages) ? 'Yes' : 'No']);
378
379     if (isset($image_styles[$image_style_setting])) {
380       $preview[] = $this->t('Preview image style: @style', ['@style' => $image_style_setting]);
381     }
382     else {
383       $preview[] = $this->t('No preview image style');
384     }
385
386     if (isset($crop_preview)) {
387       $preview[] = $this->t('Preview crop zone image style: @style', ['@style' => $crop_preview]);
388     }
389
390     if (!empty($crop_list)) {
391       $preview[] = $this->t('Crop Type used: @list', ['@list' => implode(", ", $crop_list)]);
392     }
393
394     if (!empty($crop_required)) {
395       $preview[] = $this->t('Required crop types : @list', ['@list' => implode(", ", $crop_required)]);
396     }
397
398     return $preview;
399   }
400
401   /**
402    * {@inheritdoc}
403    *
404    * @return array[]
405    *   The form elements for a single widget for this field.
406    */
407   public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state) {
408     // Add properties needed by process() method.
409     $element['#crop_list'] = $this->getSetting('crop_list');
410     $element['#crop_preview_image_style'] = $this->getSetting('crop_preview_image_style');
411     $element['#show_crop_area'] = $this->getSetting('show_crop_area');
412     $element['#show_default_crop'] = $this->getSetting('show_default_crop');
413     $element['#warn_multiple_usages'] = $this->getSetting('warn_multiple_usages');
414     $element['#crop_types_required'] = $this->getSetting('crop_types_required');
415
416     return parent::formElement($items, $delta, $element, $form, $form_state);
417   }
418
419 }