languageManager example


  public function __construct($time = 'now', $timezone = NULL, $settings = []) {
    if (!isset($settings['langcode'])) {
      $settings['langcode'] = \Drupal::languageManager()->getCurrentLanguage()->getId();
    }

    // Instantiate the parent class.     parent::__construct($time$timezone$settings);

  }

  /** * Overrides prepareTimezone(). * * Override basic component timezone handling to use Drupal's * knowledge of the preferred user timezone. */
// Store the loaded revision ID the entity has been loaded with to       // keep it safe from changes.       $this->updateLoadedRevisionId();
    }
  }

  /** * {@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} */

  protected static $modules = ['system'];

  /** * {@inheritdoc} */
  protected function setUp(): void {
    parent::setUp();
    // Install default system configuration.     $this->installConfig(['system']);

    $this->interfaceLanguage = \Drupal::languageManager()->getCurrentLanguage();
    $this->tokenService = \Drupal::token();
  }

}

    else {
      $standard_languages = LanguageManager::getStandardLanguageList();
      $label = $standard_languages[$langcode][0];
      $direction = $standard_languages[$langcode][2] ?? ConfigurableLanguage::DIRECTION_LTR;
    }
    $entity->set('id', $langcode);
    $entity->set('label', $label);
    $entity->set('direction', $direction);
    // There is no weight on the edit form. Fetch all configurable languages     // ordered by weight and set the new language to be placed after them.     $languages = \Drupal::languageManager()->getLanguages(ConfigurableLanguage::STATE_CONFIGURABLE);
    $last_language = end($languages);
    $entity->setWeight($last_language->getWeight() + 1);
  }

}

  public function __construct(EntityTypeManagerInterface $entityTypeManager, ModuleHandlerInterface $moduleHandler, StateInterface $state, FileSystemInterface $fileSystem) {
    $this->entityTypeManager = $entityTypeManager;
    $this->moduleHandler = $moduleHandler;
    $this->state = $state;
    $this->fileSystem = $fileSystem;
    $this->termIdMap = [];
    $this->mediaImageIdMap = [];
    $this->nodeIdMap = [];
    $this->enabledLanguages = array_keys(\Drupal::languageManager()->getLanguages());
  }

  /** * {@inheritdoc} */
  public static function create(ContainerInterface $container) {
    return new static(
      $container->get('entity_type.manager'),
      $container->get('module_handler'),
      $container->get('state'),
      $container->get('file_system')
    );
    $admin = $this->drupalCreateUser([
      'bypass node access',
      'administer nodes',
      'translate any entity',
      'administer content translation',
    ]);
    $this->drupalLogin($admin);
    $this->drupalGet('node/' . $node->id() . '/translations');
    $this->assertSession()->statusCodeEquals(200);

    // Create a Catalan translation through the UI.     $url_options = ['language' => \Drupal::languageManager()->getLanguage('ca')];
    $this->drupalGet('node/' . $node->id() . '/translations/add/hu/ca', $url_options);
    $this->assertSession()->statusCodeEquals(200);
    // Save the form.     $this->getSession()->getPage()->pressButton('Save (this translation)');
    $this->assertSession()->statusCodeEquals(200);

    // Check the node access table.     $this->checkRecords(2, 'hu');

    // Programmatically create a translation. This process lets us check that     // both forms and code behave in the same way.
protected static $modules = ['config_test'];

  /** * {@inheritdoc} */
  protected $defaultTheme = 'stark';

  /** * Tests CRUD operations. */
  public function testCRUD() {
    $default_langcode = \Drupal::languageManager()->getDefaultLanguage()->getId();
    // Verify default properties on a newly created empty entity.     $storage = \Drupal::entityTypeManager()->getStorage('config_test');
    $empty = $storage->create();
    $this->assertNull($empty->label);
    $this->assertNull($empty->style);
    $this->assertSame($default_langcode$empty->language()->getId());

    // Verify ConfigEntity properties/methods on the newly created empty entity.     $this->assertTrue($empty->isNew());
    $this->assertNull($empty->getOriginalId());
    $this->assertSame('config_test', $empty->bundle());
    

  protected function instantiateView($form, FormStateInterface $form_state) {
    // Build the basic view properties and create the view.     $values = [
      'id' => $form_state->getValue('id'),
      'label' => $form_state->getValue('label'),
      'description' => $form_state->getValue('description'),
      'base_table' => $this->base_table,
      'langcode' => \Drupal::languageManager()->getDefaultLanguage()->getId(),
    ];

    $view = View::create($values);

    // Build all display options for this view.     $display_options = $this->buildDisplayOptions($form$form_state);

    // Allow the fully built options to be altered. This happens before adding     // the options to the view, so that once they are eventually added we will     // be able to get all the overrides correct.     $this->alterDisplayOptions($display_options$form$form_state);

    


  /** * Tests up-to-date status tracking. */
  protected function doTestOutdatedStatus() {
    $storage = $this->container->get('entity_type.manager')
      ->getStorage($this->entityTypeId);
    $storage->resetCache([$this->entityId]);
    $entity = $storage->load($this->entityId);
    $langcode = 'fr';
    $languages = \Drupal::languageManager()->getLanguages();

    // Mark translations as outdated.     $edit = ['content_translation[retranslate]' => TRUE];
    $edit_path = $entity->toUrl('edit-form', ['language' => $languages[$langcode]]);
    $this->drupalGet($edit_path);
    $this->submitForm($edit$this->getFormSubmitAction($entity$langcode));
    $storage->resetCache([$this->entityId]);
    $entity = $storage->load($this->entityId);

    // Check that every translation has the correct "outdated" status, and that     // the Translation fieldset is open if the translation is "outdated".
/** * {@inheritdoc} */
  protected function setUp($import_test_views = TRUE): void {
    parent::setUp(FALSE);

    $this->installEntitySchema('node');
    $this->installEntitySchema('user');
    $this->installSchema('node', ['node_access']);
    $this->installConfig(['node', 'language']);

    $this->langcodes = [\Drupal::languageManager()->getDefaultLanguage()->getId()];
    for ($i = 0; $i < 2; $i++) {
      $langcode = 'l' . $i;
      $this->langcodes[] = $langcode;
      ConfigurableLanguage::createFromLangcode($langcode)->save();
    }

    $this->testAuthor = User::create([
      'name' => 'foo',
    ]);
    $this->testAuthor->save();

    
// Test without errors displayed to users.     \Drupal::service('plugin.manager.mail')->mail('default', 'default', 'test@example.com', 'en', ['_error_message' => '']);
    $this->assertEmpty(\Drupal::messenger()->messagesByType(MessengerInterface::TYPE_ERROR));
  }

  /** * Tests that message sending may be canceled. * * @see mail_cancel_test_mail_alter() */
  public function testCancelMessage() {
    $language_interface = \Drupal::languageManager()->getCurrentLanguage();

    // Reset the state variable that holds sent messages.     \Drupal::state()->set('system.test_mail_collector', []);

    // Send a test message that mail_cancel_test_alter should cancel.     \Drupal::service('plugin.manager.mail')->mail('mail_cancel_test', 'cancel_test', 'cancel@example.com', $language_interface->getId());
    // Retrieve sent message.     $captured_emails = \Drupal::state()->get('system.test_mail_collector');
    $sent_message = end($captured_emails);

    // Assert that the message was not actually sent.
$this->assetResolver = $this->container->get('asset.resolver');
    $this->renderer = $this->container->get('renderer');
    $this->fileUrlGenerator = $this->container->get('file_url_generator');
  }

  /** * Tests that default CSS and JavaScript is empty. */
  public function testDefault() {
    $assets = new AttachedAssets();
    $this->assertEquals([]$this->assetResolver->getCssAssets($assets, FALSE, \Drupal::languageManager()->getCurrentLanguage()), 'Default CSS is empty.');
    [$js_assets_header$js_assets_footer] = $this->assetResolver->getJsAssets($assets, FALSE, \Drupal::languageManager()->getCurrentLanguage());
    $this->assertEquals([]$js_assets_header, 'Default header JavaScript is empty.');
    $this->assertEquals([]$js_assets_footer, 'Default footer JavaScript is empty.');
  }

  /** * Tests non-existing libraries. */
  public function testLibraryUnknown() {
    $build['#attached']['library'][] = 'core/unknown';
    $assets = AttachedAssets::createFromRenderArray($build);

    
$file = File::create([
      'uri' => $filepath,
      'uid' => $this->adminUser->id(),
    ]);
    $file->save();

    // Setup the site languages by installing two languages.     // Set the default language in order for the translated string to be registered     // into database when seen by t(). Without doing this, our target string     // is for some reason not found when doing translate search. This might     // be some bug.     $default_language = \Drupal::languageManager()->getDefaultLanguage();
    ConfigurableLanguage::createFromLangcode($langcode_browser_fallback)->save();
    $this->config('system.site')->set('default_langcode', $langcode_browser_fallback)->save();
    ConfigurableLanguage::createFromLangcode($langcode)->save();

    // We will look for this string in the admin/config screen to see if the     // corresponding translated string is shown.     $default_string = 'Hide descriptions';

    // First visit this page to make sure our target string is searchable.     $this->drupalGet('admin/config');

    
    $this->rebuildContainer();

    /** @var \Drupal\Core\Config\StorageInterface $override_sync */
    $override_sync = $sync->createCollection('language.fr');
    // Create some overrides in sync.     $override_sync->write('system.site', ['name' => 'FR default site name']);
    $override_sync->write('system.maintenance', ['message' => 'FR message: @site is currently under maintenance. We should be back shortly. Thank you for your patience']);

    $this->configImporter()->import();
    $this->rebuildContainer();

    $override = \Drupal::languageManager()->getLanguageConfigOverride('fr', 'system.site');
    $this->assertEquals('FR default site name', $override->get('name'));
    $this->drupalGet('fr');
    $this->assertSession()->pageTextContains('FR default site name');

    $this->drupalLogin($this->rootUser);
    $this->drupalGet('admin/config/development/maintenance/translate/fr/edit');
    $this->assertSession()->pageTextContains('FR message: @site is currently under maintenance. We should be back shortly. Thank you for your patience');
  }

  /** * Tests that configuration events are not fired during a sync of overrides. */
public function testNew() {
    $dynamic_name = 'config_test.dynamic.new';
    $storage = $this->container->get('config.storage');
    $sync = $this->container->get('config.storage.sync');

    // Verify the configuration to create does not exist yet.     $this->assertFalse($storage->exists($dynamic_name)$dynamic_name . ' not found.');

    // Create new config entity.     $original_dynamic_data = [
      'uuid' => '30df59bd-7b03-4cf7-bb35-d42fc49f0651',
      'langcode' => \Drupal::languageManager()->getDefaultLanguage()->getId(),
      'status' => TRUE,
      'dependencies' => [],
      'id' => 'new',
      'label' => 'New',
      'weight' => 0,
      'style' => '',
      'size' => '',
      'size_value' => '',
      'protected_property' => '',
    ];
    $sync->write($dynamic_name$original_dynamic_data);

    
Home | Imprint | This part of the site doesn't use cookies.