Unverified Commit 4f1f3e23 authored by Stefan Auditor's avatar Stefan Auditor Committed by Stefan Auditor
Browse files

Issue #3282696 by sanduhrs: Port of l10n_community: Add Translations and Explore languages pages

parent d347a42a
Loading
Loading
Loading
Loading
+15 −0
Original line number Diff line number Diff line
l10n_community.welcone_page:
  path: '/translate'
  defaults:
    _title: 'Translations'
    _controller: '\Drupal\l10n_community\Controller\L10nCommunityWelcomePageController::build'
  requirements:
    _permission: 'access localization community'

l10n_community.explore_languages:
  path: '/translate/languages'
  defaults:
    _title: 'Explore languages'
    _controller: '\Drupal\l10n_community\Controller\L10nCommunityExploreLanguagesController::build'
  requirements:
    _permission: 'access localization community'
+151 −0
Original line number Diff line number Diff line
<?php
declare(strict_types=1);

namespace Drupal\l10n_community\Controller;

use Drupal\Component\Render\FormattableMarkup;
use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Database\Connection;
use Drupal\Core\Url;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Returns responses for Localization community UI routes.
 */
class L10nCommunityExploreLanguagesController extends ControllerBase {

  /**
   * The database connection.
   *
   * @var \Drupal\Core\Database\Connection
   */
  protected $connection;

  /**
   * The controller constructor.
   *
   * @param \Drupal\Core\Database\Connection $connection
   *   The database connection.
   */
  public function __construct(Connection $connection) {
    $this->connection = $connection;
  }

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

  /**
   * Order listing table by column for language overview columns.
   */
  public static function sortByColumnLanguage($a, $b) {
    $sortkey = ($_GET['order'] == t('Language') ? 0 : ($_GET['order'] == t('Contributors') ? 2 : 1));
    if (@$a[$sortkey]['sortdata'] == @$b[$sortkey]['sortdata']) {
      return 0;
    }
    return ((@$a[$sortkey]['sortdata'] < @$b[$sortkey]['sortdata']) ? -1 : 1) * ($_GET['sort'] == 'asc' ? 1 : -1);
  }

  /**
   * Builds the response.
   */
  public function build() {
    /** @var \Drupal\locale\PluralFormula $plural_formula */
    $plural_formula = \Drupal::service('locale.plural.formula');
    /** @var \Drupal\l10n_community\L10nStatistics $statistics */
    $statistics = \Drupal::service('l10n_community.statistics');

    // Checking whether we have languages to translate to.
    if (!$languages = \Drupal::languageManager()->getLanguages()) {
      $build['content'] = [
        '#type' => 'item',
        '#markup' => $this->t('No languages to list.'),
      ];
      return $build;
    }

    // Checking whether we have strings to translate.
    if (!$num_source = $statistics->getStringCount()) {
      $build['content'] = [
        '#type' => 'item',
        '#markup' => $this->t('No strings to translate.'),
      ];
      return $build;
    }

    // Generate listing of all languages with summaries. The list of languages
    // is relatively "short", compared to projects, so we don't need a pager
    // here.
    $table_rows = [];
    $string_counts = $statistics->getLanguagesStringCount();
    foreach ($languages as $langcode => $language) {
      if (!$plural_formula->getFormula($language->getId())) {
        $table_rows[] = [
          [
            'data' => t($language->getName()),
            'sortdata' => t($language->getName()),
            'class' => ['rowhead'],
          ],
          [
            'data' => t('Uninitialized plural formula. Please set up the plural formula in <a href="@language-config">the langauge configuration</a> or alternatively <a href="@import-url">import a valid interface translation</a> for Drupal in this language.', ['@import-url' => Url::fromUri('internal:/admin/structure/translate/import')->toString(), '@language-config' => Url::fromUri('internal:/admin/config/language')->toString()]
            ),
            'class' => ['error'],
          ],
          ['data' => ''],
        ];
      }
      else {
        $stats = $statistics->getLanguageStatisticsByLanguage($langcode);
        $progress = [
          'data' => [
            '#theme' => 'l10n_community_progress_columns',
            '#sum' => $stats['strings'],
            '#translated' => $stats['translations'],
            '#has_suggestion' => $stats['suggestions'],
          ],
        ];
        $table_rows[] = [
          [
            'data' => new FormattableMarkup('<a href=":link">@name</a>', [
              ':link' => Url::fromUri('internal:/translate/languages/' . $langcode)->toString(),
              '@name' => $language->getName(),
            ]),
            'sortdata' => t($language->getName()),
            'class' => ['rowhead'],
          ],
          [
            'data' => $progress,
            'sortdata' => ($num_source == 0 ? 0 : round(@$string_counts[$langcode]['translations'] / $num_source * 100, 2)),
          ],
          [
            'data' => $stats['users'],
            'sortdata' => $stats['users'],
          ],
        ];
      }
    }

    if (!empty($_GET['sort']) && !empty($_GET['order'])) {
      usort($table_rows, static::class . '::sortByColumnLanguage');
    }

    $header = [
      ['data' => t('Language'), 'class' => ['rowhead'], 'field' => 'language'],
      ['data' => t('Overall progress'), 'field' => 'progress'],
      ['data' => t('Contributors'), 'field' => 'contributors'],
    ];
    $build['content'] = [
      '#type' => 'table',
      '#header' => $header,
      '#rows' => $table_rows,
      '#attributes' => ['class' => ['l10n-community-overview l10n-community-highlighted']],
    ];
    return $build;
  }

}
+191 −0
Original line number Diff line number Diff line
<?php
declare(strict_types=1);

namespace Drupal\l10n_community\Controller;

use Drupal\Component\Render\FormattableMarkup;
use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Url;
use Drupal\l10n_community\L10nStatistics;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Returns responses for Localization community UI routes.
 */
