class LocaleThemeAlterHooks

Same name and namespace in other branches
  1. main core/modules/locale/src/Hook/LocaleThemeAlterHooks.php \Drupal\locale\Hook\LocaleThemeAlterHooks

Hook theme alter implementations for locale.

Hierarchy

Expanded class hierarchy of LocaleThemeAlterHooks

File

core/modules/locale/src/Hook/LocaleThemeAlterHooks.php, line 14

Namespace

Drupal\locale\Hook
View source
class LocaleThemeAlterHooks {
  public function __construct(#[AutowireServiceClosure(LocaleJs::class)] protected readonly \Closure $localeJs) {
  }
  
  /**
   * Implements hook_js_alter().
   */
  public function jsAlter(array &$javascript, AttachedAssetsInterface $assets, LanguageInterface $language) : void {
    $files = [];
    foreach ($javascript as $item) {
      if (isset($item['type']) && $item['type'] == 'file') {
        // Ignore the JS translation placeholder file.
        if ($item['data'] === 'core/modules/locale/locale.translation.js') {
          continue;
        }
        $files[] = $item['data'];
      }
    }
    // Replace the placeholder file with the actual JS translation file.
    $placeholderFile = 'core/modules/locale/locale.translation.js';
    if (isset($javascript[$placeholderFile])) {
      if ($translationFile = ($this->localeJs)()
        ->jsTranslate($files, $language)) {
        $jsTranslationAsset =& $javascript[$placeholderFile];
        $jsTranslationAsset['data'] = $translationFile;
      }
      else {
        // If no translation file exists, then remove the placeholder JS asset.
        unset($javascript[$placeholderFile]);
      }
    }
  }
  
  /**
   * Implements hook_library_info_alter().
   *
   * Provides language support.
   */
  public function libraryInfoAlter(array &$libraries, string $module) : void {
    // When the locale module is enabled, we update the core/drupal library to
    // have a dependency on the locale/translations library, which provides
    // window.drupalTranslations, containing the translations for all strings in
    // JavaScript assets in the current language.
    // @see locale_js_alter()
    if ($module === 'core' && isset($libraries['drupal'])) {
      $libraries['drupal']['dependencies'][] = 'locale/translations';
    }
  }

}

Members

Title Sort descending Modifiers Object type Summary
LocaleThemeAlterHooks::jsAlter public function Implements hook_js_alter().
LocaleThemeAlterHooks::libraryInfoAlter public function Implements hook_library_info_alter().
LocaleThemeAlterHooks::__construct public function

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.