translation example


  public static function finished($success$results$operations$elapsed) {
    $successes = $results['successes'];
    $failures = $results['failures'];

    // If we had any successes log that for the user.     if ($successes > 0) {
      \Drupal::messenger()->addStatus(\Drupal::translation()
        ->formatPlural($successes, 'Completed 1 upgrade task successfully', 'Completed @count upgrade tasks successfully'));
    }
    // If we had failures, log them and show the migration failed.     if ($failures > 0) {
      \Drupal::messenger()->addError(\Drupal::translation()
        ->formatPlural($failures, '1 upgrade failed', '@count upgrades failed'));
      \Drupal::messenger()->addError(t('Upgrade process not completed'));
    }
    else {
      // Everything went off without a hitch. We may not have had successes       // but we didn't have failures so this is fine.
    $element['media_library_selection']['#value'] = '';

    $field_state = static::getFieldState($element$form_state);

    // Announce the updated content to screen readers.     if ($is_remove_button) {
      $media_item = Media::load($field_state['removed_item_id']);
      $announcement = $media_item->access('view label') ? new TranslatableMarkup('@label has been removed.', ['@label' => $media_item->label()]) : new TranslatableMarkup('Media has been removed.');
    }
    else {
      $new_items = count(static::getNewMediaItems($element$form_state));
      $announcement = \Drupal::translation()->formatPlural($new_items, 'Added one media item.', 'Added @count media items.');
    }

    $response = new AjaxResponse();
    $response->addCommand(new ReplaceCommand("#$wrapper_id", $element));
    $response->addCommand(new AnnounceCommand($announcement));

    // When the remove button is clicked, shift focus to the next remove button.     // When the last item is deleted, we no longer have a selection and shift     // the focus to the open button.     $removed_last = $is_remove_button && !count($field_state['items']);
    if ($is_remove_button && !$removed_last) {
      
'name' => 'foobar',
      'mail' => 'foobar@example.com',
    ]);
    $this->testUser->save();
    \Drupal::service('current_user')->setAccount($this->testUser);
  }

  /** * @covers \Drupal\Core\Action\Plugin\Action\Derivative\EntityDeleteActionDeriver::getDerivativeDefinitions */
  public function testGetDerivativeDefinitions() {
    $deriver = new EntityDeleteActionDeriver(\Drupal::entityTypeManager(), \Drupal::translation());
    $this->assertEquals([
      'entity_test_mulrevpub' => [
        'type' => 'entity_test_mulrevpub',
        'label' => 'Delete test entity - revisions, data table, and published interface',
        'action_label' => 'Delete',
        'confirm_form_route_name' => 'entity.entity_test_mulrevpub.delete_multiple_form',
      ],
      'entity_test_revpub' => [
        'type' => 'entity_test_revpub',
        'label' => 'Delete test entity - revisions and publishing status',
        'action_label' => 'Delete',
        
'name' => 'EspaƱol',
                'localeId' => $esLocale,
                'translationCodeId' => $esLocale,
            ],
        ], Context::createDefaultContext());

        $this->productRepository->create(
            [
                (new ProductBuilder($ids, '1000'))
                    ->price(10)
                    ->name('Test product')
                    ->translation($ids->get('language'), 'name', 'Test produkt')
                    ->build(),
            ],
            Context::createDefaultContext()
        );

        $this->assertKeywords(
            $ids->get('1000'),
            Defaults::LANGUAGE_SYSTEM,
            [
                '1000', // productNumber                 'product', // part of name
->price(50)
                ->releaseDate('2019-01-01 10:11:00')
                ->purchasePrice(0)
                ->stock(2)
                ->category('c1')
                ->category('c2')
                ->property('red', 'color')
                ->property('xl', 'size')
                ->add('weight', 12.3)
                ->add('height', 9.3)
                ->add('width', 1.3)
                ->translation($secondLanguage, 'name', 'Second')
                ->translation($thirdLanguage, 'name', 'Third')
                ->build(),

            (new ProductBuilder($this->ids, 'dal-2'))
                ->name('Default')
                ->category('pants')
                ->customField('testField', 'Silk')
                ->visibility(TestDefaults::SALES_CHANNEL)
                ->tax('t1')
                ->manufacturer('m1')
                ->price(60)
                

                ],
            ],
            Context::createDefaultContext()
        );

        for ($i = 0; $i < 15; ++$i) {
            $products[] = (new ProductBuilder($this->ids, 'product' . $i))
                ->name('Test-Product')
                ->stock(10)
                ->price(15)
                ->translation($this->ids->create('language'), 'name', 'Other translation')
                ->manufacturer('manufacturer-' . $i)
                ->build();
        }

        $data = [
            'id' => $this->ids->create('category'),
            'name' => 'Test',
            'cmsPage' => [
                'id' => $this->ids->create('cms-page'),
                'type' => 'product_list',
                'sections' => [
                    [

    public function slot(string $key, array $value, string $languageId = Defaults::LANGUAGE_SYSTEM): self
    {
        if (isset($this->translations[$languageId]['slotConfig']) && \is_array($this->translations[$languageId]['slotConfig'])) {
            $slotConfig = $this->translations[$languageId]['slotConfig'];
        } else {
            $slotConfig = [];
        }

        $slotConfig[$this->ids->get($key)] = $value;

        $this->translation(
            $languageId,
            'slotConfig',
            $slotConfig
        );

        return $this;
    }
}

    public function slot(string $key, array $value, string $languageId = Defaults::LANGUAGE_SYSTEM): self
    {
        if (isset($this->translations[$languageId]['slotConfig']) && \is_array($this->translations[$languageId]['slotConfig'])) {
            $slotConfig = $this->translations[$languageId]['slotConfig'];
        } else {
            $slotConfig = [];
        }

        $slotConfig[$this->ids->get($key)] = $value;

        $this->translation(
            $languageId,
            'slotConfig',
            $slotConfig
        );

        return $this;
    }

    public function crossSelling(string $key, string $stream, string $sort = '+name'): self
    {
        $crossSelling = [
            

  public function assertFileHookCalled($hook$expected_count = 1, $message = NULL) {
    $actual_count = count(file_test_get_calls($hook));

    if (!isset($message)) {
      if ($actual_count == $expected_count) {
        $message = new FormattableMarkup('hook_file_@name was called correctly.', ['@name' => $hook]);
      }
      elseif ($expected_count == 0) {
        $message = \Drupal::translation()->formatPlural($actual_count, 'hook_file_@name was not expected to be called but was actually called once.', 'hook_file_@name was not expected to be called but was actually called @count times.', ['@name' => $hook, '@count' => $actual_count]);
      }
      else {
        $message = new FormattableMarkup('hook_file_@name was expected to be called %expected times but was called %actual times.', ['@name' => $hook, '%expected' => $expected_count, '%actual' => $actual_count]);
      }
    }
    $this->assertEquals($expected_count$actual_count$message);
  }

  /** * Asserts that two files have the same values (except timestamp). * * @param \Drupal\file\FileInterface $before * File object to compare. * @param \Drupal\file\FileInterface $after * File object to compare. */
$field_storage->delete();
      }
    }
    field_purge_batch($context['sandbox']['field']['purge_batch_size']$field_storage->getUniqueStorageIdentifier());
    $context['sandbox']['field']['current_progress']++;
    $fields_to_delete_count = count(static::getFieldStoragesToPurge($context['sandbox']['field']['extensions']$config_importer->getUnprocessedConfiguration('delete')));
    if ($fields_to_delete_count == 0) {
      $context['finished'] = 1;
    }
    else {
      $context['finished'] = $context['sandbox']['field']['current_progress'] / $context['sandbox']['field']['steps_to_delete'];
      $context['message'] = \Drupal::translation()->translate('Purging field @field_label', ['@field_label' => $field_storage->label()]);
    }
  }

  /** * Initializes the batch context sandbox for processing field deletions. * * This calculates the number of steps necessary to purge all the field data * and saves data for later use. * * @param array $context * The batch context. * @param \Drupal\Core\Config\ConfigImporter $config_importer * The config importer. */

function hook_node_search_result(\Drupal\node\NodeInterface $node) {
  $rating = \Drupal::database()->query('SELECT SUM([points]) FROM {my_rating} WHERE [nid] = :nid', ['nid' => $node->id()])->fetchField();
  return ['rating' => \Drupal::translation()->formatPlural($rating, '1 point', '@count points')];
}

/** * Act on a node being indexed for searching. * * This hook is invoked during search indexing, after loading, and after the * result of rendering is added as $node->rendered to the node object. * * @param \Drupal\node\NodeInterface $node * The node being indexed. * * @return string * Additional node information to be indexed. * * @ingroup entity_crud */

    ];

    foreach ($plural_tests as $langcode => $tests) {
      foreach ($tests as $count => $expected_plural_index) {
        // Assert that the we get the right plural index.         $this->assertSame($expected_plural_indexlocale_get_plural($count$langcode), 'Computed plural index for ' . $langcode . ' for count ' . $count . ' is ' . $expected_plural_index);
        // Assert that the we get the right translation for that. Change the         // expected index as per the logic for translation lookups.         $expected_plural_index = ($count == 1) ? 0 : $expected_plural_index;
        $expected_plural_string = str_replace('@count', $count$plural_strings[$langcode][$expected_plural_index]);
        $this->assertSame($expected_plural_string, \Drupal::translation()->formatPlural($count, '1 hour', '@count hours', []['langcode' => $langcode])->render(), 'Plural translation of 1 hours / @count hours for count ' . $count . ' in ' . $langcode . ' is ' . $expected_plural_string);
        // DO NOT use translation to pass translated strings into         // PluralTranslatableMarkup::createFromTranslatedString() this way. It         // is designed to be used with *already* translated text like settings         // from configuration. We use PHP translation here just because we have         // the expected result data in that format.         $translated_string = \Drupal::translation()->translate('1 hour' . PoItem::DELIMITER . '@count hours', []['langcode' => $langcode]);
        $plural = PluralTranslatableMarkup::createFromTranslatedString($count$translated_string[]['langcode' => $langcode]);
        $this->assertSame($expected_plural_string$plural->render());
      }
    }
  }

  