class L10nCommunityWelcomePageController extends ControllerBase {

  /**
   * The l10n_community.statistics service.
   *
   * @var \Drupal\l10n_community\L10nStatistics
   */
  protected $statistics;

  /**
   * The controller constructor.
   *
   * @param \Drupal\l10n_community\L10nStatistics $statistics
   *   The l10n_community.statistics service.
   */
  public function __construct(L10nStatistics $statistics) {
    $this->statistics = $statistics;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static(
      $container->get('l10n_community.statistics')
    );
  }

  /**
   * Order listing table by column for language overview columns.
   */
  public static function sortByColumnLanguage($a, $b) {
    $sortkey = ($_GET['order'] == t('Language') ? 0 : ($_GET['order'] == t('Contributors') ? 2 : 1));
    if (@$a[$sortkey]['sortdata'] == @$b[$sortkey]['sortdata']) {
      return 0;
    }
    return ((@$a[$sortkey]['sortdata'] < @$b[$sortkey]['sortdata']) ? -1 : 1) * ($_GET['sort'] == 'asc' ? 1 : -1);
  }

  /**
   * Builds the response.
   */
  public function build() {
    /** @var \Drupal\locale\PluralFormula $plural_formula */
    $plural_formula = \Drupal::service('locale.plural.formula');
    $config = \Drupal::configFactory()->get('l10n_community.settings');

    if (!$config->get('stats_enabled')) {

      $build['content'] = [
        '#type' => 'item',
        '#markup' => $this->t('Statistics for projects have been disabled.'),
      ];
      return $build;

    }
    elseif ($project_name = $config->get('highlighted_project')) {

      $entities = \Drupal::entityTypeManager()
        ->getStorage('l10n_server_project')
        ->loadByProperties(['title' => $project_name]);
      $project = reset($entities);
      $languages = \Drupal::languageManager()->getLanguages();

      // Check for l10n_packager, for faster queries but only on latest release.
      if (\Drupal::moduleHandler()->moduleExists('l10n_packager')
          && $config->get('package_count')) {
        [$num_source, $string_counts] = $this->statistics->getReleaseStringCount($project);
      }
      else {
        $num_source = $this->statistics->getProjectStringCount($project);
        $string_counts = $this->statistics->getLanguagesStringCount($project);
      }

      $table_rows = [];
      /** @var \Drupal\language\ConfigurableLanguageInterface $language */
      foreach ($languages as $langcode => $language) {
        if (!$plural_formula->getFormula($language->getId())) {
          $table_rows[] = [
            [
              'data' => $this->t($language->getName()),
              'sortdata' => $this->t($language->getName()),
              'class' => ['rowhead'],
            ],
            [
              'data' => $this->t('Uninitialized plural formula. Please set up the plural formula in <a href="@language-config">the language configuration</a> or alternatively <a href="@import-url">import a valid interface translation</a> for Drupal in this language.', ['@import-url' => Url::fromUri('internal:/admin/structure/translate/import')->toString(), '@language-config' => Url::fromUri('internal:/admin/config/language')->toString()]
              ),
              'class' => ['error'],
            ],
            ['data' => ''],
          ];
        }
        else {
          $stats = $this->statistics->getLanguageStatisticsByLanguage($langcode);
          $progress = [
            'data' => [
              '#theme' => 'l10n_community_progress_columns',
              '#sum' => $stats['strings'],
              '#translated' => $stats['translations'],
              '#has_suggestion' => $stats['suggestions'],
            ],
          ];
          $table_rows[] = [
            [
              'data' => new FormattableMarkup('<a href=":link">@name</a>', [
                ':link' => Url::fromUri('internal:/translate/languages/' . $langcode)->toString(),
                '@name' => $language->getName(),
              ]),
              'sortdata' => t($language->getName()),
              'class' => ['rowhead'],
            ],
            [
              'data' => $progress,
              'sortdata' => ($num_source == 0 ? 0 : round(@$string_counts[$langcode]['translations'] / $num_source * 100, 2)),
            ],
            [
              'data' => $stats['users'],
              'sortdata' => $stats['users'],
            ],
          ];
        }
      }

      if (!empty($_GET['sort']) && !empty($_GET['order'])) {
        usort($table_rows, static::class . '::sortByColumnLanguage');
      }

      $header = [
        ['data' => $this->t('Language'), 'field' => 'language', 'class' => ['rowhead']],
        ['data' => $this->t('@project progress', ['@project' => $project->label()]), 'field' => 'progress'],
        ['data' => $this->t('Contributors'), 'field' => 'contributors'],
      ];
      $build['content'] = [
        '#type' => 'table',
        '#header' => $header,
        '#rows' => $table_rows,
        '#attributes' => [
          'class' => [
            'l10n-community-overview l10n-community-highlighted',
          ],
        ],
      ];

      $project_storage = \Drupal::entityTypeManager()
        ->getStorage('l10n_server_project');
      $project_count = $project_storage->getQuery()
        ->condition('status', 1)
        ->count()->execute();
      if ($project_count > 1) {
        $build['count'] = [
          '#type' => 'html_tag',
          '#tag' => 'p',
          '#value' => $this->formatPlural(
            $project_count,
            '@project is just one of the <a href="@projects">@count projects translated on this server</a>. Check them out.',
            '@project is just one of the <a href="@projects">@count projects translated on this server</a>. Check them out.',
            [
              '@project' => $project->label(),
              '@projects' => Url::fromUri('internal:/translate/projects')->toString(),
            ]
          ),
        ];
      }

    }
    else {

      $build['content'] = [
        '#type' => 'item',
        '#markup' => $this->t('No highlighted project set.'),
      ];

    }
    return $build;
  }

}