function PoHeader::parsePluralForms

PoHeader::parsePluralForms($pluralforms)

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

function parsePluralForms($pluralforms) {
  $plurals = array();
  // First, delete all whitespace.
  $pluralforms = strtr($pluralforms, array(" " => "", "\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 array($nplurals, array('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 array($nplurals, $plurals);
  }
  else {
    throw new \Exception('The plural formula could not be parsed.');
  }
}

© 2001–2016 by the original authors
Licensed under the GNU General Public License, version 2 and later.
Drupal is a registered trademark of Dries Buytaert.
https://api.drupal.org/api/drupal/core!lib!Drupal!Component!Gettext!PoHeader.php/function/PoHeader::parsePluralForms/8.1.x