You are here

class ImportForm in Default Content Deploy 8

Config Form for run DCD deploy in Admin UI.

Hierarchy

Expanded class hierarchy of ImportForm

1 string reference to 'ImportForm'
default_content_deploy.routing.yml in ./default_content_deploy.routing.yml
default_content_deploy.routing.yml

File

src/Form/ImportForm.php, line 16

Namespace

Drupal\default_content_deploy\Form
View source
class ImportForm extends FormBase {

  /**
   * Default Content Deploy Importer object.
   *
   * @var \Drupal\default_content_deploy\Importer
   */
  private $importer;

  /**
   * Deploy manager.
   *
   * @var \Drupal\default_content_deploy\DeployManager
   */
  protected $deployManager;

  /**
   * The File system.
   *
   * @var \Drupal\Core\File\FileSystemInterface
   */
  protected $fileSystem;

  /**
   * ImportForm constructor.
   *
   * @param \Drupal\default_content_deploy\Importer $importer
   * @param \Drupal\Core\Messenger\Messenger $messenger
   * @param \Drupal\default_content_deploy\DeployManager $deploy_manager
   * @param \Drupal\Core\File\FileSystemInterface $file_system
   */
  public function __construct(Importer $importer, Messenger $messenger, DeployManager $deploy_manager, FileSystemInterface $file_system) {
    $this->importer = $importer;
    $this->messenger = $messenger;
    $this->deployManager = $deploy_manager;
    $this->fileSystem = $file_system;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static($container
      ->get('default_content_deploy.importer'), $container
      ->get('messenger'), $container
      ->get('default_content_deploy.manager'), $container
      ->get('file_system'));
  }

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

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    $form['file'] = [
      '#type' => 'file',
      '#title' => $this
        ->t('Archive'),
      '#description' => $this
        ->t('Upload a file if you want importing from archive.</br> <b>Important!!!</b> The structure should be the same as after export.'),
    ];
    $form['folder'] = [
      '#type' => 'textfield',
      '#title' => $this
        ->t('Folder'),
      '#description' => $this
        ->t('All existing content will be imported form this folder.'),
      '#default_value' => $this->deployManager
        ->getContentFolder(),
      '#states' => [
        'visible' => [
          ':input[name="files[file]"]' => [
            'value' => '',
          ],
        ],
      ],
    ];
    $form['force_override'] = [
      '#type' => 'checkbox',
      '#title' => $this
        ->t('Force override'),
      '#description' => $this
        ->t('All existing content will be overridden (locally updated default content will be reverted to the state defined in a content directory).'),
      '#default_value' => FALSE,
    ];
    $form['import'] = [
      '#type' => 'submit',
      '#value' => $this
        ->t('Import content'),
    ];
    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function validateForm(array &$form, FormStateInterface $form_state) {
    $all_files = $this
      ->getRequest()->files
      ->get('files', []);
    if (!empty($all_files['file'])) {

      /** @var \Symfony\Component\HttpFoundation\File\UploadedFile $file_upload */
      $file_upload = $all_files['file'];
      $extension = $file_upload
        ->getClientOriginalExtension();

      // Checking the extension.
      if ($extension != 'gz') {
        $form_state
          ->setErrorByName('file', $this
          ->t('The selected file %filename cannot be uploaded. Only files with the following extensions are allowed: %extensions.', [
          '%filename' => $file_upload
            ->getClientOriginalName(),
          '%extensions' => 'tar.gz',
        ]));
      }
      if ($file_upload
        ->isValid()) {
        $form_state
          ->setValue('file', $file_upload
          ->getRealPath());
      }
      else {
        $form_state
          ->setErrorByName('file', $this
          ->t('The file could not be uploaded.'));
      }
    }
  }

  /**
   * Form submission handler.
   *
   * @param array $form
   *   An associative array containing the structure of the form.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The current state of the form.
   *
   * @throws \Exception
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $force_override = $form_state
      ->getValue('force_override', FALSE);
    $folder = $form_state
      ->getValue('folder');
    $file = $form_state
      ->getValue('file');
    try {
      if ($file) {
        $this->importer
          ->setFolder($this->fileSystem
          ->getTempDirectory() . '/dcd/content');
        $this->deployManager
          ->uncompressContent($file);
      }
      else {
        $this->importer
          ->setFolder($folder);
      }
      $this->importer
        ->setForceOverride($force_override);
      $this->importer
        ->prepareForImport();
      $this
        ->addResultMessage();
      $this->importer
        ->import();
    } catch (\Exception $exception) {
      $this->messenger
        ->addError($exception
        ->getMessage());
    }
  }

  /**
   * Add a message with importing results.
   */
  private function addResultMessage() {
    $result = $this->importer
      ->getResult();
    $array_column = array_column($result, 'status');
    $count = array_count_values($array_column);
    $this->messenger
      ->addMessage($this
      ->t('Created: @count', [
      '@count' => isset($count['create']) ? $count['create'] : 0,
    ]));
    $this->messenger
      ->addMessage($this
      ->t('Updated: @count', [
      '@count' => isset($count['update']) ? $count['update'] : 0,
    ]));
    $this->messenger
      ->addMessage($this
      ->t('Skipped: @count', [
      '@count' => isset($count['skip']) ? $count['skip'] : 0,
    ]));
    return $this;
  }

}

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.
ImportForm::$deployManager protected property Deploy manager.
ImportForm::$fileSystem protected property The File system.
ImportForm::$importer private property Default Content Deploy Importer object.
ImportForm::addResultMessage private function Add a message with importing results.
ImportForm::buildForm public function Form constructor. Overrides FormInterface::buildForm
ImportForm::create public static function Instantiates a new instance of this class. Overrides FormBase::create
ImportForm::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId
ImportForm::submitForm public function Form submission handler. Overrides FormInterface::submitForm
ImportForm::validateForm public function Form validation handler. Overrides FormBase::validateForm
ImportForm::__construct public function ImportForm constructor.
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.
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.