You are here

class MigrateSourceUiForm in Migrate source UI 8

Contribute form.

Hierarchy

Expanded class hierarchy of MigrateSourceUiForm

1 string reference to 'MigrateSourceUiForm'
migrate_source_ui.routing.yml in ./migrate_source_ui.routing.yml
migrate_source_ui.routing.yml

File

src/Form/MigrateSourceUiForm.php, line 22

Namespace

Drupal\migrate_source_ui\Form
View source
class MigrateSourceUiForm extends FormBase {

  /**
   * The migration plugin manager.
   *
   * @var \Drupal\migrate\Plugin\MigrationPluginManager
   */
  protected $pluginManagerMigration;

  /**
   * The migration definitions.
   *
   * @var array
   */
  protected $definitions;

  /**
   * Config object for migrate_source_ui.settings.
   *
   * @var \Drupal\Core\Config\ImmutableConfig
   */
  protected $config;

  /**
   * @var FileSystemInterface
   */
  protected $fileSystem;

  /**
   * MigrateSourceUiForm constructor.
   *
   * @param \Drupal\migrate\Plugin\MigrationPluginManager $plugin_manager_migration
   *   The migration plugin manager.
   * @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
   *   The config factory service.
   * @param \Drupal\Core\File\FileSystemInterface $file_system
   *   The File System service.
   */
  public function __construct(MigrationPluginManager $plugin_manager_migration, ConfigFactoryInterface $config_factory, FileSystemInterface $file_system) {
    $this->pluginManagerMigration = $plugin_manager_migration;
    $this->definitions = $this->pluginManagerMigration
      ->getDefinitions();
    $this->config = $config_factory
      ->get('migrate_source_ui.settings');
    $this->fileSystem = $file_system;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static($container
      ->get('plugin.manager.migration'), $container
      ->get('config.factory'), $container
      ->get('file_system'));
  }

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

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    $options = [];
    foreach ($this->definitions as $definition) {
      $migrationInstance = $this->pluginManagerMigration
        ->createStubMigration($definition);
      if ($migrationInstance
        ->getSourcePlugin() instanceof CSV || $migrationInstance
        ->getSourcePlugin() instanceof Json || $migrationInstance
        ->getSourcePlugin() instanceof Xml) {
        $id = $definition['id'];
        $options[$id] = $this
          ->t('%id (supports %file_type)', [
          '%id' => $definition['label'] ?? $id,
          '%file_type' => $this
            ->getFileExtensionSupported($migrationInstance),
        ]);
      }
    }
    $form['migrations'] = [
      '#type' => 'select',
      '#title' => $this
        ->t('Migrations'),
      '#options' => $options,
    ];
    $form['source_file'] = [
      '#type' => 'file',
      '#title' => $this
        ->t('Upload the source file'),
    ];
    $form['update_existing_records'] = [
      '#type' => 'checkbox',
      '#title' => $this
        ->t('Update existing records'),
      '#default_value' => 1,
    ];
    $form['import'] = [
      '#type' => 'submit',
      '#value' => $this
        ->t('Migrate'),
    ];
    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function validateForm(array &$form, FormStateInterface $form_state) {
    parent::validateForm($form, $form_state);
    $migration_id = $form_state
      ->getValue('migrations');
    $definition = $this->pluginManagerMigration
      ->getDefinition($migration_id);
    $migrationInstance = $this->pluginManagerMigration
      ->createStubMigration($definition);
    $extension = $this
      ->getFileExtensionSupported($migrationInstance);
    $validators = [
      'file_validate_extensions' => [
        $extension,
      ],
    ];

    // Check to see if a specific file temp directory is configured. If not,
    // default the value to FALSE, which will instruct file_save_upload() to
    // use Drupal's temporary files scheme.
    $file_destination = $this->config
      ->get('file_temp_directory');
    if (is_null($file_destination)) {
      $file_destination = FALSE;
    }
    $directory = $this->fileSystem
      ->realpath($file_destination);
    $this->fileSystem
      ->prepareDirectory($directory, FileSystemInterface::CREATE_DIRECTORY);
    $file = file_save_upload('source_file', $validators, $file_destination, 0, FileSystemInterface::EXISTS_REPLACE);
    if (isset($file)) {

      // File upload was attempted.
      if ($file) {
        $form_state
          ->setValue('file_path', $file
          ->getFileUri());
      }
      else {
        $form_state
          ->setErrorByName('source_file', $this
          ->t('The file could not be uploaded.'));
      }
    }
    else {
      $form_state
        ->setErrorByName('source_file', $this
        ->t('You have to upload a source file.'));
    }
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $migration_id = $form_state
      ->getValue('migrations');

    /** @var \Drupal\migrate\Plugin\Migration $migration */
    $migration = $this->pluginManagerMigration
      ->createInstance($migration_id);

    // Reset status.
    $status = $migration
      ->getStatus();
    if ($status !== MigrationInterface::STATUS_IDLE) {
      $migration
        ->setStatus(MigrationInterface::STATUS_IDLE);
      $this
        ->messenger()
        ->addWarning($this
        ->t('Migration @id reset to Idle', [
        '@id' => $migration_id,
      ]));
    }
    $options = [
      'file_path' => $form_state
        ->getValue('file_path'),
    ];

    // Force updates or not.
    if ($form_state
      ->getValue('update_existing_records')) {
      $options['update'] = TRUE;
    }
    $executable = new MigrateBatchExecutable($migration, new StubMigrationMessage(), $options);
    $executable
      ->batchImport();
  }

  /**
   * The allowed file extension for the migration.
   *
   * @param \Drupal\migrate\Plugin\Migration $migrationInstance
   *   The migration instance.
   *
   * @return string
   *   The file extension.
   */
  public function getFileExtensionSupported(Migration $migrationInstance) {
    $extension = 'csv';
    if ($migrationInstance
      ->getSourcePlugin() instanceof CSV) {
      $extension = 'csv';
    }
    elseif ($migrationInstance
      ->getSourcePlugin() instanceof Json) {
      $extension = 'json';
    }
    elseif ($migrationInstance
      ->getSourcePlugin() instanceof Xml) {
      $extension = 'xml';
    }
    return $extension;
  }

}

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.
MigrateSourceUiForm::$config protected property Config object for migrate_source_ui.settings.
MigrateSourceUiForm::$definitions protected property The migration definitions.
MigrateSourceUiForm::$fileSystem protected property
MigrateSourceUiForm::$pluginManagerMigration protected property The migration plugin manager.
MigrateSourceUiForm::buildForm public function Form constructor. Overrides FormInterface::buildForm
MigrateSourceUiForm::create public static function Instantiates a new instance of this class. Overrides FormBase::create
MigrateSourceUiForm::getFileExtensionSupported public function The allowed file extension for the migration.
MigrateSourceUiForm::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId
MigrateSourceUiForm::submitForm public function Form submission handler. Overrides FormInterface::submitForm
MigrateSourceUiForm::validateForm public function Form validation handler. Overrides FormBase::validateForm
MigrateSourceUiForm::__construct public function MigrateSourceUiForm constructor.
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.
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.