LanguageManager.php 12.9 KB
Newer Older
1 2 3 4
<?php

/**
 * @file
5
 * Contains \Drupal\Core\Language\LanguageManager.
6 7 8 9
 */

namespace Drupal\Core\Language;

10 11
use Drupal\Component\Utility\MapArray;
use Drupal\Core\Extension\ModuleHandlerInterface;
12
use Drupal\Core\KeyValueStore\StateInterface;
13
use Symfony\Component\HttpFoundation\Request;
14 15

/**
16
 * Class responsible for initializing each language type.
17 18 19
 */
class LanguageManager {

20 21 22 23 24 25
  /**
   * A request object.
   *
   * @var \Symfony\Component\HttpFoundation\Request
   */
  protected $request;
26

27 28 29
  /**
   * The Key/Value Store to use for state.
   *
30
   * @var \Drupal\Core\KeyValueStore\StateInterface
31 32 33
   */
  protected $state = NULL;

34 35 36 37 38 39 40
  /**
   * The module handler service.
   *
   * @var \Drupal\Core\Extension\ModuleHandlerInterface
   */
  protected $moduleHandler;

41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64
  /**
   * An array of language objects keyed by language type.
   *
   * @var array
   */
  protected $languages;

  /**
   * Whether or not the language manager has been initialized.
   *
   * @var bool
   */
  protected $initialized = FALSE;

  /**
   * Whether already in the process of language initialization.
   *
   * @todo This is only needed due to the circular dependency between language
   *   and config. See http://drupal.org/node/1862202 for the plan to fix this.
   *
   * @var bool
   */
  protected $initializing = FALSE;

65 66 67
  /**
   * Constructs an LanguageManager object.
   *
68
   * @param \Drupal\Core\KeyValueStore\StateInterface $state
69 70 71
   *   (optional) The state keyvalue store. Defaults to NULL.
   * @param \Drupal\Core\Extension\ModuleHandlerInterface $module_handler
   *   (optional) The module handler service. Defaults to NULL.
72
   */
73
  public function __construct(StateInterface $state = NULL, ModuleHandlerInterface $module_handler = NULL) {
74
    $this->state = $state;
75
    $this->moduleHandler = $module_handler;
76 77
  }

78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99
  /**
   * Initializes each language type to a language object.
   */
  public function init() {
    if ($this->initialized) {
      return;
    }
    if ($this->isMultilingual()) {
      foreach ($this->getLanguageTypes() as $type) {
        $this->getLanguage($type);
      }
    }
    $this->initialized = TRUE;
  }

  /**
   * Sets the $request property and resets all language types.
   *
   * @param \Symfony\Component\HttpFoundation\Request $request
   *   The HttpRequest object representing the current request.
   */
  public function setRequest(Request $request) {
100
    $this->request = $request;
101 102
    $this->reset();
    $this->init();
103 104
  }

105 106 107 108
  /**
   * Returns a language object for the given type.
   *
   * @param string $type
109 110
   *   (optional) The language type, e.g. the interface or the content language.
   *   Defaults to \Drupal\Core\Language\Language::TYPE_INTERFACE.
111 112 113 114
   *
   * @return \Drupal\Core\Language\Language
   *   A language object for the given type.
   */
115
  public function getLanguage($type = Language::TYPE_INTERFACE) {
116 117 118 119
    if (isset($this->languages[$type])) {
      return $this->languages[$type];
    }

120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136
    if ($this->isMultilingual() && $this->request) {
      if (!$this->initializing) {
        $this->initializing = TRUE;
        // @todo Objectify the language system so that we don't have to load an
        //   include file and call out to procedural code. See
        //   http://drupal.org/node/1862202
        include_once DRUPAL_ROOT . '/core/includes/language.inc';
        $this->languages[$type] = language_types_initialize($type, $this->request);
        $this->initializing = FALSE;
      }
      else {
        // Config has called getLanguage() during initialization of a language
        // type. Simply return the default language without setting it on the
        // $this->languages property. See the TODO in the docblock for the
        // $initializing property.
        return $this->getLanguageDefault();
      }
137 138
    }
    else {
139
      $this->languages[$type] = $this->getLanguageDefault();
140
    }
141
    return $this->languages[$type];
142 143
  }

144 145 146 147 148
  /**
   * Resets the given language type or all types if none specified.
   *
   * @param string|null $type
   *   (optional) The language type to reset as a string, e.g.,
149 150
   *   Language::TYPE_INTERFACE, or NULL to reset all language types. Defaults
   *   to NULL.
151
   */
152 153 154
  public function reset($type = NULL) {
    if (!isset($type)) {
      $this->languages = array();
155
      $this->initialized = FALSE;
156 157 158 159
    }
    elseif (isset($this->languages[$type])) {
      unset($this->languages[$type]);
    }
160
  }
161 162 163 164 165 166 167

