comparison core/modules/locale/src/PluralFormula.php @ 0:4c8ae668cc8c

Initial import (non-working)
author Chris Cannam
date Wed, 29 Nov 2017 16:09:58 +0000
parents
children 129ea1e6d783
comparison
equal deleted inserted replaced
-1:000000000000 0:4c8ae668cc8c
1 <?php
2
3 namespace Drupal\locale;
4
5 use Drupal\Core\Language\LanguageManagerInterface;
6 use Drupal\Core\State\StateInterface;
7
8 /**
9 * Manages the storage of plural formula per language in state.
10 *
11 * @see \Drupal\locale\PoDatabaseWriter::setHeader()
12 */
13 class PluralFormula implements PluralFormulaInterface {
14
15 /**
16 * @var \Drupal\Core\Language\LanguageManagerInterface
17 */
18 protected $languageManager;
19
20 /**
21 * @var \Drupal\Core\State\StateInterface
22 */
23 protected $state;
24
25 /**
26 * The plural formula and count keyed by langcode.
27 *
28 * For example the structure looks like this:
29 * @code
30 * [
31 * 'de' => [
32 * 'plurals' => 2,
33 * 'formula' => [
34 * // @todo
35 * ]
36 * ],
37 * ]
38 * @endcode
39 * @var []
40 */
41 protected $formulae;
42
43 /**
44 * @param \Drupal\Core\Language\LanguageManagerInterface $language_manager
45 * @param \Drupal\Core\State\StateInterface $state
46 */
47 public function __construct(LanguageManagerInterface $language_manager, StateInterface $state) {
48 $this->languageManager = $language_manager;
49 $this->state = $state;
50 }
51
52 /**
53 * {@inheritdoc}
54 */
55 public function setPluralFormula($langcode, $plural_count, array $formula) {
56 // Ensure that the formulae are loaded.
57 $this->loadFormulae();
58
59 $this->formulae[$langcode] = [
60 'plurals' => $plural_count,
61 'formula' => $formula,
62 ];
63 $this->state->set('locale.translation.formulae', $this->formulae);
64 return $this;
65 }
66
67 /**
68 * {@inheritdoc}
69 */
70 public function getNumberOfPlurals($langcode = NULL) {
71 // Ensure that the formulae are loaded.
72 $this->loadFormulae();
73
74 // Set the langcode to use.
75 $langcode = $langcode ?: $this->languageManager->getCurrentLanguage()->getId();
76
77 // We assume 2 plurals if there is no explicit information yet.
78 if (!isset($this->formulae[$langcode]['plurals'])) {
79 return 2;
80 }
81 return $this->formulae[$langcode]['plurals'];
82 }
83
84 /**
85 * {@inheritdoc}
86 */
87 public function getFormula($langcode) {
88 $this->loadFormulae();
89 return isset($this->formulae[$langcode]['formula']) ? $this->formulae[$langcode]['formula'] : FALSE;
90 }
91
92 /**
93 * Loads the formulae and stores them on the PluralFormula object if not set.
94 *
95 * @return array
96 */
97 protected function loadFormulae() {
98 if (!isset($this->formulae)) {
99 $this->formulae = $this->state->get('locale.translation.formulae', []);
100 }
101 }
102
103 /**
104 * {@inheritdoc}
105 */
106 public function reset() {
107 $this->formulae = NULL;
108 return $this;
109 }
110
111 }