Added the Search API Synonym module to deal specifically with licence and license...
[yaffs-website] / web / modules / contrib / search_api_synonym / src / Form / SynonymImportForm.php
1 <?php
2
3 namespace Drupal\search_api_synonym\Form;
4
5 use Drupal\Core\Form\FormBase;
6 use Drupal\Core\Form\FormStateInterface;
7 use Drupal\Core\Render\Markup;
8 use Drupal\search_api_synonym\Import\Importer;
9 use Drupal\search_api_synonym\Import\ImportPluginManager;
10 use Drupal\search_api_synonym\Import\Import;
11 use Drupal\search_api_synonym\ImportException;
12 use Symfony\Component\DependencyInjection\ContainerInterface;
13
14 /**
15  * Class SynonymImportForm.
16  *
17  * @package Drupal\search_api_synonym\Form
18  *
19  * @ingroup search_api_synonym
20  */
21 class SynonymImportForm extends FormBase {
22
23   /**
24    * Import plugin manager.
25    *
26    * @var \Drupal\search_api_synonym\Import\ImportPluginManager
27    */
28   protected $pluginManager;
29
30   /**
31    * An array containing available import plugins.
32    *
33    * @var array
34    */
35   protected $availablePlugins = [];
36
37   /**
38    * Constructs a SynonymImportForm object.
39    *
40    * @param \Drupal\search_api_synonym\Import\ImportPluginManager $manager
41    *   Import plugin manager.
42    */
43   public function __construct(ImportPluginManager $manager) {
44     $this->pluginManager = $manager;
45
46     foreach ($manager->getAvailableImportPlugins() as $id => $definition) {
47       $this->availablePlugins[$id] = $manager->createInstance($id);
48     }
49   }
50
51   /**
52    * {@inheritdoc}
53    */
54   public static function create(ContainerInterface $container) {
55     return new static(
56       $container->get('plugin.manager.search_api_synonym.import')
57     );
58   }
59
60   /**
61    * {@inheritdoc}
62    */
63   public function getFormId() {
64     return 'search_api_synonym_import';
65   }
66
67   /**
68    * {@inheritdoc}
69    */
70   public function buildForm(array $form, FormStateInterface $form_state) {
71     // File.
72     $form['file_upload'] = [
73       '#type' => 'file',
74       '#title' => $this->t('File'),
75       '#description' => $this->t('Select the import file.'),
76       '#required' => FALSE,
77     ];
78
79     // Update
80     $form['update_existing'] = [
81       '#type' => 'radios',
82       '#title' => $this->t('Update existing'),
83       '#description' => $this->t('What should happen with existing synonyms?'),
84       '#options' => [
85         'merge' => $this->t('Merge'),
86         'overwrite' => $this->t('Overwrite')
87       ],
88       '#default_value' => 'merge',
89       '#required' => TRUE,
90     ];
91
92     // Synonym type.
93     $form['synonym_type'] = [
94       '#type' => 'radios',
95       '#title' => $this->t('Type '),
96       '#description' => $this->t('Which synonym type should the imported data be saved as?'),
97       '#options' => [
98         'synonym' => $this->t('Synonym'),
99         'spelling_error' => $this->t('Spelling error'),
100         'mixed' => $this->t('Mixed - Controlled by information in the source file')
101       ],
102       '#default_value' => 'synonym',
103       '#required' => TRUE,
104     ];
105
106     $message = $this->t('Notice: the source file must contain information per synonym about the synonym type. All synonyms without type information will be skipped during import!');
107     $message = Markup::create('<div class="messages messages--warning">' . $message . '</div>');
108     $form['synonym_type_notice'] = [
109       '#type' => 'item',
110       '#markup' => $message,
111       '#states' => [
112         'visible' => [
113           ':radio[name="synonym_type"]' => ['value' => 'mixed'],
114         ],
115       ],
116     ];
117
118     // Activate.
119     $form['status'] = [
120       '#type' => 'checkbox',
121       '#title' => $this->t('Activate synonyms'),
122       '#description' => $this->t('Mark import synonyms as active. Only active synonyms will be exported to the configured search backend.'),
123       '#default_value' => TRUE,
124       '#required' => TRUE,
125     ];
126
127     // Language code.
128     $form['langcode'] = [
129       '#type' => 'language_select',
130       '#title' => $this->t('Language'),
131       '#description' => $this->t('Which language should the imported data be saved as?'),
132       '#default_value' => \Drupal::languageManager()->getCurrentLanguage()->getId(),
133     ];
134
135     // Import plugin configuration.
136     $form['plugin'] = [
137       '#type' => 'radios',
138       '#title' => $this->t('Import format'),
139       '#description' => $this->t('Choose the import format to use.'),
140       '#options' => [],
141       '#default_value' => key($this->availablePlugins),
142       '#required' => TRUE,
143     ];
144
145     $form['plugin_settings'] = [
146       '#tree' => TRUE,
147     ];
148
149     foreach ($this->availablePlugins as $id => $instance) {
150       $definition = $instance->getPluginDefinition();
151       $form['plugin']['#options'][$id] = $definition['label'];
152       $form['plugin_settings'][$id] = [
153         '#type' => 'details',
154         '#title' => $this->t('@plugin plugin', ['@plugin' => $definition['label']]),
155         '#open' => TRUE,
156         '#tree' => TRUE,
157         '#states' => [
158           'visible' => [
159             ':radio[name="plugin"]' => ['value' => $id],
160           ],
161         ],
162       ];
163       $form['plugin_settings'][$id] += $instance->buildConfigurationForm([], $form_state);
164     }
165
166     // Actions.
167     $form['actions']['submit'] = [
168       '#type' => 'submit',
169       '#value' => $this->t('Import file'),
170       '#button_type' => 'primary',
171     ];
172
173     return $form;
174   }
175
176   /**
177    * {@inheritdoc}
178    */
179   public function validateForm(array &$form, FormStateInterface $form_state) {
180     parent::validateForm($form, $form_state);
181
182     $values = $form_state->getValues();
183     // Get plugin instance for active plugin.
184     $instance_active = $this->getPluginInstance($values['plugin']);
185
186     // Validate the uploaded file.
187     $extensions = $instance_active->allowedExtensions();
188     $validators = ['file_validate_extensions' => $extensions];
189
190     $file = file_save_upload('file_upload', $validators, FALSE, 0, FILE_EXISTS_RENAME);
191     if (isset($file)) {
192       if ($file) {
193         $form_state->setValue('file_upload', $file);
194       }
195       else {
196         $form_state->setErrorByName('file_upload', $this->t('The import file could not be uploaded.'));
197       }
198     }
199
200     // Call the form validation handler for each of the plugins.
201     foreach ($this->availablePlugins as $instance) {
202       $instance->validateConfigurationForm($form, $form_state);
203     }
204   }
205
206   /**
207    * {@inheritdoc}
208    */
209   public function submitForm(array &$form, FormStateInterface $form_state) {
210     try {
211       // All values from the form.
212       $values = $form_state->getValues();
213
214       // Instance of active import plugin.
215       $plugin_id = $values['plugin'];
216       $instance = $this->getPluginInstance($plugin_id);
217
218       // Parse file.
219       $data = $instance->parseFile($values['file_upload'], (array) $values['plugin_settings'][$plugin_id]);
220
221       // Import data.
222       $importer = new Importer();
223       $results = $importer->execute($data, $values);
224
225       if (!empty($results['errors'])) {
226         $count = count($results['errors']);
227         $message = \Drupal::translation()->formatPlural($count,
228           '@count synonym failed import.',
229           '@count synonyms failed import.',
230           ['@count' => $count]
231         );
232         drupal_set_message($message);
233       }
234     }
235     catch (ImportException $e) {
236       $this->logger('search_api_synonym')->error($this->t('Failed to import file due to "%error".', ['%error' => $e->getMessage()]));
237       drupal_set_message($this->t('Failed to import file due to "%error".', ['%error' => $e->getMessage()]));
238     }
239   }
240
241   /**
242    * Returns an import plugin instance for a given plugin id.
243    *
244    * @param string $plugin_id
245    *   The plugin_id for the plugin instance.
246    *
247    * @return \Drupal\search_api_synonym\Import\ImportPluginInterface
248    *   An import plugin instance.
249    */
250   public function getPluginInstance($plugin_id) {
251     return $this->pluginManager->createInstance($plugin_id, []);
252   }
253
254 }