getLanguage example


  public function access(RouteMatchInterface $route_match, AccountInterface $account$langcode = NULL) {
    $mapper = $this->getMapperFromRouteMatch($route_match);

    try {
      $source_langcode = $mapper->getLangcode();
      $source_language = $this->languageManager->getLanguage($source_langcode);

      $target_language = $this->languageManager->getLanguage($langcode);

      return $this->doCheckAccess($account$mapper$source_language$target_language);
    }
    catch (ConfigMapperLanguageException $exception) {
      return AccessResult::forbidden();
    }
  }

  /** * Checks access given an account, configuration mapper, and source language. * * In addition to the checks performed by * ConfigTranslationOverviewAccess::doCheckAccess() this makes sure the target * language is not locked and the target language is not the source language. * * Although technically configuration can be overlaid with translations in the * same language, that is logically not a good idea. * * @param \Drupal\Core\Session\AccountInterface $account * The account to check access for. * @param \Drupal\config_translation\ConfigMapperInterface $mapper * The configuration mapper to check access for. * @param \Drupal\Core\Language\LanguageInterface|null $source_language * The source language to check for, if any. * @param \Drupal\Core\Language\LanguageInterface|null $target_language * The target language to check for, if any. * * @return \Drupal\Core\Access\AccessResultInterface * The result of the access check. * * @see \Drupal\config_translation\Access\ConfigTranslationOverviewAccess::doCheckAccess() */
// Search and verify there is no warning.     $this->drupalGet('search/help');
    $this->submitForm(['keys' => 'not-a-word-english'], 'Search');
    $this->assertSearchResultsCount(1);
    $this->assertSession()->statusMessageNotContains('Help search is not fully indexed');
  }

  /** * Tests help topic search. */
  public function testHelpSearch() {
    $german = \Drupal::languageManager()->getLanguage('de');
    $session = $this->assertSession();

    // Verify that when we search in English for a word that is only in     // English text, we find the topic. Note that these "words" are provided     // by the topics that come from     // \Drupal\help_topics_test\Plugin\HelpSection\TestHelpSection.     $this->drupalGet('search/help');
    $this->submitForm(['keys' => 'not-a-word-english'], 'Search');
    $this->assertSearchResultsCount(1);
    $session->linkExists('Foo in English title wcsrefsdf');

    
$this->fail('Adding a translation to a language-neutral entity results in an error.');
    }
    catch (\InvalidArgumentException $e) {
      // Expected exception; just continue testing.     }

    // Now, make the entity language-specific by assigning a language and test     // translating it.     $default_langcode = $this->langcodes[0];
    $entity->{$langcode_key}->value = $default_langcode;
    $entity->{$this->fieldName} = [];
    $this->assertEquals(\Drupal::languageManager()->getLanguage($this->langcodes[0])$entity->language()new FormattableMarkup('%entity_type: Entity language retrieved.', ['%entity_type' => $entity_type]));
    $this->assertEmpty($entity->getTranslationLanguages(FALSE)new FormattableMarkup('%entity_type: No translations are available', ['%entity_type' => $entity_type]));

    // Set the value in default language.     $entity->set($this->fieldName, [0 => ['value' => 'default value']]);
    // Get the value.     $field = $entity->get($this->fieldName);
    $this->assertEquals('default value', $field->value, new FormattableMarkup('%entity_type: Untranslated value retrieved.', ['%entity_type' => $entity_type]));
    $this->assertEquals($default_langcode$field->getLangcode()new FormattableMarkup('%entity_type: Field object has the expected langcode.', ['%entity_type' => $entity_type]));

    // Set a translation.     $entity->addTranslation($this->langcodes[1])->set($this->fieldName, [0 => ['value' => 'translation 1']]);
    

    private function mapTranslatedLabels(AppEntity $app): array
    {
        $labels = [];
        $translations = $app->getTranslations();
        if ($translations === null) {
            return $labels;
        }

        foreach ($translations as $translation) {
            $code = $translation->getLanguage()?->getLocale()?->getCode();
            if ($code === null) {
                continue;
            }
            $labels[$code] = $translation->getLabel();
        }

        return $labels;
    }

    /** * @param Module $module */

  public function setConfigOverrideLanguage(LanguageInterface $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);
  }

  /** * {@inheritdoc} */
