You are here

class ExportForm in Drupal 8

Same name and namespace in other branches
  1. 9 core/modules/locale/src/Form/ExportForm.php \Drupal\locale\Form\ExportForm

Form for the Gettext translation files export form.

@internal

Hierarchy

Expanded class hierarchy of ExportForm

1 string reference to 'ExportForm'
locale.routing.yml in core/modules/locale/locale.routing.yml
core/modules/locale/locale.routing.yml

File

core/modules/locale/src/Form/ExportForm.php, line 20

Namespace

Drupal\locale\Form
View source
class ExportForm extends FormBase {

  /**
   * The language manager.
   *
   * @var \Drupal\Core\Language\LanguageManagerInterface
   */
  protected $languageManager;

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

  /**
   * Constructs a new ExportForm.
   *
   * @param \Drupal\Core\Language\LanguageManagerInterface $language_manager
   *   The language manager.
   * @param \Drupal\Core\File\FileSystemInterface $file_system
   *   The file system service.
   */
  public function __construct(LanguageManagerInterface $language_manager, FileSystemInterface $file_system) {
    $this->languageManager = $language_manager;
    $this->fileSystem = $file_system;
  }

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

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

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    $languages = $this->languageManager
      ->getLanguages();
    $language_options = [];
    foreach ($languages as $langcode => $language) {
      if (locale_is_translatable($langcode)) {
        $language_options[$langcode] = $language
          ->getName();
      }
    }
    $language_default = $this->languageManager
      ->getDefaultLanguage();
    if (empty($language_options)) {
      $form['langcode'] = [
        '#type' => 'value',
        '#value' => LanguageInterface::LANGCODE_SYSTEM,
      ];
      $form['langcode_text'] = [
        '#type' => 'item',
        '#title' => $this
          ->t('Language'),
        '#markup' => $this
          ->t('No language available. The export will only contain source strings.'),
      ];
    }
    else {
      $form['langcode'] = [
        '#type' => 'select',
        '#title' => $this
          ->t('Language'),
        '#options' => $language_options,
        '#default_value' => $language_default
          ->getId(),
        '#empty_option' => $this
          ->t('Source text only, no translations'),
        '#empty_value' => LanguageInterface::LANGCODE_SYSTEM,
      ];
      $form['content_options'] = [
        '#type' => 'details',
        '#title' => $this
          ->t('Export options'),
        '#tree' => TRUE,
        '#states' => [
          'invisible' => [
            ':input[name="langcode"]' => [
              'value' => LanguageInterface::LANGCODE_SYSTEM,
            ],
          ],
        ],
      ];
      $form['content_options']['not_customized'] = [
        '#type' => 'checkbox',
        '#title' => $this
          ->t('Include non-customized translations'),
        '#default_value' => TRUE,
      ];
      $form['content_options']['customized'] = [
        '#type' => 'checkbox',
        '#title' => $this
          ->t('Include customized translations'),
        '#default_value' => TRUE,
      ];
      $form['content_options']['not_translated'] = [
        '#type' => 'checkbox',
        '#title' => $this
          ->t('Include untranslated text'),
        '#default_value' => TRUE,
      ];
    }
    $form['actions'] = [
      '#type' => 'actions',
    ];
    $form['actions']['submit'] = [
      '#type' => 'submit',
      '#value' => $this
        ->t('Export'),
    ];
    return $form;
  }

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

    // If template is required, language code is not given.
    if ($form_state
      ->getValue('langcode') != LanguageInterface::LANGCODE_SYSTEM) {
      $language = $this->languageManager
        ->getLanguage($form_state
        ->getValue('langcode'));
    }
    else {
      $language = NULL;
    }
    $content_options = $form_state
      ->getValue('content_options', []);
    $reader = new PoDatabaseReader();
    $language_name = '';
    if ($language != NULL) {
      $reader
        ->setLangcode($language
        ->getId());
      $reader
        ->setOptions($content_options);
      $languages = $this->languageManager
        ->getLanguages();
      $language_name = isset($languages[$language
        ->getId()]) ? $languages[$language
        ->getId()]
        ->getName() : '';
      $filename = $language
        ->getId() . '.po';
    }
    else {

      // Template required.
      $filename = 'drupal.pot';
    }
    $item = $reader
      ->readItem();
    if (!empty($item)) {
      $uri = $this->fileSystem
        ->tempnam('temporary://', 'po_');
      $header = $reader
        ->getHeader();
      $header
        ->setProjectName($this
        ->config('system.site')
        ->get('name'));
      $header
        ->setLanguageName($language_name);
      $writer = new PoStreamWriter();
      $writer
        ->setURI($uri);
      $writer
        ->setHeader($header);
      $writer
        ->open();
      $writer
        ->writeItem($item);
      $writer
        ->writeItems($reader);
      $writer
        ->close();
      $response = new BinaryFileResponse($uri);
      $response
        ->setContentDisposition('attachment', $filename);
      $form_state
        ->setResponse($response);
    }
    else {
      $this
        ->messenger()
        ->addStatus($this
        ->t('Nothing to export.'));
    }
  }

}

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
ExportForm::$fileSystem protected property The file system service.
ExportForm::$languageManager protected property The language manager.
ExportForm::buildForm public function Form constructor. Overrides FormInterface::buildForm
ExportForm::create public static function Instantiates a new instance of this class. Overrides FormBase::create
ExportForm::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId
ExportForm::submitForm public function Form submission handler. Overrides FormInterface::submitForm
ExportForm::__construct public function Constructs a new ExportForm.
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 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.