3 namespace Drupal\search_api_synonym\Plugin\search_api_synonym\import;
5 use Drupal\Core\Form\FormStateInterface;
8 use Drupal\file\Entity\File;
9 use Drupal\search_api_synonym\Import\ImportPluginBase;
10 use Drupal\search_api_synonym\Import\ImportPluginInterface;
13 * Import of CSV files.
15 * @SearchApiSynonymImport(
17 * label = @Translation("CSV"),
18 * description = @Translation("Synonym import plugin from CSV / delimited file.")
21 class CSV extends ImportPluginBase implements ImportPluginInterface {
26 public function parseFile(File $file, array $settings = []) {
28 $delimiter = $settings['delimiter'];
29 $enclosure = $settings['enclosure'];
30 $header_row = $settings['header_row'];
33 if (($handle = fopen($file->getFileUri(), 'r')) !== FALSE) {
34 while (($row = fgetcsv($handle, 1000, $delimiter, $enclosure)) !== FALSE) {
35 if ($header_row && $i++ == 1) {
39 if (!empty($row[0]) && !empty($row[1])) {
42 'synonym' => $row['1'],
43 'type' => !empty($row['2']) ? $row['2'] : ''
56 public function buildConfigurationForm(array $form, FormStateInterface $form_state) {
57 $example_url = 'internal:' . base_path() . drupal_get_path('module', 'search_api_synonym') . '/examples/example.csv';
60 '#title' => $this->t('Example'),
61 '#markup' => Link::fromTextAndUrl(t('Download example file'), Url::fromUri($example_url))->toString()
63 $form['delimiter'] = [
65 '#title' => t('Delimiter'),
66 '#description' => t('Field delimiter character used in the import file.'),
68 ';' => $this->t('Semicolon'),
69 ',' => $this->t('Comma'),
70 '\t' => $this->t('Tab'),
71 '|' => $this->t('Pipe'),
73 '#default_value' => ';',
76 $form['enclosure'] = [
78 '#title' => t('Text qualifier'),
79 '#description' => t('Field enclosure character used in import file.'),
83 '' => $this->t('None'),
85 '#default_value' => '"'
87 $form['header_row'] = [
88 '#type' => 'checkbox',
89 '#title' => $this->t('Header row'),
90 '#description' => $this->t('Does the file contain a header row that should be skipped in the import?'),
91 '#default_value' => FALSE,
99 public function validateConfigurationForm(array &$form, FormStateInterface $form_state) {
100 $values = $form_state->getValues();
106 public function allowedExtensions() {