You are here

abstract class WebformExporterBase in Webform 8.5

Same name and namespace in other branches
  1. 6.x src/Plugin/WebformExporterBase.php \Drupal\webform\Plugin\WebformExporterBase

Provides a base class for a results exporter.

Hierarchy

Expanded class hierarchy of WebformExporterBase

See also

\Drupal\webform\Plugin\WebformExporterInterface

\Drupal\webform\Plugin\WebformExporterManager

\Drupal\webform\Plugin\WebformExporterManagerInterface

Plugin API

3 files declare their use of WebformExporterBase
DocumentBaseWebformExporter.php in src/Plugin/WebformExporter/DocumentBaseWebformExporter.php
TabularBaseWebformExporter.php in src/Plugin/WebformExporter/TabularBaseWebformExporter.php
WebformSubmissionExportImportWebformExporter.php in modules/webform_submission_export_import/src/Plugin/WebformExporter/WebformSubmissionExportImportWebformExporter.php

File

src/Plugin/WebformExporterBase.php, line 22

Namespace

Drupal\webform\Plugin
View source
abstract class WebformExporterBase extends PluginBase implements WebformExporterInterface {

  /**
   * A logger instance.
   *
   * @var \Psr\Log\LoggerInterface
   */
  protected $logger;

  /**
   * The configuration factory.
   *
   * @var \Drupal\Core\Config\ConfigFactoryInterface
   */
  protected $configFactory;

  /**
   * The entity type manager.
   *
   * @var \Drupal\Core\Entity\EntityTypeManagerInterface
   */
  protected $entityTypeManager;

  /**
   * The webform submission storage.
   *
   * @var \Drupal\webform\WebformSubmissionStorageInterface
   */
  protected $entityStorage;

  /**
   * The webform element manager.
   *
   * @var \Drupal\webform\Plugin\WebformElementManagerInterface
   */
  protected $elementManager;

  /**
   * The webform token manager.
   *
   * @var \Drupal\webform\WebformTokenManagerInterface
   */
  protected $tokenManager;

  /**
   * Cached archive object.
   *
   * @var \Archive_Tar|\ZipArchive
   */
  protected $archive;

  /**
   * Constructs a WebformExporterBase object.
   *
   * @param array $configuration
   *   A configuration array containing information about the plugin instance.
   * @param string $plugin_id
   *   The plugin_id for the plugin instance.
   * @param mixed $plugin_definition
   *   The plugin implementation definition.
   * @param \Psr\Log\LoggerInterface $logger
   *   A logger instance.
   * @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
   *   The configuration factory.
   * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
   *   The entity type manager.
   * @param \Drupal\webform\Plugin\WebformElementManagerInterface $element_manager
   *   The webform element manager.
   * @param \Drupal\webform\WebformTokenManagerInterface $token_manager
   *   The webform token manager.
   */
  public function __construct(array $configuration, $plugin_id, $plugin_definition, LoggerInterface $logger, ConfigFactoryInterface $config_factory, EntityTypeManagerInterface $entity_type_manager, WebformElementManagerInterface $element_manager, WebformTokenManagerInterface $token_manager) {
    parent::__construct($configuration, $plugin_id, $plugin_definition);
    $this
      ->setConfiguration($configuration);
    $this->logger = $logger;
    $this->configFactory = $config_factory;
    $this->entityTypeManager = $entity_type_manager;
    $this->entityStorage = $entity_type_manager
      ->getStorage('webform_submission');
    $this->elementManager = $element_manager;
    $this->tokenManager = $token_manager;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    return new static($configuration, $plugin_id, $plugin_definition, $container
      ->get('logger.factory')
      ->get('webform'), $container
      ->get('config.factory'), $container
      ->get('entity_type.manager'), $container
      ->get('plugin.manager.webform.element'), $container
      ->get('webform.token_manager'));
  }

  /**
   * {@inheritdoc}
   */
  public function label() {
    return $this->pluginDefinition['label'];
  }

  /**
   * {@inheritdoc}
   */
  public function description() {
    return $this->pluginDefinition['description'];
  }

  /**
   * {@inheritdoc}
   */
  public function getStatus() {
    return TRUE;
  }

  /**
   * {@inheritdoc}
   */
  public function isExcluded() {
    return $this->configFactory
      ->get('webform.settings')
      ->get('export.excluded_exporters.' . $this->pluginDefinition['id']) ? TRUE : FALSE;
  }

  /**
   * {@inheritdoc}
   */
  public function isArchive() {
    return $this->pluginDefinition['archive'];
  }

  /**
   * {@inheritdoc}
   */
  public function hasFiles() {
    return $this->pluginDefinition['files'];
  }

