getCurrentLanguage example


  public static function create(ContainerInterface $container, array $configuration$plugin_id$plugin_definition) {
    return new static($plugin_id$plugin_definition$configuration['field_definition']$configuration['settings']$configuration['label']$configuration['view_mode']$configuration['third_party_settings']);
  }

  /** * {@inheritdoc} */
  public function view(FieldItemListInterface $items$langcode = NULL) {
    // Default the language to the current content language.     if (empty($langcode)) {
      $langcode = \Drupal::languageManager()->getCurrentLanguage(LanguageInterface::TYPE_CONTENT)->getId();
    }
    $elements = $this->viewElements($items$langcode);

    // If there are actual renderable children, use #theme => field, otherwise,     // let access cacheability metadata pass through for correct bubbling.     if (Element::children($elements)) {
      $entity = $items->getEntity();
      $entity_type = $entity->getEntityTypeId();
      $field_name = $this->fieldDefinition->getName();
      $info = [
        '#theme' => 'field',
        

  protected function getAllDisplayModesByEntityType($display_type) {
    if (!isset($this->displayModeInfo[$display_type])) {
      $key = 'entity_' . $display_type . '_info';
      $entity_type_id = 'entity_' . $display_type;
      $langcode = $this->languageManager->getCurrentLanguage(LanguageInterface::TYPE_INTERFACE)->getId();
      if ($cache = $this->cacheGet("$key:$langcode")) {
        $this->displayModeInfo[$display_type] = $cache->data;
      }
      else {
        $this->displayModeInfo[$display_type] = [];
        foreach ($this->entityTypeManager->getStorage($entity_type_id)->loadMultiple() as $display_mode) {
          [$display_mode_entity_type$display_mode_name] = explode('.', $display_mode->id(), 2);
          $this->displayModeInfo[$display_type][$display_mode_entity_type][$display_mode_name] = $display_mode->toArray();
        }
        $this->moduleHandler->alter($key$this->displayModeInfo[$display_type]);
        $this->cacheSet("$key:$langcode", $this->displayModeInfo[$display_type], CacheBackendInterface::CACHE_PERMANENT, ['entity_types', 'entity_field_info']);
      }

  public function __construct(ArgumentResolverInterface $argument_resolver, RequestStack $request_stack, RouteMatchInterface $route_match, RouteProviderInterface $route_provider, ModuleHandlerInterface $module_handler, CacheBackendInterface $cache, LanguageManagerInterface $language_manager, AccessManagerInterface $access_manager, AccountInterface $account) {
    $this->factory = new ContainerFactory($this, '\Drupal\Core\Menu\LocalTaskInterface');
    $this->argumentResolver = $argument_resolver;
    $this->requestStack = $request_stack;
    $this->routeMatch = $route_match;
    $this->routeProvider = $route_provider;
    $this->accessManager = $access_manager;
    $this->account = $account;
    $this->moduleHandler = $module_handler;
    $this->alterInfo('local_tasks');
    $this->setCacheBackend($cache, 'local_task_plugins:' . $language_manager->getCurrentLanguage()->getId()['local_task']);
  }

  /** * {@inheritdoc} */
  protected function getDiscovery() {
    if (!isset($this->discovery)) {
      $yaml_discovery = new YamlDiscovery('links.task', $this->moduleHandler->getModuleDirectories());
      $yaml_discovery->addTranslatableProperty('title', 'title_context');
      $this->discovery = new ContainerDerivativeDiscoveryDecorator($yaml_discovery);
    }
    
/** * {@inheritdoc} */
  protected $defaultTheme = 'stark';

  /** * Creates a comment, then tests the tokens generated from it. */
  public function testCommentTokenReplacement() {
    $token_service = \Drupal::token();
    $language_interface = \Drupal::languageManager()->getCurrentLanguage();
    $url_options = [
      'absolute' => TRUE,
      'language' => $language_interface,
    ];

    // Setup vocabulary.     Vocabulary::create([
      'vid' => 'tags',
      'name' => 'Tags',
    ])->save();

    
$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);

    
// Update zh-hant password_reset config with custom translation.     $configLanguageOverride = $this->container->get('language_manager')->getLanguageConfigOverride('zh-hant', 'user.mail');
    $configLanguageOverride->set('password_reset.subject', 'hant subject [user:display-name]')->save();
    $configLanguageOverride->set('password_reset.body', 'hant body [user:display-name] and token link [user:one-time-login-url]')->save();

    // Update fr password_reset config with custom translation.     $configLanguageOverride = $this->container->get('language_manager')->getLanguageConfigOverride('fr', 'user.mail');
    $configLanguageOverride->set('password_reset.subject', 'fr subject [user:display-name]')->save();
    $configLanguageOverride->set('password_reset.body', 'fr body [user:display-name] and token link [user:one-time-login-url]')->save();

    // Current language is 'en'.     $currentLanguage = $this->container->get('language_manager')->getCurrentLanguage()->getId();
    $this->assertSame('en', $currentLanguage);

    // Set preferred_langcode to 'zh-hant'.     $user = $this->createUser();
    $user->set('preferred_langcode', 'zh-hant')->save();
    $preferredLangcode = $user->getPreferredLangcode();
    $this->assertSame('zh-hant', $preferredLangcode);

    // Recovery email should respect user preferred langcode by default if     // langcode not set.     $this->config('system.site')->set('mail', 'test@example.com')->save();
    
/** * {@inheritdoc} */
  public function setLocale($locale) {
    $this->locale = $locale;
  }

  /** * {@inheritdoc} */
  public function getLocale() {
    return $this->locale ? $this->locale : \Drupal::languageManager()->getCurrentLanguage()->getId();
  }

  /** * Processes the parameters array for use with TranslatableMarkup. */
  protected function processParameters(array $parameters) {
    $return = [];
    foreach ($parameters as $key => $value) {
      // We allow the values in the parameters to be safe string objects. This       // can be useful when we want to use parameter values that are       // TranslatableMarkup.

  public static function processMachineName(&$element, FormStateInterface $form_state, &$complete_form) {
    // We need to pass the langcode to the client.     $language = \Drupal::languageManager()->getCurrentLanguage();

    // Apply default form element properties.     $element += [
      '#title' => t('Machine-readable name'),
      '#description' => t('A unique machine-readable name. Can only contain lowercase letters, numbers, and underscores.'),
      '#machine_name' => [],
      '#field_prefix' => '',
      '#field_suffix' => '',
      '#suffix' => '',
    ];
    // A form element that only wants to set one #machine_name property (usually
'config_export' => [
        'id',
      ],
      'list_cache_tags' => [$this->entityTypeId . '_list'],
    ]);

    $this->moduleHandler = $this->prophesize(ModuleHandlerInterface::class);

    $this->uuidService = $this->prophesize(UuidInterface::class);

    $this->languageManager = $this->prophesize(LanguageManagerInterface::class);
    $this->languageManager->getCurrentLanguage()->willReturn(new Language(['id' => 'hu']));

    $this->configFactory = $this->prophesize(ConfigFactoryInterface::class);

    $this->entityQuery = $this->prophesize(QueryInterface::class);
    $entity_query_factory = $this->prophesize(QueryFactoryInterface::class);
    $entity_query_factory->get($entity_type, 'AND')->willReturn($this->entityQuery->reveal());

    $this->entityStorage = new ConfigEntityStorage($entity_type$this->configFactory->reveal()$this->uuidService->reveal()$this->languageManager->reveal()new MemoryCache());
    $this->entityStorage->setModuleHandler($this->moduleHandler->reveal());

    $entity_type_manager = $this->prophesize(EntityTypeManagerInterface::class);
    
return NULL;
      }
      $entity = reset($entities);
      // If the entity type is translatable, ensure we return the proper       // translation object for the current context.       if ($entity instanceof TranslatableInterface && $entity->isTranslatable()) {
        // @see https://www.drupal.org/project/drupal/issues/2624770         $entity = $this->entityRepository->getTranslationFromContext($entity, NULL, ['operation' => 'entity_upcast']);
        // JSON:API always has only one method per route.         $method = $defaults[RouteObjectInterface::ROUTE_OBJECT]->getMethods()[0];
        if (in_array($method['PATCH', 'DELETE'], TRUE)) {
          $current_content_language = $this->languageManager->getCurrentLanguage(LanguageInterface::TYPE_CONTENT)->getId();
          if ($method === 'DELETE' && (!$entity->isDefaultTranslation() || $entity->language()->getId() !== $current_content_language)) {
            throw new MethodNotAllowedHttpException(['GET'], 'Deleting a resource object translation is not yet supported. See https://www.drupal.org/docs/8/modules/jsonapi/translations.');
          }
          if ($method === 'PATCH' && $entity->language()->getId() !== $current_content_language) {
            $available_translations = implode(', ', array_keys($entity->getTranslationLanguages()));
            throw new MethodNotAllowedHttpException(['GET']sprintf('The requested translation of the resource object does not exist, instead modify one of the translations that do exist: %s.', $available_translations));
          }
        }
      }
      return $entity;
    }
    

  protected function processAssetLibraries(AttachedAssetsInterface $assets, array $placeholders) {
    $variables = [];

    $maintenance_mode = defined('MAINTENANCE_MODE') || \Drupal::state()->get('system.maintenance_mode');

    // Print styles - if present.     if (isset($placeholders['styles'])) {
      // Optimize CSS if necessary, but only during normal site operation.       $optimize_css = !$maintenance_mode && $this->config->get('css.preprocess');
      $variables['styles'] = $this->cssCollectionRenderer->render($this->assetResolver->getCssAssets($assets$optimize_css$this->languageManager->getCurrentLanguage()));
    }

    // Print scripts - if any are present.     if (isset($placeholders['scripts']) || isset($placeholders['scripts_bottom'])) {
      // Optimize JS if necessary, but only during normal site operation.       $optimize_js = !$maintenance_mode && $this->config->get('js.preprocess');
      [$js_assets_header$js_assets_footer] = $this->assetResolver->getJsAssets($assets$optimize_js$this->languageManager->getCurrentLanguage());
      $variables['scripts'] = $this->jsCollectionRenderer->render($js_assets_header);
      $variables['scripts_bottom'] = $this->jsCollectionRenderer->render($js_assets_footer);
    }

    

  }

  /** * {@inheritdoc} */
  public function getPathByAlias($alias$langcode = NULL) {
    // If no language is explicitly specified we default to the current URL     // language. If we used a language different from the one conveyed by the     // requested URL, we might end up being unable to check if there is a path     // alias matching the URL path.     $langcode = $langcode ?: $this->languageManager->getCurrentLanguage(LanguageInterface::TYPE_URL)->getId();

    // If we already know that there are no paths for this alias simply return.     if (empty($alias) || !empty($this->noPath[$langcode][$alias])) {
      return $alias;
    }

    // Look for the alias within the cached map.     if (isset($this->lookupMap[$langcode]) && ($path = array_search($alias$this->lookupMap[$langcode]))) {
      return $path;
    }

    
