3 namespace Drupal\locale;
5 use Drupal\Core\Language\LanguageManagerInterface;
6 use Drupal\Core\State\StateInterface;
9 * Manages the storage of plural formula per language in state.
11 * @see \Drupal\locale\PoDatabaseWriter::setHeader()
13 class PluralFormula implements PluralFormulaInterface {
16 * @var \Drupal\Core\Language\LanguageManagerInterface
18 protected $languageManager;
21 * @var \Drupal\Core\State\StateInterface
26 * The plural formula and count keyed by langcode.
28 * For example the structure looks like this:
44 * @param \Drupal\Core\Language\LanguageManagerInterface $language_manager
45 * @param \Drupal\Core\State\StateInterface $state
47 public function __construct(LanguageManagerInterface $language_manager, StateInterface $state) {
48 $this->languageManager = $language_manager;
49 $this->state = $state;
55 public function setPluralFormula($langcode, $plural_count, array $formula) {
56 // Ensure that the formulae are loaded.
57 $this->loadFormulae();
59 $this->formulae[$langcode] = [
60 'plurals' => $plural_count,
61 'formula' => $formula,
63 $this->state->set('locale.translation.formulae', $this->formulae);
70 public function getNumberOfPlurals($langcode = NULL) {
71 // Ensure that the formulae are loaded.
72 $this->loadFormulae();
74 // Set the langcode to use.
75 $langcode = $langcode ?: $this->languageManager->getCurrentLanguage()->getId();
77 // We assume 2 plurals if there is no explicit information yet.
78 if (!isset($this->formulae[$langcode]['plurals'])) {
81 return $this->formulae[$langcode]['plurals'];
87 public function getFormula($langcode) {
88 $this->loadFormulae();
89 return isset($this->formulae[$langcode]['formula']) ? $this->formulae[$langcode]['formula'] : FALSE;
93 * Loads the formulae and stores them on the PluralFormula object if not set.
97 protected function loadFormulae() {
98 if (!isset($this->formulae)) {
99 $this->formulae = $this->state->get('locale.translation.formulae', []);
106 public function reset() {
107 $this->formulae = NULL;