Language example



        if (AppServices::request() instanceof IncomingRequest) {
            $requestLocale = AppServices::request()->getLocale();
        } else {
            $requestLocale = Locale::getDefault();
        }

        // Use '?:' for empty string check         $locale = $locale ?: $requestLocale;

        return new Language($locale);
    }

    /** * The Logger class is a PSR-3 compatible Logging class that supports * multiple handlers that process the actual logging. * * @return Logger */
    public static function logger(bool $getShared = true)
    {
        if ($getShared) {
            
$this->drupalLogin($admin_user);

    // Add custom language.     $edit = [
      'predefined_langcode' => 'custom',
    ];
    $this->drupalGet('admin/config/regional/language/add');
    $this->submitForm($edit, 'Add custom language');
    // Test validation on missing values.     $this->assertSession()->statusMessageContains('Language code field is required.', 'error');
    $this->assertSession()->statusMessageContains('Language name field is required.', 'error');
    $empty_language = new Language();
    $this->assertSession()->checkboxChecked('edit-direction-' . $empty_language->getDirection());
    $this->assertSession()->addressEquals(Url::fromRoute('language.add'));

    // Test validation of invalid values.     $edit = [
      'predefined_langcode' => 'custom',
      'langcode' => 'white space',
      'label' => '<strong>evil markup</strong>',
      'direction' => LanguageInterface::DIRECTION_LTR,
    ];
    $this->drupalGet('admin/config/regional/language/add');
    
$this->assertRows([
      [
        'title' => 'example EN',
        'sticky' => 'Off',
      ],
      [
        'title' => 'example EN',
        'sticky' => 'Off',
      ],
    ]);

    $this->drupalGet('test_entity_field_renderers/language_interface', ['language' => new Language(['id' => 'es'])]);
    $this->assertRows([
      [
        'title' => 'example ES',
        'sticky' => 'On',
      ],
      [
        'title' => 'example ES',
        'sticky' => 'On',
      ],
    ]);

    

  public function getDefaultLockedLanguages($weight = 0) {
    $languages = [];

    $locked_language = [
      'default' => FALSE,
      'locked' => TRUE,
      'direction' => LanguageInterface::DIRECTION_LTR,
    ];
    // This is called very early while initializing the language system. Prevent     // early t() calls by using the TranslatableMarkup.     $languages[LanguageInterface::LANGCODE_NOT_SPECIFIED] = new Language([
      'id' => LanguageInterface::LANGCODE_NOT_SPECIFIED,
      'name' => new TranslatableMarkup('Not specified'),
      'weight' => ++$weight,
    ] + $locked_language);

    $languages[LanguageInterface::LANGCODE_NOT_APPLICABLE] = new Language([
      'id' => LanguageInterface::LANGCODE_NOT_APPLICABLE,
      'name' => new TranslatableMarkup('Not applicable'),
      'weight' => ++$weight,
    ] + $locked_language);

    
    $source = 'en';
    $target = 'it';

    // Set the mock language manager.     $language_manager = $this->createMock('Drupal\Core\Language\LanguageManagerInterface');
    $language_manager->expects($this->once())
      ->method('getLanguages')
      ->willReturn([$source => []$target => []]);
    $language_manager->expects($this->any())
      ->method('getLanguage')
      ->willReturnMap([
        [$sourcenew Language(['id' => $source])],
        [$targetnew Language(['id' => $target])],
      ]);

    // Set the mock entity. We need to use ContentEntityBase for mocking due to     // issues with phpunit and multiple interfaces.     $entity = $this->getMockBuilder('Drupal\Core\Entity\ContentEntityBase')
      ->disableOriginalConstructor()
      ->getMock();
    $entity->expects($this->once())
      ->method('getEntityTypeId');
    $entity->expects($this->once())
      