  /**
   * {@inheritdoc}
   */
  public function hasOptions() {
    return $this->pluginDefinition['options'];
  }

  /**
   * {@inheritdoc}
   */
  public function getConfiguration() {
    return $this->configuration;
  }

  /**
   * {@inheritdoc}
   */
  public function setConfiguration(array $configuration) {
    $this->configuration = $configuration + $this
      ->defaultConfiguration();
    return $this;
  }

  /**
   * {@inheritdoc}
   */
  public function defaultConfiguration() {
    return [
      'webform' => NULL,
      'source_entity' => NULL,
    ];
  }

  /**
   * Get the webform whose submissions are being exported.
   *
   * @return \Drupal\webform\WebformInterface
   *   A webform.
   */
  protected function getWebform() {
    return $this->configuration['webform'];
  }

  /**
   * Get the webform source entity whose submissions are being exported.
   *
   * @return \Drupal\Core\Entity\EntityInterface
   *   A webform's source entity.
   */
  protected function getSourceEntity() {
    return $this->configuration['source_entity'];
  }

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

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

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

  /**
   * {@inheritdoc}
   */
  public function createExport() {
  }

  /**
   * {@inheritdoc}
   */
  public function openExport() {
  }

  /**
   * {@inheritdoc}
   */
  public function closeExport() {
  }

  /**
   * {@inheritdoc}
   */
  public function writeHeader() {
  }

  /**
   * {@inheritdoc}
   */
  public function writeSubmission(WebformSubmissionInterface $webform_submission) {
  }

  /**
   * {@inheritdoc}
   */
  public function writeFooter() {
  }

  /**
   * {@inheritdoc}
   */
  public function getFileTempDirectory() {
    return $this->configFactory
      ->get('webform.settings')
      ->get('export.temp_directory') ?: \Drupal::service('file_system')
      ->getTempDirectory();
  }

  /**
   * {@inheritdoc}
   */
  public function getSubmissionBaseName(WebformSubmissionInterface $webform_submission) {
    $export_options = $this
      ->getConfiguration();
    $file_name = $export_options['file_name'];
    $file_name = $this->tokenManager
      ->replace($file_name, $webform_submission);

    // Sanitize file name.
    // @see http://stackoverflow.com/questions/2021624/string-sanitizer-for-filename
    $file_name = preg_replace('([^\\w\\s\\d\\-_~,;:\\[\\]\\(\\].]|[\\.]{2,})', '', $file_name);
    $file_name = preg_replace('/\\s+/', '-', $file_name);
    return $file_name;
  }

  /**
   * {@inheritdoc}
   */
  public function getFileExtension() {
    return 'txt';
  }

  /**
   * {@inheritdoc}
   */
  public function getBaseFileName() {
    $webform = $this
      ->getWebform();
    $source_entity = $this
      ->getSourceEntity();
    if ($source_entity) {
      return $webform
        ->id() . '.' . $source_entity
        ->getEntityTypeId() . '.' . $source_entity
        ->id();
    }
    else {
      return $webform
        ->id();
    }
  }

  /**
   * {@inheritdoc}
   */
  public function getExportFileName() {
    return $this
      ->getBaseFileName() . '.' . $this
      ->getFileExtension();
  }

  /**
   * {@inheritdoc}
   */
  public function getExportFilePath() {
    return $this
      ->getFileTempDirectory() . '/' . $this
      ->getExportFileName();
  }

  /**
   * {@inheritdoc}
   */
  public function getArchiveFilePath() {
    return $this
      ->getFileTempDirectory() . '/' . $this
      ->getArchiveFileName();
  }

  /**
   * {@inheritdoc}
   */
  public function getArchiveFileName() {
    return $this
      ->getBaseFileName() . '.' . $this
      ->getArchiveFileExtension();
  }

  /**
   * {@inheritdoc}
   */
  public function getArchiveType() {
    return $this->configuration['archive_type'] === WebformExporterInterface::ARCHIVE_ZIP && class_exists('\\ZipArchive') ? WebformExporterInterface::ARCHIVE_ZIP : WebformExporterInterface::ARCHIVE_TAR;
  }

  /**
   * {@inheritdoc}
   */
  public function getArchiveFileExtension() {
    return $this
      ->getArchiveType() === WebformExporterInterface::ARCHIVE_ZIP ? 'zip' : 'tar.gz';
  }

  /**
   * {@inheritdoc}
   */
  public function addToArchive($path, $name, array $options = []) {
    $options += [
      'remove_path' => '',
      'close' => FALSE,
    ];
    if ($this
      ->getArchiveType() === WebformExporterInterface::ARCHIVE_ZIP) {
      $this
        ->addToZipFile($path, $name, $options);
    }
    else {
      $this
        ->addToTarArchive($path, $name, $options);
    }
  }

