ConfigurableLanguageManager.php 12.2 KB
Newer Older
1 2 3 4 5 6 7 8 9
<?php

/**
 * @file
 * Contains \Drupal\language\ConfigurableLanguageManager.
 */

namespace Drupal\language;

10
use Drupal\Core\PhpStorage\PhpStorageFactory;
11
use Drupal\Core\Config\ConfigFactoryInterface;
12 13
use Drupal\Core\Extension\ModuleHandlerInterface;
use Drupal\Core\Language\Language;
14
use Drupal\Core\Language\LanguageDefault;
15
use Drupal\Core\Language\LanguageManager;
16
use Drupal\language\Config\LanguageConfigFactoryOverrideInterface;
17 18 19 20 21 22 23 24 25 26
use Symfony\Component\HttpFoundation\Request;

/**
 * Overrides default LanguageManager to provide configured languages.
 */
class ConfigurableLanguageManager extends LanguageManager implements ConfigurableLanguageManagerInterface {

  /**
   * The configuration storage service.
   *
27
   * @var \Drupal\Core\Config\ConfigFactoryInterface
28 29 30 31 32 33 34 35 36 37
   */
  protected $configFactory;

  /**
   * The module handler service.
   *
   * @var \Drupal\Core\Extension\ModuleHandlerInterface
   */
  protected $moduleHandler;

38 39 40 41 42 43 44
  /**
   * The language configuration override service.
   *
   * @var \Drupal\language\Config\LanguageConfigFactoryOverrideInterface
   */
  protected $configFactoryOverride;

45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94
  /**
   * The request object.
   *
   * @var \Symfony\Component\HttpFoundation\Request
   */
  protected $request;

  /**
   * The language negotiator.
   *
   * @var \Drupal\language\LanguageNegotiatorInterface
   */
  protected $negotiator;

  /**
   * Local cache for language type configuration data.
   *
   * @var array
   */
  protected $languageTypes;

  /**
   * Local cache for language type information.
   *
   * @var array
   */
  protected $languageTypesInfo;

  /**
   * An array of language objects keyed by language type.
   *
   * @var array
   */
  protected $negotiatedLanguages;

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

  /**
   * Whether already in the process of language initialization.
   *
   * @var bool
   */
  protected $initializing = FALSE;

  /**
95
   * {@inheritdoc}
96 97 98 99 100 101 102 103
   */
  public static function rebuildServices() {
    PhpStorageFactory::get('service_container')->deleteAll();
  }

  /**
   * Constructs a new ConfigurableLanguageManager object.
   *
104 105
   * @param \Drupal\Core\Language\LanguageDefault $default_language
   *   The default language service.
106
   * @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
107
   *   The configuration factory service.
108 109
   * @param \Drupal\Core\Extension\ModuleHandlerInterface $module_handler
   *   The module handler service.
110 111 112 113
   * @param \Drupal\language\Config\LanguageConfigFactoryOverrideInterface $config_override
   *   The language configuration override service.
   * @param \Drupal\Core\Config\StorageInterface $config_storage
   *   The configuration storage engine.
114
   */
115
  public function __construct(LanguageDefault $default_language, ConfigFactoryInterface $config_factory, ModuleHandlerInterface $module_handler, LanguageConfigFactoryOverrideInterface $config_override) {
116
    $this->defaultLanguage = $default_language;
117 118
    $this->configFactory = $config_factory;
    $this->moduleHandler = $module_handler;
119
    $this->configFactoryOverride = $config_override;
120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185
  }

  /**
   * {@inheritdoc}
   */
  public function init() {
    if (!$this->initialized) {
      foreach ($this->getDefinedLanguageTypes() as $type) {
        $this->getCurrentLanguage($type);
      }
      $this->initialized = TRUE;
    }
  }

  /**
   * {@inheritdoc}
   */
  public function isMultilingual() {
    return count($this->getLanguages(Language::STATE_CONFIGURABLE)) > 1;
  }

  /**
   * {@inheritdoc}
   */
  public function getLanguageTypes() {
    $this->loadLanguageTypesConfiguration();
    return $this->languageTypes['configurable'];
  }

