You are here

class FileAddArchiveForm in File Entity (fieldable files) 8.2

Form controller for archive type forms.

Hierarchy

Expanded class hierarchy of FileAddArchiveForm

1 string reference to 'FileAddArchiveForm'
file_entity.routing.yml in ./file_entity.routing.yml
file_entity.routing.yml

File

src/Form/FileAddArchiveForm.php, line 18

Namespace

Drupal\file_entity\Form
View source
class FileAddArchiveForm extends FormBase {
  use UploadValidatorsTrait;

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

  /**
   * The messenger.
   *
   * @var \Drupal\Core\Messenger\MessengerInterface
   */
  protected $messenger;

  /**
   * The archiver manager.
   *
   * @var \Drupal\Core\Archiver\ArchiverManager
   */
  protected $archiverManager;

  /**
   * {@inheritdoc}
   */
  public function __construct(FileSystemInterface $file_system, MessengerInterface $messenger, ArchiverManager $archiver_manager) {
    $this->fileSystem = $file_system;
    $this->messenger = $messenger;
    $this->archiverManager = $archiver_manager;
  }

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

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

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    $options = [
      'file_extensions' => $this->archiverManager
        ->getExtensions(),
    ];
    $options = $form_state
      ->get('options') ? $form_state
      ->get('options') : $options;
    $validators = $this
      ->getUploadValidators($options);
    $form['upload'] = array(
      '#type' => 'managed_file',
      '#title' => $this
        ->t('Upload an archive file'),
      '#upload_location' => 'public://',
      '#progress_indicator' => 'bar',
      '#default_value' => $form_state
        ->has('file') ? array(
        $form_state
          ->get('file')
          ->id(),
      ) : NULL,
      '#required' => TRUE,
      '#description' => $this
        ->t('Files must be less than <strong>%valid_size</strong><br> Allowed file types: <strong>%valid_extension</strong>', array(
        '%valid_size' => format_size($validators['file_validate_size'][0]),
        '%valid_extension' => $validators['file_validate_extensions'][0],
      )),
      '#upload_validators' => $validators,
    );
    $form['pattern'] = array(
      '#type' => 'textfield',
      '#title' => $this
        ->t('Pattern'),
      '#description' => $this
        ->t('Only files matching this pattern will be imported. For example, to import all jpg and gif files, the pattern would be <strong>.*jpg|.*gif</strong>. Use <strong>.*</strong> to extract all files in the archive.'),
      '#default_value' => '.*',
      '#required' => TRUE,
    );
    $form['remove_archive'] = array(
      '#type' => 'checkbox',
      '#title' => $this
        ->t('Remove archive'),
      '#description' => $this
        ->t('Removes archive after extraction.'),
      '#default_value' => FALSE,
    );
    $form['actions'] = array(
      '#type' => 'actions',
    );
    $form['actions']['submit'] = array(
      '#type' => 'submit',
      '#value' => t('Submit'),
    );
    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    if ($archive = File::load($form_state
      ->getValue('upload')[0])) {
      if ($archiver = $this->archiverManager
        ->getInstance([
        'filepath' => $this->fileSystem
          ->realpath($archive
          ->getFileUri()),
      ])) {
        $extract_dir = $this
          ->config('system.file')
          ->get('default_scheme') . '://' . pathinfo($archive
          ->getFilename(), PATHINFO_FILENAME);
        $extract_dir = $this->fileSystem
          ->getDestinationFilename($extract_dir, FileSystemInterface::EXISTS_RENAME);
        if (!$this->fileSystem
          ->prepareDirectory($extract_dir, FileSystemInterface::MODIFY_PERMISSIONS | FileSystemInterface::CREATE_DIRECTORY)) {
          throw new \Exception(t('Unable to prepare, the directory %dir for extraction.', array(
            '%dir' => $extract_dir,
          )));
        }
        $archiver
          ->extract($extract_dir);
        $pattern = '/' . $form_state
          ->getValue('pattern') . '/';
        if ($files = $this->fileSystem
          ->scanDirectory($extract_dir, $pattern)) {
          foreach ($files as $file) {
            $file = File::create([
              'uri' => $file->uri,
              'filename' => $file->filename,
              'status' => FILE_STATUS_PERMANENT,
            ]);
            $file
              ->save();
          }
          $all_files = $this->fileSystem
            ->scanDirectory($extract_dir, '/.*/');

          // Get all files that don't match the pattern so we can remove them.
          $remainig_files = array_diff_key($all_files, $files);
          foreach ($remainig_files as $file) {
            $this->fileSystem
              ->unlink($file->uri);
          }
        }
        $this->messenger
          ->addMessage($this
          ->t('Extracted %file and added @count new files.', array(
          '%file' => $archive
            ->getFilename(),
          '@count' => count($files),
        )));
        if ($form_state
          ->getValue('remove_archive')) {
          $this->messenger
            ->addMessage($this
            ->t('Archive %name was removed from the system.', array(
            '%name' => $archive
              ->getFilename(),
          )));
          $archive
            ->delete();
        }
        else {
          $archive
            ->setPermanent();
          $archive
            ->save();
        }
      }
      else {
        $form_state
          ->setErrorByName('', $this
          ->t('Cannot extract %file, not a valid archive.', array(
          '%file' => $archive
            ->getFileUri(),
        )));
      }
    }
    $this
      ->redirect('entity.file.collection')
      ->send();
  }

}

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
FileAddArchiveForm::$archiverManager protected property The archiver manager.
FileAddArchiveForm::$fileSystem protected property The file system service.
FileAddArchiveForm::$messenger protected property The messenger. Overrides MessengerTrait::$messenger
FileAddArchiveForm::buildForm public function Form constructor. Overrides FormInterface::buildForm
FileAddArchiveForm::create public static function Instantiates a new instance of this class. Overrides FormBase::create
FileAddArchiveForm::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId
FileAddArchiveForm::submitForm public function Form submission handler. Overrides FormInterface::submitForm
FileAddArchiveForm::__construct public function
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.
FormBase::validateForm public function Form validation handler. Overrides FormInterface::validateForm 62
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 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.
UploadValidatorsTrait::getUploadValidators public function Retrieves the upload validators for a file or archive.
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.