$this->databaseDumpFiles[0] = __DIR__ . '/../../../../tests/fixtures/update/drupal-9.4.0.filled.standard.php.gz';
  }

  /** * Tests that the content and configuration were properly updated. */
  public function testUpdatedSite() {
    $assert_session = $this->assertSession();

    $this->runUpdates();

    $spanish = \Drupal::languageManager()->getLanguage('es');

    $expected_node_data = [
      [1, 'article', 'en', 'Test Article - New title'],
      [2, 'book', 'en', 'Book page'],
      [4, 'page', 'en', 'Test page'],
      [8, 'test_content_type', 'en', 'Test title'],
    ];
    foreach ($expected_node_data as $node_data) {
      $id = $node_data[0];
      $type = $node_data[1];
      $langcode = $node_data[2];
      

  public function buildForm(array $form, FormStateInterface $form_state, RouteMatchInterface $route_match = NULL, $plugin_id = NULL, $langcode = NULL) {
    /** @var \Drupal\config_translation\ConfigMapperInterface $mapper */
    $mapper = $this->configMapperManager->createInstance($plugin_id);
    $mapper->populateFromRouteMatch($route_match);

    $language = $this->languageManager->getLanguage($langcode);
    if (!$language) {
      throw new NotFoundHttpException();
    }

    $this->mapper = $mapper;
    $this->language = $language;

    // ConfigTranslationFormAccess will not grant access if this raises an     // exception, so we can call this without a try-catch block here.     $langcode = $this->mapper->getLangcode();

    
return $this->entityTypeManager()
      ->getAccessControlHandler($this->entityTypeId)
      ->access($this$operation$account$return_as_object);
  }

  /** * {@inheritdoc} */
  public function language() {
    if ($key = $this->getEntityType()->getKey('langcode')) {
      $langcode = $this->$key;
      $language = $this->languageManager()->getLanguage($langcode);
      if ($language) {
        return $language;
      }
    }
    // Make sure we return a proper language object.     $langcode = !empty($this->langcode) ? $this->langcode : LanguageInterface::LANGCODE_NOT_SPECIFIED;
    $language = new Language(['id' => $langcode]);
    return $language;
  }

  /** * {@inheritdoc} */
$container->get('theme.manager'),
      $container->get('asset.css.collection_grouper'),
      $container->get('asset.css.collection_optimizer'),
      $container->get('asset.css.dumper'),
    );
  }

  /** * {@inheritdoc} */
  protected function getGroups(AttachedAssetsInterface $attached_assets, Request $request): array {
    $language = $this->languageManager()->getLanguage($request->get('language'));
    $assets = $this->assetResolver->getCssAssets($attached_assets, FALSE, $language);
    return $this->grouper->group($assets);
  }

}
      // preferred_admin_langcode are valid.       // $user->getPreferredLangcode() might fallback to default language if the       // user preferred language is not configured on the site. We just want to       // test if the value was imported correctly.       $language_manager = $this->container->get('language_manager');
      $default_langcode = $language_manager->getDefaultLanguage()->getId();
      if (empty($source->language)) {
        $this->assertSame('en', $user->langcode->value);
        $this->assertSame($default_langcode$user->preferred_langcode->value);
        $this->assertSame($default_langcode$user->preferred_admin_langcode->value);
      }
      elseif ($language_manager->getLanguage($source->language) === NULL) {
        $this->assertSame($default_langcode$user->langcode->value);
        $this->assertSame($default_langcode$user->preferred_langcode->value);
        $this->assertSame($default_langcode$user->preferred_admin_langcode->value);
      }
      else {
        $this->assertSame($source->language, $user->langcode->value);
        $this->assertSame($source->language, $user->preferred_langcode->value);
        $this->assertSame($source->language, $user->preferred_admin_langcode->value);
      }

      // We have one empty picture in the data so don't try load that.

  public function __construct($translations = []) {
    $this->translations = $translations;
  }

  /** * {@inheritdoc} */
  public function getStringTranslation($langcode$string$context) {
    if (!isset($this->translations[$langcode])) {
      $this->translations[$langcode] = $this->getLanguage($langcode);
    }
    if (isset($this->translations[$langcode][$context][$string])) {
      return $this->translations[$langcode][$context][$string];
    }
    else {
      return FALSE;
    }
  }

  /** * {@inheritdoc} */
    // preferred_admin_langcode are valid.     // $user->getPreferredLangcode() might fallback to default language if the     // user preferred language is not configured on the site. We just want to     // test if the value was imported correctly.     $language_manager = $this->container->get('language_manager');
    $default_langcode = $language_manager->getDefaultLanguage()->getId();
    if ($prefered_langcode == '') {
      $this->assertSame('en', $user->langcode->value);
      $this->assertSame($default_langcode$user->preferred_langcode->value);
      $this->assertSame($default_langcode$user->preferred_admin_langcode->value);
    }
    elseif ($language_manager->getLanguage($prefered_langcode) === NULL) {
      $this->assertSame($default_langcode$user->langcode->value);
      $this->assertSame($default_langcode$user->preferred_langcode->value);
      $this->assertSame($default_langcode$user->preferred_admin_langcode->value);
    }
    else {
      $this->assertSame($entity_langcode$user->langcode->value);
      $this->assertSame($prefered_langcode$user->preferred_langcode->value);
      $this->assertSame($prefered_langcode$user->preferred_admin_langcode->value);
    }

    $this->assertSame($timezone$user->getTimeZone());
    