/** * Finish batch. * * @param bool $success * Indicates whether the batch process was successful. * @param array $results * Results information passed from the processing callback. */
  public static function finishBatch($success$results) {
    \Drupal::messenger()->addMessage(
      \Drupal::translation()->formatPlural($results['processed'], 'One item has been processed.', '@count items have been processed.')
    );
    \Drupal::messenger()->addMessage($results['theme'] . ' theme used');
  }

}

  public function assertFileHookCalled($hook$expected_count = 1, $message = NULL) {
    $actual_count = count(file_test_get_calls($hook));

    if (!isset($message)) {
      if ($actual_count == $expected_count) {
        $message = new FormattableMarkup('hook_file_@name was called correctly.', ['@name' => $hook]);
      }
      elseif ($expected_count == 0) {
        $message = \Drupal::translation()->formatPlural($actual_count, 'hook_file_@name was not expected to be called but was actually called once.', 'hook_file_@name was not expected to be called but was actually called @count times.', ['@name' => $hook, '@count' => $actual_count]);
      }
      else {
        $message = new FormattableMarkup('hook_file_@name was expected to be called %expected times but was called %actual times.', ['@name' => $hook, '%expected' => $expected_count, '%actual' => $actual_count]);
      }
    }
    $this->assertEquals($expected_count$actual_count$message);
  }

  /** * Asserts that two files have the same values (except timestamp). * * @param \Drupal\file\FileInterface $before * File object to compare. * @param \Drupal\file\FileInterface $after * File object to compare. */
$this->setMockContainerService('link_generator');
    $this->assertNotNull(\Drupal::linkGenerator());
  }

  /** * Tests the translation() method. * * @covers ::translation */
  public function testTranslation() {
    $this->setMockContainerService('string_translation');
    $this->assertNotNull(\Drupal::translation());
  }

  /** * Tests the languageManager() method. * * @covers ::languageManager */
  public function testLanguageManager() {
    $this->setMockContainerService('language_manager');
    $this->assertNotNull(\Drupal::languageManager());
  }

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