  /**
   * Returns whether or not the site has more than one language enabled.
   *
   * @return bool
   *   TRUE if more than one language is enabled, FALSE otherwise.
   */
168
  public function isMultilingual() {
169 170 171 172 173
    if (!isset($this->state)) {
      // No state service in install time.
      return FALSE;
    }
    return ($this->state->get('language_count') ?: 1) > 1;
174 175
  }

176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222
  /**
   * Returns the language fallback candidates for a given context.
   *
   * @param string $langcode
   *   (optional) The language of the current context. Defaults to NULL.
   * @param array $context
   *   (optional) An associative array of data that can be useful to determine
   *   the fallback sequence. The following keys are used in core:
   *   - langcode: The desired language.
   *   - operation: The name of the operation indicating the context where
   *     language fallback is being applied, e.g. 'entity_view'.
   *   - data: An arbitrary data structure that makes sense in the provided
   *     context, e.g. an entity.
   *
   * @return array
   *   An array of language codes sorted by priority: first values should be
   *   tried first.
   */
  public function getFallbackCandidates($langcode = NULL, array $context = array()) {
    if ($this->isMultilingual()) {
      // Get languages ordered by weight, add Language::LANGCODE_NOT_SPECIFIED at
      // the end.
      $candidates = array_keys(language_list());
      $candidates[] = Language::LANGCODE_NOT_SPECIFIED;
      $candidates = MapArray::copyValuesToKeys($candidates);

      // The first candidate should always be the desired language if specified.
      if (!empty($langcode)) {
        $candidates = array($langcode => $langcode) + $candidates;
      }

      // Let other modules hook in and add/change candidates.
      $type = 'language_fallback_candidates';
      $types = array();
      if (!empty($context['operation'])) {
        $types[] = $type . '_' .  $context['operation'];
      }
      $types[] = $type;
      $this->moduleHandler->alter($types, $candidates, $context);
    }
    else {
      $candidates = array(Language::LANGCODE_DEFAULT);
    }

    return $candidates;
  }

223 224 225 226 227 228 229
  /**
   * Returns an array of the available language types.
   *
   * @return array()
   *   An array of all language types.
   */
  protected function getLanguageTypes() {
230
    return language_types_get_all();
231 232 233 234 235
  }