  /**
   * {@inheritdoc}
   */
  public function getBatchLimit() {
    return $this->configFactory
      ->get('webform.settings')
      ->get('batch.default_batch_export_size') ?: 500;
  }

  /****************************************************************************/

  // Archive helper methods.

  /****************************************************************************/

  /**
   * Add file, directory, or content to Tar archive.
   *
   * @param string $path
   *   System path or file content.
   * @param string $name
   *   Archive path or file name (applies to file content).
   * @param array $options
   *   Zip file options.
   */
  protected function addToTarArchive($path, $name, array $options = []) {
    if (!isset($this->archive)) {
      $this->archive = new \Archive_Tar($this
        ->getArchiveFilePath(), 'gz');
    }
    if (@file_exists($path)) {
      if (is_dir($path)) {

        // Add directory to Tar archive.
        $this->archive
          ->addModify((array) $path, $name, $options['remove_path']);
      }
      else {

        // Add file to Tar archive.
        $this->archive
          ->addModify((array) $path, $name, $options['remove_path']);
      }
    }
    else {

      // Add text to Tar archive.
      $this->archive
        ->addString($name, $path);
    }

    // Reset the Tar archive.
    // @see \Drupal\webform\WebformSubmissionExporter::writeExportToArchive
    if (!empty($options['close'])) {
      $this->archive = NULL;
    }
  }