public function __construct(CacheableDependencyInterface $cacheability, ResourceType $resource_type$id$revision_id, array $fields, LinkCollection $links, LanguageInterface $language = NULL) {
    assert(is_null($revision_id) || $resource_type->isVersionable());
    $this->setCacheability($cacheability);
    $this->resourceType = $resource_type;
    $this->resourceIdentifier = new ResourceIdentifier($resource_type$id);
    $this->versionIdentifier = $revision_id ? 'id:' . $revision_id : NULL;
    $this->fields = $fields;
    $this->links = $links->withContext($this);

    // If the specified language empty it falls back the same way as in the entity system     // @see \Drupal\Core\Entity\EntityBase::language()     $this->language = $language ?: new Language(['id' => LanguageInterface::LANGCODE_NOT_SPECIFIED]);
  }

  /** * Creates a new ResourceObject from an entity. * * @param \Drupal\jsonapi\ResourceType\ResourceType $resource_type * The JSON:API resource type of the resource object. * @param \Drupal\Core\Entity\EntityInterface $entity * The entity to be represented by this resource object. * @param \Drupal\jsonapi\JsonApiResource\LinkCollection $links * (optional) Any links for the resource object, if a `self` link is not * provided, one will be automatically added if the resource is locatable * and is not an internal entity. * * @return static * An instantiated resource object. */
/** * {@inheritdoc} */
  protected function getLanguages() {
    if (empty($this->languages)) {
      $this->languages = $this->languageManager()->getLanguages(LanguageInterface::STATE_ALL);
      // If the entity references a language that is not or no longer available,       // we return a mock language object to avoid disrupting the consuming       // code.       if (!isset($this->languages[$this->defaultLangcode])) {
        $this->languages[$this->defaultLangcode] = new Language(['id' => $this->defaultLangcode]);
      }
    }
    return $this->languages;
  }

  /** * {@inheritdoc} */
  public function postCreate(EntityStorageInterface $storage) {
    $this->newRevision = TRUE;
  }

  

      $this->messenger()->addWarning($this->renderer->renderPlain($message));

      $original_langcode = LanguageInterface::LANGCODE_NOT_SPECIFIED;
      $operations_access = FALSE;
    }

    if (!isset($languages[$original_langcode])) {
      // If the language is not configured on the site, create a dummy language       // object for this listing only to ensure the user gets useful info.       $language_name = $this->languageManager->getLanguageName($original_langcode);
      $languages[$original_langcode] = new Language(['id' => $original_langcode, 'name' => $language_name]);
    }

    // We create a fake request object to pass into     // ConfigMapperInterface::populateFromRouteMatch() for the different languages.     // Creating a separate request for each language and route is neither easily     // possible nor performant.     $fake_request = $request->duplicate();

    $page['languages'] = [
      '#type' => 'table',
      '#header' => [$this->t('Language')$this->t('Operations')],
    ];
$this->assertStringContainsString('UNTRANSLATED', (string) $output);

    // Translate the separator.     ConfigurableLanguage::createFromLangcode('nl')->save();
    /** @var \Drupal\language\ConfigurableLanguageManagerInterface $language_manager */
    $language_manager = $this->container->get('language_manager');
    $language_manager->getLanguageConfigOverride('nl', 'core.entity_view_display.entity_test.entity_test.default')
      ->set('content.' . $this->fieldStorage->getName() . '.settings.separator', 'NL_TRANSLATED!')
      ->save();

    $this->container->get('language.config_factory_override')
      ->setLanguage(new Language(['id' => 'nl']));
    $this->container->get('cache_tags.invalidator')->invalidateTags($entity->getCacheTags());
    $display = EntityViewDisplay::collectRenderDisplay($entity, 'default');
    $build = $display->build($entity);
    $output = $this->container->get('renderer')->renderRoot($build);
    $this->assertStringContainsString('NL_TRANSLATED!', (string) $output);
  }

}

class LanguageUnitTest extends UnitTestCase {

  /** * @covers ::__construct */
  public function testConstruct() {
    $name = $this->randomMachineName();
    $language_code = $this->randomMachineName(2);
    $uuid = $this->randomMachineName();
    $language = new Language(['id' => $language_code, 'name' => $name, 'uuid' => $uuid]);
    // Test that nonexistent properties are not added to the language object.     $this->assertTrue(property_exists($language, 'id'));
    $this->assertTrue(property_exists($language, 'name'));
    $this->assertFalse(property_exists($language, 'uuid'));
  }

