Updated all the contrib modules to their latest versions.
[yaffs-website] / web / modules / contrib / image_widget_crop / src / Form / CropWidgetForm.php
1 <?php
2
3 namespace Drupal\image_widget_crop\Form;
4
5 use Drupal\Core\Cache\Cache;
6 use Drupal\Core\Config\ConfigFactoryInterface;
7 use Drupal\Core\Extension\ModuleHandlerInterface;
8 use Drupal\Core\Form\ConfigFormBase;
9 use Drupal\Core\Form\FormStateInterface;
10 use Drupal\crop\Entity\CropType;
11 use Drupal\image_widget_crop\ImageWidgetCropInterface;
12 use GuzzleHttp\ClientInterface;
13 use Symfony\Component\DependencyInjection\ContainerInterface;
14
15 /**
16  * Configure ImageWidgetCrop general settings for this site.
17  */
18 class CropWidgetForm extends ConfigFormBase {
19
20   /**
21    * The settings of image_widget_crop configuration.
22    *
23    * @var array
24    *
25    * @see \Drupal\Core\Config\Config
26    */
27   protected $settings;
28
29   /**
30    * Instance of ImageWidgetCropManager object.
31    *
32    * @var \Drupal\image_widget_crop\ImageWidgetCropInterface
33    */
34   protected $imageWidgetCropManager;
35
36   /**
37    * The module handler to use to load modules.
38    *
39    * @var \Drupal\Core\Extension\ModuleHandlerInterface
40    */
41   protected $moduleHandler;
42
43   /**
44    * The HTTP client to fetch the feed data with.
45    *
46    * @var \GuzzleHttp\ClientInterface
47    */
48   protected $httpClient;
49
50   /**
51    * Constructs a CropWidgetForm object.
52    *
53    * @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
54    *   The factory for configuration objects.
55    * @param \Drupal\image_widget_crop\ImageWidgetCropInterface $iwc_manager
56    *   The ImageWidgetCrop manager service.
57    * @param \Drupal\Core\Extension\ModuleHandlerInterface $module_handler
58    *   The module handler to use to load modules.
59    * @param \GuzzleHttp\ClientInterface $http_client
60    *   The Guzzle HTTP client.
61    */
62   public function __construct(ConfigFactoryInterface $config_factory, ImageWidgetCropInterface $iwc_manager, ModuleHandlerInterface $module_handler, ClientInterface $http_client) {
63     parent::__construct($config_factory);
64     $this->settings = $this->config('image_widget_crop.settings');
65     $this->imageWidgetCropManager = $iwc_manager;
66     $this->moduleHandler = $module_handler;
67     $this->httpClient = $http_client;
68   }
69
70   /**
71    * {@inheritdoc}
72    */
73   public static function create(ContainerInterface $container) {
74     return new static (
75       $container->get('config.factory'),
76       $container->get('image_widget_crop.manager'),
77       $container->get('module_handler'),
78       $container->get('http_client')
79     );
80   }
81
82   /**
83    * {@inheritdoc}
84    */
85   public function getFormId() {
86     return 'image_widget_crop_settings_form';
87   }
88
89   /**
90    * {@inheritdoc}
91    */
92   protected function getEditableConfigNames() {
93     return ['image_widget_crop.settings'];
94   }
95
96   /**
97    * {@inheritdoc}
98    */
99   public function buildForm(array $form, FormStateInterface $form_state) {
100     $url = 'https://cdnjs.com/libraries/cropper';
101     $cdn_js = IMAGE_WIDGET_CROP_JS_CDN;
102     $cdn_css = IMAGE_WIDGET_CROP_CSS_CDN;
103
104     $form['library'] = [
105       '#type' => 'details',
106       '#title' => $this->t('Cropper library settings'),
107       '#description' => $this->t('Changes here require a cache rebuild to take full effect.'),
108     ];
109
110     $form['library']['library_url'] = [
111       '#type' => 'textfield',
112       '#title' => $this->t('Custom Cropper library'),
113       '#description' => $this->t('Set the URL or local path for the file, or leave empty to use the installed library (if present) or a <a href="@file">CDN</a> fallback. You can retrieve the library file from <a href="@url">Cropper CDN</a>.', [
114         '@url' => $url,
115         '@file' => $cdn_js,
116       ]),
117       '#default_value' => $this->settings->get('settings.library_url'),
118     ];
119
120     $form['library']['css_url'] = [
121       '#type' => 'textfield',
122       '#title' => $this->t('Custom Cropper CSS file'),
123       '#description' => $this->t('Set the URL or local path for the file, or leave empty to use installed library (if installed) or a <a href="@file">CDN</a> fallback. You can retrieve the CSS file from <a href="@url">Cropper CDN</a>.', [
124         '@url' => $url,
125         '@file' => $cdn_css,
126       ]),
127       '#default_value' => $this->settings->get('settings.css_url'),
128     ];
129
130     // Indicate which files are used when custom urls are not set.
131     if ($this->moduleHandler->moduleExists('libraries')
132       && ($info = libraries_detect('cropper')) && $info['installed']) {
133       $form['library']['library_url']['#attributes']['placeholder'] = $info['library path'] . '/dist/' . key($info['files']['js']);
134       $form['library']['css_url']['#attributes']['placeholder'] = $info['library path'] . '/dist/' . key($info['files']['css']);
135     }
136     else {
137       $form['library']['library_url']['#attributes']['placeholder'] = $cdn_js;
138       $form['library']['css_url']['#attributes']['placeholder'] = $cdn_css;
139     }
140
141     $form['image_crop'] = [
142       '#type' => 'details',
143       '#title' => $this->t('General configuration'),
144     ];
145
146     $form['image_crop']['crop_preview_image_style'] = [
147       '#title' => $this->t('Crop preview image style'),
148       '#type' => 'select',
149       '#options' => image_style_options(FALSE),
150       '#default_value' => $this->settings->get('settings.crop_preview_image_style'),
151       '#description' => $this->t('The preview image will be shown while editing the content.'),
152       '#weight' => 15,
153     ];
154
155     $form['image_crop']['crop_list'] = [
156       '#title' => $this->t('Crop Type'),
157       '#type' => 'select',
158       '#options' => $this->imageWidgetCropManager->getAvailableCropType(CropType::getCropTypeNames()),
159       '#empty_option' => $this->t('<@no-preview>', ['@no-preview' => $this->t('no preview')]),
160       '#default_value' => $this->settings->get('settings.crop_list'),
161       '#multiple' => TRUE,
162       '#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'),
163       '#weight' => 16,
164     ];
165
166     $form['image_crop']['show_crop_area'] = [
167       '#title' => $this->t('Always expand crop area'),
168       '#type' => 'checkbox',
169       '#default_value' => $this->settings->get('settings.show_crop_area'),
170     ];
171
172     $form['image_crop']['warn_multiple_usages'] = [
173       '#title' => $this->t('Warn user when a file have multiple usages'),
174       '#type' => 'checkbox',
175       '#default_value' => $this->settings->get('settings.warn_multiple_usages'),
176     ];
177
178     $form['image_crop']['show_default_crop'] = [
179       '#title' => $this->t('Show default crop area'),
180       '#type' => 'checkbox',
181       '#default_value' => $this->settings->get('settings.show_default_crop'),
182     ];
183
184     $form['image_crop']['crop_types_required'] = [
185       '#title' => $this->t('Set Crop Type as required'),
186       '#type' => 'select',
187       '#options' => $this->imageWidgetCropManager->getAvailableCropType(CropType::getCropTypeNames()),
188       '#empty_option' => $this->t("- Any crop selected -"),
189       '#default_value' => $this->settings->get('settings.crop_types_required'),
190       '#multiple' => TRUE,
191       '#description' => $this->t('Set active crop as required.'),
192       '#weight' => 16,
193     ];
194
195     return parent::buildForm($form, $form_state);
196   }
197
198   /**
199    * Validation for cropper library.
200    *
201    * @param array $form
202    *   An associative array containing the structure of the form.
203    * @param \Drupal\Core\Form\FormStateInterface $form_state
204    *   The current state of the form.
205    */
206   public function validateForm(array &$form, FormStateInterface $form_state) {
207     parent::validateForm($form, $form_state);
208
209     if (!empty($form_state->getValue('library_url')) || !empty($form_state->getValue('css_url'))) {
210       $files = [
211         'library' => $form_state->getValue('library_url'),
212         'css' => $form_state->getValue('css_url'),
213       ];
214       if (empty($files['library']) || empty($files['css'])) {
215         $form_state->setErrorByName('plugin', $this->t('Please provide both a library and a CSS file when using custom URLs.'));
216       }
217       else {
218         foreach ($files as $type => $file) {
219           // Verify that both files exist.
220           $is_local = parse_url($file, PHP_URL_SCHEME) === NULL && strpos($file, '//') !== 0;
221           if ($is_local && !file_exists($file)) {
222             $form_state->setErrorByName($type . '_url', $this->t('The provided local file does not exist.'));
223           }
224           elseif (!$is_local) {
225             try {
226               $result = $this->httpClient->request('GET', $file);
227               if ($result->getStatusCode() != 200) {
228                 throw new \Exception($result->getReasonPhrase(), 1);
229               }
230             }
231             catch (\Exception $e) {
232               $form_state->setErrorByName($type . '_url', $this->t('The remote URL for the library does not appear to be valid: @message.', [
233                 '@message' => $e->getMessage(),
234               ]), 'error');
235             }
236           }
237         }
238       }
239     }
240   }
241
242   /**
243    * {@inheritdoc}
244    */
245   public function submitForm(array &$form, FormStateInterface $form_state) {
246     parent::submitForm($form, $form_state);
247
248     // We need to rebuild the library cache if we switch from remote to local
249     // library or vice-versa.
250     Cache::invalidateTags(['library_info']);
251
252     $this->settings
253       ->set("settings.library_url", $form_state->getValue('library_url'))
254       ->set("settings.css_url", $form_state->getValue('css_url'))
255       ->set("settings.crop_preview_image_style", $form_state->getValue('crop_preview_image_style'))
256       ->set("settings.show_default_crop", $form_state->getValue('show_default_crop'))
257       ->set("settings.show_crop_area", $form_state->getValue('show_crop_area'))
258       ->set("settings.warn_multiple_usages", $form_state->getValue('warn_multiple_usages'))
259       ->set("settings.crop_list", $form_state->getValue('crop_list'))
260       ->set("settings.crop_types_required", $form_state->getValue('crop_types_required'));
261     $this->settings->save();
262   }
263
264 }