You are here

class SynonymImportForm in Search API Synonym 8

Class SynonymImportForm.

@package Drupal\search_api_synonym\Form

Hierarchy

Expanded class hierarchy of SynonymImportForm

1 string reference to 'SynonymImportForm'
search_api_synonym.routing.yml in ./search_api_synonym.routing.yml
search_api_synonym.routing.yml

File

src/Form/SynonymImportForm.php, line 22

Namespace

Drupal\search_api_synonym\Form
View source
class SynonymImportForm extends FormBase {

  /**
   * Import plugin manager.
   *
   * @var \Drupal\search_api_synonym\Import\ImportPluginManager
   */
  protected $pluginManager;

  /**
   * An array containing available import plugins.
   *
   * @var array
   */
  protected $availablePlugins = [];

  /**
   * Constructs a SynonymImportForm object.
   *
   * @param \Drupal\search_api_synonym\Import\ImportPluginManager $manager
   *   Import plugin manager.
   */
  public function __construct(ImportPluginManager $manager) {
    $this->pluginManager = $manager;
    foreach ($manager
      ->getAvailableImportPlugins() as $id => $definition) {
      $this->availablePlugins[$id] = $manager
        ->createInstance($id);
    }
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static($container
      ->get('plugin.manager.search_api_synonym.import'));
  }