  /**
   * Returns a language object representing the site's default language.
   *
236
   * @return \Drupal\Core\Language\Language
237 238 239 240
   *   A language object.
   */
  protected function getLanguageDefault() {
    $default_info = variable_get('language_default', array(
241
      'id' => 'en',
242 243 244 245 246
      'name' => 'English',
      'direction' => 0,
      'weight' => 0,
      'locked' => 0,
    ));
247 248
    $default_info['default'] = TRUE;
    return new Language($default_info);
249 250
  }

251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299
  /**
   * Some common languages with their English and native names.
   *
   * Language codes are defined by the W3C language tags document for
   * interoperability. Language codes typically have a language and optionally,
   * a script or regional variant name. See
   * http://www.w3.org/International/articles/language-tags/ for more information.
   *
   * This list is based on languages available from localize.drupal.org. See
   * http://localize.drupal.org/issues for information on how to add languages
   * there.
   *
   * The "Left-to-right marker" comments and the enclosed UTF-8 markers are to
   * make otherwise strange looking PHP syntax natural (to not be displayed in
   * right to left). See http://drupal.org/node/128866#comment-528929.
   *
   * @return array
   *   An array of language code to language name information.
   *   Language name information itself is an array of English and native names.
   */
  public static function getStandardLanguageList() {
    return array(
      'af' => array('Afrikaans', 'Afrikaans'),
      'am' => array('Amharic', 'አማርኛ'),
      'ar' => array('Arabic', /* Left-to-right marker "‭" */ 'العربية', Language::DIRECTION_RTL),
      'ast' => array('Asturian', 'Asturianu'),
      'az' => array('Azerbaijani', 'Azərbaycanca'),
      'be' => array('Belarusian', 'Беларуская'),
      'bg' => array('Bulgarian', 'Български'),
      'bn' => array('Bengali', 'বাংলা'),
      'bo' => array('Tibetan', 'བོད་སྐད་'),
      'bs' => array('Bosnian', 'Bosanski'),
      'ca' => array('Catalan', 'Català'),
      'cs' => array('Czech', 'Čeština'),
      'cy' => array('Welsh', 'Cymraeg'),
      'da' => array('Danish', 'Dansk'),
      'de' => array('German', 'Deutsch'),
      'dz' => array('Dzongkha', 'རྫོང་ཁ'),
      'el' => array('Greek', 'Ελληνικά'),
      'en' => array('English', 'English'),
      'eo' => array('Esperanto', 'Esperanto'),
      'es' => array('Spanish', 'Español'),
      'et' => array('Estonian', 'Eesti'),
      'eu' => array('Basque', 'Euskera'),
      'fa' => array('Persian, Farsi', /* Left-to-right marker "‭" */ 'فارسی', Language::DIRECTION_RTL),
      'fi' => array('Finnish', 'Suomi'),
      'fil' => array('Filipino', 'Filipino'),
      'fo' => array('Faeroese', 'Føroyskt'),
      'fr' => array('French', 'Français'),
300 301
      'fy' => array('Frisian, Western', 'Frysk'),
      'ga' => array('Irish', 'Gaeilge'),
302 303 304 305 306 307 308 309 310
      'gd' => array('Scots Gaelic', 'Gàidhlig'),
      'gl' => array('Galician', 'Galego'),
      'gsw-berne' => array('Swiss German', 'Schwyzerdütsch'),
      'gu' => array('Gujarati', 'ગુજરાતી'),
      'he' => array('Hebrew', /* Left-to-right marker "‭" */ 'עברית', Language::DIRECTION_RTL),
      'hi' => array('Hindi', 'हिन्दी'),
      'hr' => array('Croatian', 'Hrvatski'),
      'ht' => array('Haitian Creole', 'Kreyòl ayisyen'),
      'hu' => array('Hungarian', 'Magyar'),
311
      'hy' => array('Armenian', 'Հայերեն'),
312 313 314 315 316 317 318
      'id' => array('Indonesian', 'Bahasa Indonesia'),
      'is' => array('Icelandic', 'Íslenska'),
      'it' => array('Italian', 'Italiano'),
      'ja' => array('Japanese', '日本語'),
      'jv' => array('Javanese', 'Basa Java'),
      'ka' => array('Georgian', 'ქართული ენა'),
      'kk' => array('Kazakh', 'Қазақ'),
319
      'km' => array('Khmer', 'ភាសាខ្មែរ'),
320 321 322 323 324 325 326 327 328 329 330 331
      'kn' => array('Kannada', 'ಕನ್ನಡ'),
      'ko' => array('Korean', '한국어'),
      'ku' => array('Kurdish', 'Kurdî'),
      'ky' => array('Kyrgyz', 'Кыргызча'),
      'lo' => array('Lao', 'ພາສາລາວ'),
      'lt' => array('Lithuanian', 'Lietuvių'),
      'lv' => array('Latvian', 'Latviešu'),
      'mg' => array('Malagasy', 'Malagasy'),
      'mk' => array('Macedonian', 'Македонски'),
      'ml' => array('Malayalam', 'മലയാളം'),
      'mn' => array('Mongolian', 'монгол'),
      'mr' => array('Marathi', 'मराठी'),
332
      'ms' => array('Bahasa Malaysia', 'بهاس ملايو'),
333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352
      'my' => array('Burmese', 'ဗမာစကား'),
      'ne' => array('Nepali', 'नेपाली'),
      'nl' => array('Dutch', 'Nederlands'),
      'nb' => array('Norwegian Bokmål', 'Bokmål'),
      'nn' => array('Norwegian Nynorsk', 'Nynorsk'),
      'oc' => array('Occitan', 'Occitan'),
      'pa' => array('Punjabi', 'ਪੰਜਾਬੀ'),
      'pl' => array('Polish', 'Polski'),
      'pt-pt' => array('Portuguese, Portugal', 'Português, Portugal'),
      'pt-br' => array('Portuguese, Brazil', 'Português, Brasil'),
      'ro' => array('Romanian', 'Română'),
      'ru' => array('Russian', 'Русский'),
      'sco' => array('Scots', 'Scots'),
      'se' => array('Northern Sami', 'Sámi'),
      'si' => array('Sinhala', 'සිංහල'),
      'sk' => array('Slovak', 'Slovenčina'),
      'sl' => array('Slovenian', 'Slovenščina'),
      'sq' => array('Albanian', 'Shqip'),
      'sr' => array('Serbian', 'Српски'),
      'sv' => array('Swedish', 'Svenska'),
353
      'sw' => array('Swahili', 'Kiswahili'),
354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369
      'ta' => array('Tamil', 'தமிழ்'),
      'ta-lk' => array('Tamil, Sri Lanka', 'தமிழ், இலங்கை'),
      'te' => array('Telugu', 'తెలుగు'),
      'th' => array('Thai', 'ภาษาไทย'),
      'tr' => array('Turkish', 'Türkçe'),
      'tyv' => array('Tuvan', 'Тыва дыл'),
      'ug' => array('Uyghur', 'Уйғур'),
      'uk' => array('Ukrainian', 'Українська'),
      'ur' => array('Urdu', /* Left-to-right marker "‭" */ 'اردو', Language::DIRECTION_RTL),
      'vi' => array('Vietnamese', 'Tiếng Việt'),
      'xx-lolspeak' => array('Lolspeak', 'Lolspeak'),
      'zh-hans' => array('Chinese, Simplified', '简体中文'),
      'zh-hant' => array('Chinese, Traditional', '繁體中文'),
    );
  }

Crell's avatar
Crell committed
370
}