if ($css_group['type'] === 'external') {
        // We don't do any aggregation and hence also no caching for external         // CSS assets.         $uri = $css_group['items'][0]['data'];
        $css_assets[$order]['data'] = $uri;
      }
    }

    // All asset group URLs will have exactly the same query arguments, except     // for the delta, so prepare them in advance.     $query_args = [
      'language' => $this->languageManager->getCurrentLanguage()->getId(),
      'theme' => $this->themeManager->getActiveTheme()->getName(),
      'include' => UrlHelper::compressQueryParameter(implode(',', $this->dependencyResolver->getMinimalRepresentativeSubset($libraries))),
    ];
    $ajax_page_state = $this->requestStack->getCurrentRequest()->get('ajax_page_state');
    $already_loaded = isset($ajax_page_state) ? explode(',', $ajax_page_state['libraries']) : [];
    if ($already_loaded) {
      $query_args['exclude'] = UrlHelper::compressQueryParameter(implode(',', $this->dependencyResolver->getMinimalRepresentativeSubset($already_loaded)));
    }

    // Generate a URL for each group of assets, but do not process them inline,     // this is done using optimizeGroup() when the asset path is requested.

  public function testOrder() {
    $expected_commands = [];

    // Expected commands, in a very specific order.     $asset_resolver = \Drupal::service('asset.resolver');
    $css_collection_renderer = \Drupal::service('asset.css.collection_renderer');
    $js_collection_renderer = \Drupal::service('asset.js.collection_renderer');
    $renderer = \Drupal::service('renderer');
    $build['#attached']['library'][] = 'ajax_test/order-css-command';
    $assets = AttachedAssets::createFromRenderArray($build);
    $css_render_array = $css_collection_renderer->render($asset_resolver->getCssAssets($assets, FALSE, \Drupal::languageManager()->getCurrentLanguage()));
    $expected_commands[1] = new AddCssCommand(array_column($css_render_array, '#attributes'));
    $build['#attached']['library'][] = 'ajax_test/order-header-js-command';
    $build['#attached']['library'][] = 'ajax_test/order-footer-js-command';
    $assets = AttachedAssets::createFromRenderArray($build);
    [$js_assets_header$js_assets_footer] = $asset_resolver->getJsAssets($assets, FALSE, \Drupal::languageManager()->getCurrentLanguage());
    $js_header_render_array = $js_collection_renderer->render($js_assets_header);
    $js_footer_render_array = $js_collection_renderer->render($js_assets_footer);
    $expected_commands[2] = new AddJsCommand(array_column($js_header_render_array, '#attributes'), 'head');
    $expected_commands[3] = new AddJsCommand(array_column($js_footer_render_array, '#attributes'));
    $expected_commands[4] = new HtmlCommand('body', 'Hello, world!');

    
$this->container->get('typed_data_manager')->willReturn($this->typedDataManager->reveal());

    $this->moduleHandler = $this->prophesize(ModuleHandlerInterface::class);
    $this->moduleHandler->alter('entity_base_field_info', Argument::type('array'), Argument::any())->willReturn(NULL);
    $this->moduleHandler->alter('entity_bundle_field_info', Argument::type('array'), Argument::any(), Argument::type('string'))->willReturn(NULL);

    $this->cacheBackend = $this->prophesize(CacheBackendInterface::class);
    $this->cacheTagsInvalidator = $this->prophesize(CacheTagsInvalidatorInterface::class);

    $language = new Language(['id' => 'en']);
    $this->languageManager = $this->prophesize(LanguageManagerInterface::class);
    $this->languageManager->getCurrentLanguage()->willReturn($language);
    $this->languageManager->getLanguages()->willReturn(['en' => (object) ['id' => 'en']]);

    $this->keyValueFactory = $this->prophesize(KeyValueFactoryInterface::class);

    $this->entityTypeManager = $this->prophesize(EntityTypeManagerInterface::class);
    $this->entityTypeRepository = $this->prophesize(EntityTypeRepositoryInterface::class);
    $this->entityTypeBundleInfo = $this->prophesize(EntityTypeBundleInfoInterface::class);
    $this->entityDisplayRepository = $this->prophesize(EntityDisplayRepositoryInterface::class);
    $this->entityLastInstalledSchemaRepository = $this->prophesize(EntityLastInstalledSchemaRepositoryInterface::class);

    $this->entityFieldManager = new TestEntityFieldManager($this->entityTypeManager->reveal()$this->entityTypeBundleInfo->reveal()$this->entityDisplayRepository->reveal()$this->typedDataManager->reveal()$this->languageManager->reveal()$this->keyValueFactory->reveal()$this->moduleHandler->reveal()$this->cacheBackend->reveal()$this->entityLastInstalledSchemaRepository->reveal());
  }
Home | Imprint | This part of the site doesn't use cookies.