  /**
   * {@inheritdoc}
   */
  public function getDefinedLanguageTypes() {
    $this->loadLanguageTypesConfiguration();
    return $this->languageTypes['all'];
  }

  /**
   * Retrieves language types from the configuration storage.
   *
   * @return array
   *   An array of language type names.
   */
  protected function loadLanguageTypesConfiguration() {
    if (!$this->languageTypes) {
      $this->languageTypes = $this->configFactory->get('language.types')->get() ?: array('configurable' => array(), 'all' => parent::getLanguageTypes());
    }
    return $this->languageTypes;
  }

  /**
   * {@inheritdoc}
   */
  public function getDefinedLanguageTypesInfo() {
    if (!isset($this->languageTypesInfo)) {
      $info = $this->moduleHandler->invokeAll('language_types_info');
      // Let other modules alter the list of language types.
      $this->moduleHandler->alter('language_types_info', $info);
      $this->languageTypesInfo = $info;
    }
    return $this->languageTypesInfo;
  }

  /**
   * Stores language types configuration.
   */
186 187 188 189 190 191 192 193 194
  public function saveLanguageTypesConfiguration(array $values) {
    $config = $this->configFactory->get('language.types');
    if (isset($values['configurable'])) {
      $config->set('configurable', $values['configurable']);
    }
    if (isset($values['all'])) {
      $config->set('all', $values['all']);
    }
    $config->save();
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 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242
  }

  /**
   * {@inheritdoc}
   */
  public function getCurrentLanguage($type = Language::TYPE_INTERFACE) {
    if (!isset($this->negotiatedLanguages[$type])) {
      // Ensure we have a valid value for this language type.
      $this->negotiatedLanguages[$type] = $this->getDefaultLanguage();

      if ($this->negotiator && $this->isMultilingual()) {
        if (!$this->initializing) {
          $this->initializing = TRUE;
          $this->negotiatedLanguages[$type] = $this->negotiator->initializeType($type);
          $this->initializing = FALSE;
        }
        // If the current interface language needs to be retrieved during
        // initialization we return the system language. This way string
        // translation calls happening during initialization will return the
        // original strings which can be translated by calling them again
        // afterwards. This can happen for instance while parsing negotiation
        // method definitions.
        elseif ($type == Language::TYPE_INTERFACE) {
          return new Language(array('id' => Language::LANGCODE_SYSTEM));
        }
      }
    }

    return $this->negotiatedLanguages[$type];
  }

  /**
   * {@inheritdoc}
   */
  public function reset($type = NULL) {
    if (!isset($type)) {
      $this->initialized = FALSE;
      $this->negotiatedLanguages = array();
      $this->languageTypes = NULL;
      $this->languageTypesInfo = NULL;
      $this->languages = NULL;
      if ($this->negotiator) {
        $this->negotiator->reset();
      }
    }
    elseif (isset($this->negotiatedLanguages[$type])) {
      unset($this->negotiatedLanguages[$type]);
    }
243
    return $this;
244 245 246 247 248 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
  }

  /**
   * {@inheritdoc}
   */
  public function setRequest(Request $request) {
    $this->request = $request;
  }

  /**
   * {@inheritdoc}
   */
  public function getNegotiator() {
    return $this->negotiator;
  }

  /**
   * {@inheritdoc}
   */
  public function setNegotiator(LanguageNegotiatorInterface $negotiator) {
    $this->negotiator = $negotiator;
    $this->initialized = FALSE;
    $this->negotiatedLanguages = array();
  }

