You are here

public function PoHeader::parsePluralForms in Drupal 9

Same name and namespace in other branches
  1. 8 core/lib/Drupal/Component/Gettext/PoHeader.php \Drupal\Component\Gettext\PoHeader::parsePluralForms()

Parses a Plural-Forms entry from a Gettext Portable Object file header.

Parameters

string $pluralforms: The Plural-Forms entry value.

Return value

An indexed array of parsed plural formula data. Containing:

  • 'nplurals': The number of plural forms defined by the plural formula.
  • 'plurals': Array of plural positions keyed by plural value.

Throws

\Exception

File

core/lib/Drupal/Component/Gettext/PoHeader.php, line 193

Class

PoHeader
Gettext PO header handler.

Namespace

Drupal\Component\Gettext

Code

public function parsePluralForms($pluralforms) {
  $plurals = [];

  // First, delete all whitespace.
  $pluralforms = strtr($pluralforms, [
    " " => "",
    "\t" => "",
  ]);

  // Select the parts that define nplurals and plural.
  $nplurals = strstr($pluralforms, "nplurals=");
  if (strpos($nplurals, ";")) {

    // We want the string from the 10th char, because "nplurals=" length is 9.
    $nplurals = substr($nplurals, 9, strpos($nplurals, ";") - 9);
  }
  else {
    return FALSE;
  }
  $plural = strstr($pluralforms, "plural=");
  if (strpos($plural, ";")) {

    // We want the string from the 8th char, because "plural=" length is 7.
    $plural = substr($plural, 7, strpos($plural, ";") - 7);
  }
  else {
    return FALSE;
  }

  // If the number of plurals is zero, we return a default result.
  if ($nplurals == 0) {
    return [
      $nplurals,
      [
        'default' => 0,
      ],
    ];
  }

  // Calculate possible plural positions of different plural values. All known
  // plural formula's are repetitive above 100.
  // For data compression we store the last position the array value
  // changes and store it as default.
  $element_stack = $this
    ->parseArithmetic($plural);
  if ($element_stack !== FALSE) {
    for ($i = 0; $i <= 199; $i++) {
      $plurals[$i] = $this
        ->evaluatePlural($element_stack, $i);
    }
    $default = $plurals[$i - 1];
    $plurals = array_filter($plurals, function ($value) use ($default) {
      return $value != $default;
    });
    $plurals['default'] = $default;
    return [
      $nplurals,
      $plurals,
    ];
  }
  else {
    throw new \Exception('The plural formula could not be parsed.');
  }
}