  /** * @covers ::getName */
  public function testGetName() {
    $name = $this->randomMachineName();
    

  protected function dateFormat($type$langcode) {
    if (!isset($this->dateFormats[$type][$langcode])) {
      $original_language = $this->languageManager->getConfigOverrideLanguage();
      $this->languageManager->setConfigOverrideLanguage(new Language(['id' => $langcode]));
      $this->dateFormats[$type][$langcode] = $this->dateFormatStorage->load($type);
      $this->languageManager->setConfigOverrideLanguage($original_language);
    }
    return $this->dateFormats[$type][$langcode];
  }

  /** * Returns the default country from config. * * @return string * The config setting for country.default. */
    $this->drupalLogout();

    // Place a site branding block in the header region.     $this->drupalPlaceBlock('system_branding_block', [
      'region' => 'header',
      'id' => 'site-branding',
    ]);

    // Access the front page without specifying any valid URL language prefix     // and having as browser language preference a non-default language.     $http_header = ["Accept-Language" => "$langcode_browser_fallback;q=1"];
    $language = new Language(['id' => '']);
    $this->drupalGet('', ['language' => $language]$http_header);

    // Check that the language switcher active link matches the given browser     // language.     $href = Url::fromRoute('<front>')->toString() . $langcode_browser_fallback;
    $this->assertSession()->elementTextEquals('xpath', "//div[@id='block-test-language-block']//a[@class='language-link is-active' and starts-with(@href, '$href')]", $languages[$langcode_browser_fallback]->getName());

    // Check that URLs are rewritten using the given browser language.     $this->assertSession()->elementTextEquals('xpath', "//div[@id='block-site-branding']/a[@rel='home' and @href='$href'][2]", 'Drupal');
  }

  
$validation_constraint_manager = $this->getMockBuilder('\Drupal\Core\Validation\ConstraintManager')
      ->disableOriginalConstructor()
      ->getMock();
    $validation_constraint_manager->expects($this->any())
      ->method('create')
      ->willReturn([]);
    $this->typedDataManager->expects($this->any())
      ->method('getValidationConstraintManager')
      ->willReturn($validation_constraint_manager);

    $not_specified = new Language(['id' => LanguageInterface::LANGCODE_NOT_SPECIFIED, 'locked' => TRUE]);
    $this->languageManager = $this->createMock('\Drupal\Core\Language\LanguageManagerInterface');
    $this->languageManager->expects($this->any())
      ->method('getLanguages')
      ->willReturn([LanguageInterface::LANGCODE_NOT_SPECIFIED => $not_specified]);

    $this->languageManager->expects($this->any())
      ->method('getLanguage')
      ->with(LanguageInterface::LANGCODE_NOT_SPECIFIED)
      ->willReturn($not_specified);

    $this->fieldTypePluginManager = $this->getMockBuilder('\Drupal\Core\Field\FieldTypePluginManager')
      

  public function onConfigSave(ConfigCrudEvent $event) {
    $saved_config = $event->getConfig();
    if ($saved_config->getName() == 'system.site' && $event->isChanged('default_langcode')) {
      $new_default_langcode = $saved_config->get('default_langcode');
      $default_language = $this->configFactory->get('language.entity.' . $new_default_langcode);
      // During an import the language might not exist yet.       if (!$default_language->isNew()) {
        $this->languageDefault->set(new Language($default_language->get()));
        $this->languageManager->reset();

        // Directly update language negotiation settings instead of calling         // language_negotiation_url_prefixes_update() to ensure that the code         // obeys the hook_update_N() restrictions.         $negotiation_config = $this->configFactory->getEditable('language.negotiation');
        $negotiation_changed = FALSE;
        $url_prefixes = $negotiation_config->get('url.prefixes');
        $old_default_langcode = $saved_config->getOriginal('default_langcode');
        if (empty($url_prefixes[$old_default_langcode])) {
          $negotiation_config->set('url.prefixes.' . $old_default_langcode$old_default_langcode);
          

            [-3, [
                new DivisibleBy(['value' => 4]),
                new Negative(),
            ]],
            ['FOO', [
                new Choice(['choices' => ['bar', 'BAR']]),
                new Regex(['pattern' => '/foo/i']),
            ]],
            ['fr', [
                new Country(),
                new Language(),
            ]],
            [[1, 3, 5][
                new Count(['min' => 5]),
                new Unique(),
            ]],
        ];
    }

    /** * @dataProvider getInvalidCombinations */
    
Home | Imprint | This part of the site doesn't use cookies.