  /**
   * {@inheritdoc}
   */
  public function getLanguages($flags = Language::STATE_CONFIGURABLE) {
    if (!isset($this->languages)) {
      // Prepopulate the language list with the default language to keep things
      // working even if we have no configuration.
      $default = $this->getDefaultLanguage();
      $this->languages = array($default->id => $default);

      // Retrieve the config storage to list available languages.
      $prefix = 'language.entity.';
281
      $config_ids = $this->configFactory->listAll($prefix);
282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298

      // Instantiate languages from config objects.
      $weight = 0;
      foreach ($this->configFactory->loadMultiple($config_ids) as $config) {
        $data = $config->get();
        $langcode = $data['id'];
        // Initialize default property so callers have an easy reference and can
        // save the same object without data loss.
        $data['default'] = ($langcode == $default->id);
        $data['name'] = $data['label'];
        $this->languages[$langcode] = new Language($data);
        $weight = max(array($weight, $this->languages[$langcode]->weight));
      }

      // Add locked languages, they will be filtered later if needed.
      $this->languages += $this->getDefaultLockedLanguages($weight);

299
      // Sort the language list by weight then title.
300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321
      Language::sort($this->languages);
    }

    return parent::getLanguages($flags);
  }

  /**
   * {@inheritdoc}
   */
  public function updateLockedLanguageWeights() {
    $max_weight = 0;

    // Get maximum weight to update the system languages to keep them on bottom.
    foreach ($this->getLanguages(Language::STATE_CONFIGURABLE) as $language) {
      if (!$language->locked && $language->weight > $max_weight) {
        $max_weight = $language->weight;
      }
    }

    // Loop locked languages to maintain the existing order.
    $locked_languages = $this->getLanguages(Language::STATE_LOCKED);
    $config_ids = array_map(function($language) { return 'language.entity.' . $language->id; }, $locked_languages);
322
    foreach ($this->configFactory->loadMultiple($config_ids) as $config) {
323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338
      // Update system languages weight.
      $max_weight++;
      $config->set('weight', $max_weight);
      $config->save();
    }
  }

  /**
   * {@inheritdoc}
   */
  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($this->getLanguages());
      $candidates[] = Language::LANGCODE_NOT_SPECIFIED;
339
      $candidates = array_combine($candidates, $candidates);
340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387

      // 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 = parent::getFallbackCandidates($langcode, $context);
    }

    return $candidates;
  }

  /**
   * {@inheritdoc}
   */
  public function getLanguageSwitchLinks($type, $path) {
    $links = FALSE;

    if ($this->negotiator) {
      foreach ($this->negotiator->getNegotiationMethods($type) as $method_id => $method) {
        $reflector = new \ReflectionClass($method['class']);

        if ($reflector->implementsInterface('\Drupal\language\LanguageSwitcherInterface')) {
          $result = $this->negotiator->getNegotiationMethodInstance($method_id)->getLanguageSwitchLinks($this->request, $type, $path);

          if (!empty($result)) {
            // Allow modules to provide translations for specific links.
            $this->moduleHandler->alter('language_switch_links', $result, $type, $path);
            $links = (object) array('links' => $result, 'method_id' => $method_id);
            break;
          }
        }
      }
    }

    return $links;
  }

388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409
  /**
   * {@inheritdoc}
   */
  public function setConfigOverrideLanguage(Language $language = NULL) {
    $this->configFactoryOverride->setLanguage($language);
    return $this;
  }

  /**
   * {@inheritdoc}
   */
  public function getConfigOverrideLanguage() {
    return $this->configFactoryOverride->getLanguage();
  }

  /**
   * {@inheritdoc}
   */
  public function getLanguageConfigOverride($langcode, $name) {
    return $this->configFactoryOverride->getOverride($langcode, $name);
  }

410 411 412 413 414 415 416
  /**
   * {@inheritdoc}
   */
  public function getLanguageConfigOverrideStorage($langcode) {
    return $this->configFactoryOverride->getStorage($langcode);
  }

417 418 419
  /**
   * {@inheritdoc}
   */
420
  public function getStandardLanguageListWithoutConfigured() {
421 422 423 424 425 426 427 428 429 430 431 432 433
    $languages = $this->getLanguages();
    $predefined = $this->getStandardLanguageList();
    foreach ($predefined as $key => $value) {
      if (isset($languages[$key])) {
        unset($predefined[$key]);
        continue;
      }
      $predefined[$key] = $this->t($value[0]);
    }
    asort($predefined);
    return $predefined;
  }

434
}