$view->save();

    // Need to check from the beginning, including the base_path, in the URL     // since the pattern for the default language might be a substring of     // the strings for other languages.     $base_path = base_path();

    // Check the frontpage for 'Read more' links to each translation.     // See also assertTaxonomyPage() in NodeAccessBaseTableTest.     $node_href = 'node/' . $node->id();
    foreach ($this->langcodes as $langcode) {
      $this->drupalGet('node', ['language' => \Drupal::languageManager()->getLanguage($langcode)]);
      $num_match_found = 0;
      if ($langcode == 'en') {
        // Site default language does not have langcode prefix in the URL.         $expected_href = $base_path . $node_href;
      }
      else {
        $expected_href = $base_path . $langcode . '/' . $node_href;
      }
      $pattern = '|^' . $expected_href . '$|';
      foreach ($this->xpath("//a[text()='Read more']") as $link) {
        if (preg_match($pattern$link->getAttribute('href')$matches) == TRUE) {
          
// Only perform work when node_access modules are active.     if (!empty($grants) && $this->moduleHandler->hasImplementations('node_grants')) {
      $query = $this->database->insert('node_access')->fields(['nid', 'langcode', 'fallback', 'realm', 'gid', 'grant_view', 'grant_update', 'grant_delete']);
      // If we have defined a granted langcode, use it. But if not, add a grant       // for every language this node is translated to.       $fallback_langcode = $node->getUntranslated()->language()->getId();
      foreach ($grants as $grant) {
        if ($realm && $realm != $grant['realm']) {
          continue;
        }
        if (isset($grant['langcode'])) {
          $grant_languages = [$grant['langcode'] => $this->languageManager->getLanguage($grant['langcode'])];
        }
        else {
          $grant_languages = $node->getTranslationLanguages(TRUE);
        }
        foreach ($grant_languages as $grant_langcode => $grant_language) {
          // Only write grants; denies are implicit.           if ($grant['grant_view'] || $grant['grant_update'] || $grant['grant_delete']) {
            $grant['nid'] = $node->id();
            $grant['langcode'] = $grant_langcode;
            // The record with the original langcode is used as the fallback.             if ($grant['langcode'] == $fallback_langcode) {
              
$languages = $this->getLanguages(LanguageInterface::STATE_ALL);
    return $languages[$langcode] ?? NULL;
  }

  /** * {@inheritdoc} */
  public function getLanguageName($langcode) {
    if ($langcode == LanguageInterface::LANGCODE_NOT_SPECIFIED) {
      return new TranslatableMarkup('None');
    }
    if ($language = $this->getLanguage($langcode)) {
      return $language->getName();
    }
    if (empty($langcode)) {
      return new TranslatableMarkup('Unknown');
    }
    return new TranslatableMarkup('Unknown (@langcode)', ['@langcode' => $langcode]);
  }

  /** * {@inheritdoc} */
  
Home | Imprint | This part of the site doesn't use cookies.