You are here

function _locale_parse_js_file in Drupal 8

Same name and namespace in other branches
  1. 6 includes/locale.inc \_locale_parse_js_file()
  2. 7 includes/locale.inc \_locale_parse_js_file()
  3. 9 core/modules/locale/locale.module \_locale_parse_js_file()
  4. 10 core/modules/locale/locale.module \_locale_parse_js_file()

Parses a JavaScript file, extracts strings wrapped in Drupal.t() and Drupal.formatPlural() and inserts them into the database.

Parameters

string $filepath: File name to parse.

Throws

Exception If a non-local file is attempted to be parsed.

2 calls to _locale_parse_js_file()
LocaleJavascriptTranslationTest::testFileParsing in core/modules/locale/tests/src/Functional/LocaleJavascriptTranslationTest.php
locale_js_translate in core/modules/locale/locale.module
Returns a list of translation files given a list of JavaScript files.

File

core/modules/locale/locale.module, line 1121
Enables the translation of the user interface to languages other than English.

Code

function _locale_parse_js_file($filepath) {

  // The file path might contain a query string, so make sure we only use the
  // actual file.
  $parsed_url = UrlHelper::parse($filepath);
  $filepath = $parsed_url['path'];

  // If there is still a protocol component in the path, reject that.
  if (strpos($filepath, ':')) {
    throw new Exception('Only local files should be passed to _locale_parse_js_file().');
  }

  // Load the JavaScript file.
  $file = file_get_contents($filepath);

  // Match all calls to Drupal.t() in an array.
  // Note: \s also matches newlines with the 's' modifier.
  preg_match_all('~
    [^\\w]Drupal\\s*\\.\\s*t\\s*                       # match "Drupal.t" with whitespace
    \\(\\s*                                         # match "(" argument list start
    (' . LOCALE_JS_STRING . ')\\s*                 # capture string argument
    (?:,\\s*' . LOCALE_JS_OBJECT . '\\s*            # optionally capture str args
      (?:,\\s*' . LOCALE_JS_OBJECT_CONTEXT . '\\s*) # optionally capture context
    ?)?                                           # close optional args
    [,\\)]                                         # match ")" or "," to finish
    ~sx', $file, $t_matches);

  // Match all Drupal.formatPlural() calls in another array.
  preg_match_all('~
    [^\\w]Drupal\\s*\\.\\s*formatPlural\\s*  # match "Drupal.formatPlural" with whitespace
    \\(                                  # match "(" argument list start
    \\s*.+?\\s*,\\s*                       # match count argument
    (' . LOCALE_JS_STRING . ')\\s*,\\s*   # match singular string argument
    (                             # capture plural string argument
      (?:                         # non-capturing group to repeat string pieces
        (?:
          \'(?:\\\\\'|[^\'])*\'   # match single-quoted string with any character except unescaped single-quote
          |
          "(?:\\\\"|[^"])*"       # match double-quoted string with any character except unescaped double-quote
        )
        (?:\\s*\\+\\s*)?             # match "+" with possible whitespace, for str concat
      )+                          # match multiple because we supports concatenating strs
    )\\s*                          # end capturing of plural string argument
    (?:,\\s*' . LOCALE_JS_OBJECT . '\\s*          # optionally capture string args
      (?:,\\s*' . LOCALE_JS_OBJECT_CONTEXT . '\\s*)?  # optionally capture context
    )?
    [,\\)]
    ~sx', $file, $plural_matches);
  $matches = [];

  // Add strings from Drupal.t().
  foreach ($t_matches[1] as $key => $string) {
    $matches[] = [
      'source' => _locale_strip_quotes($string),
      'context' => _locale_strip_quotes($t_matches[2][$key]),
    ];
  }

  // Add string from Drupal.formatPlural().
  foreach ($plural_matches[1] as $key => $string) {
    $matches[] = [
      'source' => _locale_strip_quotes($string) . PoItem::DELIMITER . _locale_strip_quotes($plural_matches[2][$key]),
      'context' => _locale_strip_quotes($plural_matches[3][$key]),
    ];
  }

  // Loop through all matches and process them.
  foreach ($matches as $match) {
    $source = \Drupal::service('locale.storage')
      ->findString($match);
    if (!$source) {

      // We don't have the source string yet, thus we insert it into the
      // database.
      $source = \Drupal::service('locale.storage')
        ->createString($match);
    }

    // Besides adding the location this will tag it for current version.
    $source
      ->addLocation('javascript', $filepath);
    $source
      ->save();
  }
}