You are here

class ExportForm in Drupal 9

Same name and namespace in other branches
  1. 8 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
DependencySerializationTrait::$_serviceIds protected property
DependencySerializationTrait::__sleep public function 2
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. 3
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. 3
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.
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 72
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. 27
MessengerTrait::messenger public function Gets the messenger. 27
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. 4
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.