  /**
   * {@inheritdoc}
   */
  public function getFormId() {
    return 'search_api_synonym_import';
  }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {

    // File.
    $form['file_upload'] = [
      '#type' => 'file',
      '#title' => $this
        ->t('File'),
      '#description' => $this
        ->t('Select the import file.'),
      '#required' => FALSE,
    ];

    // Update
    $form['update_existing'] = [
      '#type' => 'radios',
      '#title' => $this
        ->t('Update existing'),
      '#description' => $this
        ->t('What should happen with existing synonyms?'),
      '#options' => [
        'merge' => $this
          ->t('Merge'),
        'overwrite' => $this
          ->t('Overwrite'),
      ],
      '#default_value' => 'merge',
      '#required' => TRUE,
    ];

    // Synonym type.
    $form['synonym_type'] = [
      '#type' => 'radios',
      '#title' => $this
        ->t('Type '),
      '#description' => $this
        ->t('Which synonym type should the imported data be saved as?'),
      '#options' => [
        'synonym' => $this
          ->t('Synonym'),
        'spelling_error' => $this
          ->t('Spelling error'),
        'mixed' => $this
          ->t('Mixed - Controlled by information in the source file'),
      ],
      '#default_value' => 'synonym',
      '#required' => TRUE,
    ];
    $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!');
    $message = Markup::create('<div class="messages messages--warning">' . $message . '</div>');
    $form['synonym_type_notice'] = [
      '#type' => 'item',
      '#markup' => $message,
      '#states' => [
        'visible' => [
          ':radio[name="synonym_type"]' => [
            'value' => 'mixed',
          ],
        ],
      ],
    ];

    // Activate.
    $form['status'] = [
      '#type' => 'checkbox',
      '#title' => $this
        ->t('Activate synonyms'),
      '#description' => $this
        ->t('Mark import synonyms as active. Only active synonyms will be exported to the configured search backend.'),
      '#default_value' => TRUE,
      '#required' => TRUE,
    ];

    // Language code.
    $form['langcode'] = [
      '#type' => 'language_select',
      '#title' => $this
        ->t('Language'),
      '#description' => $this
        ->t('Which language should the imported data be saved as?'),
      '#default_value' => \Drupal::languageManager()
        ->getCurrentLanguage()
        ->getId(),
    ];

    // Import plugin configuration.
    $form['plugin'] = [
      '#type' => 'radios',
      '#title' => $this
        ->t('Import format'),
      '#description' => $this
        ->t('Choose the import format to use.'),
      '#options' => [],
      '#default_value' => key($this->availablePlugins),
      '#required' => TRUE,
    ];
    $form['plugin_settings'] = [
      '#tree' => TRUE,
    ];
    foreach ($this->availablePlugins as $id => $instance) {
      $definition = $instance
        ->getPluginDefinition();
      $form['plugin']['#options'][$id] = $definition['label'];
      $form['plugin_settings'][$id] = [
        '#type' => 'details',
        '#title' => $this
          ->t('@plugin plugin', [
          '@plugin' => $definition['label'],
        ]),
        '#open' => TRUE,
        '#tree' => TRUE,
        '#states' => [
          'visible' => [
            ':radio[name="plugin"]' => [
              'value' => $id,
            ],
          ],
        ],
      ];
      $form['plugin_settings'][$id] += $instance
        ->buildConfigurationForm([], $form_state);
    }

    // Actions.
    $form['actions']['submit'] = [
      '#type' => 'submit',
      '#value' => $this
        ->t('Import file'),
      '#button_type' => 'primary',
    ];
    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function validateForm(array &$form, FormStateInterface $form_state) {
    parent::validateForm($form, $form_state);
    $values = $form_state
      ->getValues();

    // Get plugin instance for active plugin.
    $instance_active = $this
      ->getPluginInstance($values['plugin']);

    // Validate the uploaded file.
    $extensions = $instance_active
      ->allowedExtensions();
    $validators = [
      'file_validate_extensions' => $extensions,
    ];
    $file = file_save_upload('file_upload', $validators, FALSE, 0, FileSystemInterface::EXISTS_RENAME);
    if (isset($file)) {
      if ($file) {
        $form_state
          ->setValue('file_upload', $file);
      }
      else {
        $form_state
          ->setErrorByName('file_upload', $this
          ->t('The import file could not be uploaded.'));
      }
    }

    // Call the form validation handler for each of the plugins.
    foreach ($this->availablePlugins as $instance) {
      $instance
        ->validateConfigurationForm($form, $form_state);
    }
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    try {

      // All values from the form.
      $values = $form_state
        ->getValues();

      // Instance of active import plugin.
      $plugin_id = $values['plugin'];
      $instance = $this
        ->getPluginInstance($plugin_id);

      // Parse file.
      $data = $instance
        ->parseFile($values['file_upload'], (array) $values['plugin_settings'][$plugin_id]);

      // Import data.
      $importer = new Importer();
      $results = $importer
        ->execute($data, $values);
      if (!empty($results['errors'])) {
        $count = count($results['errors']);
        $message = \Drupal::translation()
          ->formatPlural($count, '@count synonym failed import.', '@count synonyms failed import.', [
          '@count' => $count,
        ]);
        $this
          ->messenger()
          ->addStatus($message);
      }
    } catch (ImportException $e) {
      $this
        ->logger('search_api_synonym')
        ->error($this
        ->t('Failed to import file due to "%error".', [
        '%error' => $e
          ->getMessage(),
      ]));
      $this
        ->messenger()
        ->addStatus($this
        ->t('Failed to import file due to "%error".', [
        '%error' => $e
          ->getMessage(),
      ]));
    }
  }

  /**
   * Returns an import plugin instance for a given plugin id.
   *
   * @param string $plugin_id
   *   The plugin_id for the plugin instance.
   *
   * @return \Drupal\search_api_synonym\Import\ImportPluginInterface
   *   An import plugin instance.
   */
  public function getPluginInstance($plugin_id) {
    return $this->pluginManager
      ->createInstance($plugin_id, []);
  }

}

Members

Namesort descending Modifiers Type Description Overrides
DependencySerializationTrait::$_entityStorages protected property An array of entity type IDs keyed by the property name of their storages.
DependencySerializationTrait::$_serviceIds protected property An array of service IDs keyed by property name used for serialization.
DependencySerializationTrait::__sleep public function 1
DependencySerializationTrait::__wakeup public function 2
FormBase::$configFactory protected property The config factory. 1
FormBase::$requestStack protected property The request stack. 1
FormBase::$routeMatch protected property The route match.
FormBase::config protected function Retrieves a configuration object.
FormBase::configFactory protected function Gets the config factory for this form. 1
FormBase::container private function Returns the service container.
FormBase::currentUser protected function Gets the current user.
FormBase::getRequest protected function Gets the request object.
FormBase::getRouteMatch protected function Gets the route match.
FormBase::logger protected function Gets the logger for a specific channel.
FormBase::redirect protected function Returns a redirect response object for the specified route. Overrides UrlGeneratorTrait::redirect
FormBase::resetConfigFactory public function Resets the configuration factory.
FormBase::setConfigFactory public function Sets the config factory for this form.
FormBase::setRequestStack public function Sets the request stack object to use.
LinkGeneratorTrait::$linkGenerator protected property The link generator. 1
LinkGeneratorTrait::getLinkGenerator Deprecated protected function Returns the link generator.
LinkGeneratorTrait::l Deprecated protected function Renders a link to a route given a route name and its parameters.
LinkGeneratorTrait::setLinkGenerator Deprecated public function Sets the link generator service.
LoggerChannelTrait::$loggerFactory protected property The logger channel factory service.
LoggerChannelTrait::getLogger protected function Gets the logger for a specific channel.
LoggerChannelTrait::setLoggerFactory public function Injects the logger channel factory.
MessengerTrait::$messenger protected property The messenger. 29
MessengerTrait::messenger public function Gets the messenger. 29
MessengerTrait::setMessenger public function Sets the messenger.
RedirectDestinationTrait::$redirectDestination protected property The redirect destination service. 1
RedirectDestinationTrait::getDestinationArray protected function Prepares a 'destination' URL query parameter for use with \Drupal\Core\Url.
RedirectDestinationTrait::getRedirectDestination protected function Returns the redirect destination service.
RedirectDestinationTrait::setRedirectDestination public function Sets the redirect destination service.
StringTranslationTrait::$stringTranslation protected property The string translation service. 1
StringTranslationTrait::formatPlural protected function Formats a string containing a count of items.
StringTranslationTrait::getNumberOfPlurals protected function Returns the number of plurals supported by a given language.
StringTranslationTrait::getStringTranslation protected function Gets the string translation service.
StringTranslationTrait::setStringTranslation public function Sets the string translation service to use. 2
StringTranslationTrait::t protected function Translates a string to the current language or to a given language.
SynonymImportForm::$availablePlugins protected property An array containing available import plugins.
SynonymImportForm::$pluginManager protected property Import plugin manager.
SynonymImportForm::buildForm public function Form constructor. Overrides FormInterface::buildForm
SynonymImportForm::create public static function Instantiates a new instance of this class. Overrides FormBase::create
SynonymImportForm::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId
SynonymImportForm::getPluginInstance public function Returns an import plugin instance for a given plugin id.
SynonymImportForm::submitForm public function Form submission handler. Overrides FormInterface::submitForm
SynonymImportForm::validateForm public function Form validation handler. Overrides FormBase::validateForm
SynonymImportForm::__construct public function Constructs a SynonymImportForm object.
UrlGeneratorTrait::$urlGenerator protected property The url generator.
UrlGeneratorTrait::getUrlGenerator Deprecated protected function Returns the URL generator service.
UrlGeneratorTrait::setUrlGenerator Deprecated public function Sets the URL generator service.
UrlGeneratorTrait::url Deprecated protected function Generates a URL or path for a specific route based on the given parameters.