  /**
   * Add file, directory, or content to ZIP file.
   *
   * @param string $path
   *   System path or file content.
   * @param string $name
   *   Archive path or file name (applies to file content).
   * @param array $options
   *   Zip file options.
   */
  protected function addToZipFile($path, $name, array $options = []) {
    if (!isset($this->archive)) {
      $this->archive = new \ZipArchive();
      $flags = !file_exists($this
        ->getArchiveFilePath()) ? \ZipArchive::CREATE : NULL;
      $this->archive
        ->open($this
        ->getArchiveFilePath(), $flags);
    }
    if (@file_exists($path)) {
      if (is_dir($path)) {

        // Add directory to ZIP file.
        $options += [
          'add_path' => $name . '/',
        ];
        $this->archive
          ->addPattern('/\\.[a-z0-9]+$/', $path, $options);
      }
      else {

        // Add file to ZIP file.
        // Get file name from the path and remove path option.
        $file_name = $path;
        if ($options['remove_path']) {
          $file_name = preg_replace('#^' . $options['remove_path'] . '#', '', $file_name);
        }
        $file_name = ltrim($file_name, '/');
        $this->archive
          ->addFile($path, $name . '/' . $file_name);
      }
    }
    else {

      // Add text to ZIP file.
      $this->archive
        ->addFromString($name, $path);
    }

    // Close and reset the ZIP file.
    // @see \Drupal\webform\WebformSubmissionExporter::writeExportToArchive
    if (!empty($options['close'])) {
      $this->archive
        ->close();
      $this->archive = NULL;
    }
  }

}

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
MessengerTrait::$messenger protected property The messenger. 29
MessengerTrait::messenger public function Gets the messenger. 29
MessengerTrait::setMessenger public function Sets the messenger.
PluginBase::$configuration protected property Configuration information passed into the plugin. 1
PluginBase::$pluginDefinition protected property The plugin implementation definition. 1
PluginBase::$pluginId protected property The plugin_id.
PluginBase::DERIVATIVE_SEPARATOR constant A string which is used to separate base plugin IDs from the derivative ID.
PluginBase::getBaseId public function Gets the base_plugin_id of the plugin instance. Overrides DerivativeInspectionInterface::getBaseId
PluginBase::getDerivativeId public function Gets the derivative_id of the plugin instance. Overrides DerivativeInspectionInterface::getDerivativeId
PluginBase::getPluginDefinition public function Gets the definition of the plugin implementation. Overrides PluginInspectionInterface::getPluginDefinition 3
PluginBase::getPluginId public function Gets the plugin_id of the plugin instance. Overrides PluginInspectionInterface::getPluginId
PluginBase::isConfigurable public function Determines if the plugin is configurable.
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.
WebformExporterBase::$archive protected property Cached archive object.
WebformExporterBase::$configFactory protected property The configuration factory.
WebformExporterBase::$elementManager protected property The webform element manager.
WebformExporterBase::$entityStorage protected property The webform submission storage.
WebformExporterBase::$entityTypeManager protected property The entity type manager.
WebformExporterBase::$logger protected property A logger instance.
WebformExporterBase::$tokenManager protected property The webform token manager.
WebformExporterBase::addToArchive public function Add file, directory, or content to exporter archive. Overrides WebformExporterInterface::addToArchive
WebformExporterBase::addToTarArchive protected function Add file, directory, or content to Tar archive.
WebformExporterBase::addToZipFile protected function Add file, directory, or content to ZIP file.
WebformExporterBase::buildConfigurationForm public function Form constructor. Overrides PluginFormInterface::buildConfigurationForm 4
WebformExporterBase::closeExport public function Close export. Overrides WebformExporterInterface::closeExport
WebformExporterBase::create public static function Creates an instance of the plugin. Overrides ContainerFactoryPluginInterface::create 1
WebformExporterBase::createExport public function Create export. Overrides WebformExporterInterface::createExport
WebformExporterBase::defaultConfiguration public function Gets default configuration for this plugin. Overrides ConfigurableInterface::defaultConfiguration 4
WebformExporterBase::description public function Returns the results exporter description. Overrides WebformExporterInterface::description
WebformExporterBase::getArchiveFileExtension public function Get archive file extension for a webform. Overrides WebformExporterInterface::getArchiveFileExtension
WebformExporterBase::getArchiveFileName public function Get archive file name for a webform. Overrides WebformExporterInterface::getArchiveFileName
WebformExporterBase::getArchiveFilePath public function Get archive file name and path for a webform. Overrides WebformExporterInterface::getArchiveFilePath
WebformExporterBase::getArchiveType public function Get archive file type. Overrides WebformExporterInterface::getArchiveType
WebformExporterBase::getBaseFileName public function Get export base file name without an extension. Overrides WebformExporterInterface::getBaseFileName
WebformExporterBase::getBatchLimit public function Get the number of submissions to be exported with each batch. Overrides WebformExporterInterface::getBatchLimit 1
WebformExporterBase::getConfiguration public function Gets this plugin's configuration. Overrides ConfigurableInterface::getConfiguration
WebformExporterBase::getExportFileName public function Get export file name. Overrides WebformExporterInterface::getExportFileName
WebformExporterBase::getExportFilePath public function Get export file path. Overrides WebformExporterInterface::getExportFilePath
WebformExporterBase::getFileExtension public function Get export file extension. Overrides WebformExporterInterface::getFileExtension 3
WebformExporterBase::getFileTempDirectory public function Get export file temp directory. Overrides WebformExporterInterface::getFileTempDirectory
WebformExporterBase::getSourceEntity protected function Get the webform source entity whose submissions are being exported.
WebformExporterBase::getStatus public function Returns the results exporter status. Overrides WebformExporterInterface::getStatus
WebformExporterBase::getSubmissionBaseName public function Get webform submission base file name. Overrides WebformExporterInterface::getSubmissionBaseName
WebformExporterBase::getWebform protected function Get the webform whose submissions are being exported.
WebformExporterBase::hasFiles public function Determine if exporter can include uploaded files (in a zipped archive). Overrides WebformExporterInterface::hasFiles
WebformExporterBase::hasOptions public function Determine if exporter has options. Overrides WebformExporterInterface::hasOptions
WebformExporterBase::isArchive public function Determine if exporter generates an archive. Overrides WebformExporterInterface::isArchive
WebformExporterBase::isExcluded public function Checks if the exporter is excluded via webform.settings. Overrides WebformExporterInterface::isExcluded
WebformExporterBase::label public function Returns the results exporter label. Overrides WebformExporterInterface::label
WebformExporterBase::openExport public function Open export. Overrides WebformExporterInterface::openExport
WebformExporterBase::setConfiguration public function Sets the configuration for this plugin instance. Overrides ConfigurableInterface::setConfiguration 1
WebformExporterBase::submitConfigurationForm public function Form submission handler. Overrides PluginFormInterface::submitConfigurationForm
WebformExporterBase::validateConfigurationForm public function Form validation handler. Overrides PluginFormInterface::validateConfigurationForm
WebformExporterBase::writeFooter public function Write footer to export. Overrides WebformExporterInterface::writeFooter 1
WebformExporterBase::writeHeader public function Write header to export. Overrides WebformExporterInterface::writeHeader 3
WebformExporterBase::writeSubmission public function Write submission to export. Overrides WebformExporterInterface::writeSubmission 6
WebformExporterBase::__construct public function Constructs a WebformExporterBase object. Overrides PluginBase::__construct 1
WebformExporterInterface::ARCHIVE_TAR constant Tar archive.
WebformExporterInterface::ARCHIVE_ZIP constant ZIP file.