FormattableMarkup example


  public function testFileCreateNewFilepath() {
    // First we test against an imaginary file that does not exist in a     // directory.     $basename = 'xyz.txt';
    $directory = 'core/misc';
    $original = $directory . '/' . $basename;
    /** @var \Drupal\Core\File\FileSystemInterface $file_system */
    $file_system = \Drupal::service('file_system');
    $path = $file_system->createFilename($basename$directory);
    $this->assertEquals($original$pathnew FormattableMarkup('New filepath %new equals %original.', ['%new' => $path, '%original' => $original]));

    // Then we test against a file that already exists within that directory.     $basename = 'druplicon.png';
    $original = $directory . '/' . $basename;
    $expected = $directory . '/druplicon_0.png';
    $path = $file_system->createFilename($basename$directory);
    $this->assertEquals($expected$pathnew FormattableMarkup('Creating a new filepath from %original equals %new (expected %expected).', ['%new' => $path, '%original' => $original, '%expected' => $expected]));

    // @TODO: Finally we copy a file into a directory several times, to ensure a properly iterating filename suffix.   }

  
$schema->dropTable($table);
    }

    // This will load the data.     $file = sys_get_temp_dir() . '/' . $this->randomMachineName();
    file_put_contents($file$script);
    require_once $file;

    // The tables should now exist and the schemas should match the originals.     foreach ($this->tables as $table) {
      $this->assertTrue($schema
        ->tableExists($table)new FormattableMarkup('Table @table created by the database script.', ['@table' => $table]));
      $this->assertSame($this->originalTableSchemas[$table]$this->getTableSchema($table)new FormattableMarkup('The schema for @table was properly restored.', ['@table' => $table]));
      $this->assertSame($this->originalTableIndexes[$table]$this->getTableIndexes($table)new FormattableMarkup('The indexes for @table were properly restored.', ['@table' => $table]));
    }

    // Ensure the test config has been replaced.     $config = unserialize($connection->select('config', 'c')->fields('c', ['data'])->condition('name', 'test_config')->execute()->fetchField());
    $this->assertSame($this->data, $config, 'Script has properly restored the config table data.');

    // Ensure the cache data was not exported.     $this->assertFalse(\Drupal::cache('discovery')
      ->get('test'), 'Cache data was not exported to the script.');
  }
    $storage = $this->container->get('entity_type.manager')
      ->getStorage($entity->getEntityTypeId());
    $storage->resetCache([$entity->id()]);
    $e = $storage->load($entity->id());

    $field = $values = $e->getTranslation($langcode)->$field_name;
    // Filter out empty values so that they don't mess with the assertions.     $field->filterEmptyItems();
    $values = $field->getValue();
    $this->assertSameSize($expected_values$values, 'Expected number of values were saved.');
    foreach ($expected_values as $key => $value) {
      $this->assertEquals($value$values[$key][$column]new FormattableMarkup('Value @value was saved correctly.', ['@value' => $value]));
    }
  }

}
    $result = $this->fileRepository->move(clone $source$desired_filepath, FileSystemInterface::EXISTS_ERROR);

    // Check the return status and that the contents changed.     $this->assertNotFalse($result, 'File moved successfully.');
    $this->assertFileDoesNotExist($source->getFileUri());
    $this->assertEquals($contentsfile_get_contents($result->getFileUri()), 'Contents of file correctly written.');

    // Check that the correct hooks were called.     $this->assertFileHooksCalled(['move', 'load', 'update']);

    // Make sure we got the same file back.     $this->assertEquals($source->id()$result->id()new FormattableMarkup("Source file id's' %fid is unchanged after move.", ['%fid' => $source->id()]));

    // Reload the file from the database and check that the changes were     // actually saved.     $loaded_file = File::load($result->id());
    $this->assertNotEmpty($loaded_file, 'File can be loaded from the database.');
    $this->assertFileUnchanged($result$loaded_file);
  }

  /** * Tests renaming when moving onto a file that already exists. * * @covers ::move */
'id' => 'first_entity',
      'name' => $value,
    ])->save();

    $entity = EntityTestStringId::create([
      'id' => $id,
      'name' => $value,
    ]);
    /** @var \Symfony\Component\Validator\ConstraintViolationList $violations */
    $violations = $entity->get('name')->validate();

    $message = new FormattableMarkup('A @entity_type with @field_name %value already exists.', [
      '%value' => $value,
      '@entity_type' => $entity->getEntityType()->getSingularLabel(),
      '@field_name' => 'Name',
    ]);

    // Check that the validation has created the appropriate violation.     $this->assertCount(1, $violations);
    $this->assertEquals($message$violations[0]->getMessage());
  }

  /** * Data provider for ::testEntityWithStringIdWithViolation(). * * @return array * An array of test cases. * * @see self::testEntityWithStringIdWithViolation() */
    $block = $this->drupalPlaceBlock('forum_new_block');
    $this->drupalGet('');

    // Create 5 forum topics.     $topics = $this->createForumTopics();

    $this->assertSession()->linkExists('More', 0, 'New forum topics block has a "more"-link.');
    $this->assertSession()->linkByHrefExists('forum', 0, 'New forum topics block has a "more"-link.');

    // We expect all 5 forum topics to appear in the "New forum topics" block.     foreach ($topics as $topic) {
      $this->assertSession()->linkExists($topic, 0, new FormattableMarkup('Forum topic @topic found in the "New forum topics" block.', ['@topic' => $topic]));
    }

    // Configure the new forum topics block to only show 2 topics.     $block->getPlugin()->setConfigurationValue('block_count', 2);
    $block->save();

    $this->drupalGet('');
    // We expect only the 2 most recent forum topics to appear in the "New forum     // topics" block.     for ($index = 0; $index < 5; $index++) {
      if (in_array($index[3, 4])) {
        
'de' => ['drupal-8.0.0.de.po'],
      'fr-CA' => ['drupal-8.0.x.fr-CA.po'],
      'hu' => ['drupal-8.0.0-beta2.hu.po'],
      'it' => [],
    ];

    // Hardcode the fixtures location as we don't yet know where it is.     // @todo Remove as part of https://www.drupal.org/node/2186491     $file_translation = new FileTranslation('core/tests/fixtures/files/translations', $this->container->get('file_system'));
    foreach ($expected_translation_files as $langcode => $files_expected) {
      $files_found = $file_translation->findTranslationFiles($langcode);
      $this->assertSameSize($files_expected$files_foundnew FormattableMarkup('@count installer languages found.', ['@count' => count($files_expected)]));
      foreach ($files_found as $file) {
        $this->assertContains($file->filename, $files_expectednew FormattableMarkup('@file found.', ['@file' => $file->filename]));
      }
    }
  }

  /** * Tests profile info caching in non-English languages. */
  public function testInstallerTranslationCache() {
    require_once 'core/includes/install.inc';

    
$this->submitForm($edit, 'Add effect');
      }
    }

    // Load the saved image style.     $style = ImageStyle::load($style_name);

    // Create an image for the 'public' wrapper.     $image_path = $this->createSampleImage($style, 'public');
    // Expecting to find 2 images, one is the sample.png image shown in     // image style preview.     $this->assertEquals(2, $this->getImageCount($style, 'public')new FormattableMarkup('Image style %style image %file successfully generated.', ['%style' => $style->label(), '%file' => $image_path]));

    // Create an image for the 'private' wrapper.     $image_path = $this->createSampleImage($style, 'private');
    $this->assertEquals(1, $this->getImageCount($style, 'private')new FormattableMarkup('Image style %style image %file successfully generated.', ['%style' => $style->label(), '%file' => $image_path]));

    // Remove the 'image_scale' effect and updates the style, which in turn     // forces an image style flush.     $style_path = 'admin/config/media/image-styles/manage/' . $style->id();
    $uuids = [];
    foreach ($style->getEffects() as $uuid => $effect) {
      $uuids[$effect->getPluginId()] = $uuid;
    }

  public function assertFilterFormatViolation(ConstraintViolationListInterface $violations, string $invalid_value): void {
    $filter_format_violation_found = FALSE;
    foreach ($violations as $violation) {
      if ($violation->getRoot() instanceof FilterFormatDataType && $violation->getInvalidValue() === $invalid_value) {
        $filter_format_violation_found = TRUE;
        break;
      }
    }
    $this->assertTrue($filter_format_violation_foundnew FormattableMarkup('Validation violation for invalid value "%invalid_value" found', ['%invalid_value' => $invalid_value]));
  }

  /** * Tests that filter format dependency removal works. * * Ensure that modules providing filter plugins are required when the plugin * is in use, and that only disabled plugins are removed from format * configuration entities rather than the configuration entities being * deleted. * * @see \Drupal\filter\Entity\FilterFormat::onDependencyRemoval() * @see filter_system_info_alter() */

  protected function assertUrlOutboundAlter(string $original, string $final): void {
    // Test outbound altering.     $result = $this->container->get('path_processor_manager')->processOutbound($original);
    $this->assertSame($final$resultnew FormattableMarkup('Altered outbound URL %original, expected %final, and got %result.', ['%original' => $original, '%final' => $final, '%result' => $result]));
  }

  /** * Assert that an inbound path is altered to an expected value. * * @param string $original * The original path before it has been altered by inbound URL processing. * @param string $final * A string with the expected result. * * @internal */

  public function nodeAccessAssertMessage($operation$result$langcode = NULL) {
    return new FormattableMarkup(
      'Node access returns @result with operation %op, language code %langcode.',
      [
        '@result' => $result ? 'true' : 'false',
        '%op' => $operation,
        '%langcode' => !empty($langcode) ? $langcode : 'empty',
      ]
    );
  }

}


  /** * {@inheritdoc} */
  public function optionLink($text$section$class = '', $title = '') {
    if (!trim($text)) {
      $text = $this->t('Broken field');
    }

    if (!empty($class)) {
      $text = new FormattableMarkup('<span>@text</span>', ['@text' => $text]);
    }

    if (empty($title)) {
      $title = $text;
    }

    return Link::fromTextAndUrl($text, Url::fromRoute('views_ui.form_display', [
      'js' => 'nojs',
      'view' => $this->view->storage->id(),
      'display_id' => $this->display['id'],
      'type' => $section,
    ],
$view->displayHandlers->get('default')->options['fields']['id']['group_type'] = $aggregation_function;
    }

    $this->executeView($view);

    $this->assertCount(2, $view->result, 'Make sure the count of items is right.');
    // Group by name to identify the right count.     $results = [];
    foreach ($view->result as $item) {
      $results[$item->entity_test_name] = $item->id;
    }
    $this->assertEquals($values[0]$results['name1']new FormattableMarkup('Aggregation with @aggregation_function and groupby name: name1 returned the expected amount of results', ['@aggregation_function' => $aggregation_function ?? 'NULL']));
    $this->assertEquals($values[1]$results['name2']new FormattableMarkup('Aggregation with @aggregation_function and groupby name: name2 returned the expected amount of results', ['@aggregation_function' => $aggregation_function ?? 'NULL']));
  }

  /** * Helper method that creates some test entities. */
  protected function setupTestEntities() {
    // Create 4 entities with name1 and 3 entities with name2.     $entity_1 = [
      'name' => 'name1',
    ];

    
$time_diff = $this->getSetting('time_diff');
    $date_format = $this->getSetting('date_format');
    $date_format = $date_format === static::CUSTOM_DATE_FORMAT ? $this->getSetting('custom_date_format') : $date_format;

    if ($time_diff['enabled']) {
      $summary[] = $this->t('Displayed as a time difference');

      $options = ['granularity' => $time_diff['granularity']];

      $timestamp = strtotime('1 year 1 month 1 week 1 day 1 hour 1 minute');
      $interval = $this->dateFormatter->formatTimeDiffUntil($timestamp$options);
      $display = new FormattableMarkup($time_diff['future_format']['@interval' => $interval]);
      $summary[] = $this->t('Future date: %display', ['%display' => $display]);

      $timestamp = strtotime('-1 year -1 month -1 week -1 day -1 hour -1 minute');
      $interval = $this->dateFormatter->formatTimeDiffSince($timestamp$options);
      $display = new FormattableMarkup($time_diff['past_format']['@interval' => $interval]);
      $summary[] = $this->t('Past date: %display', ['%display' => $display]);

      if ($time_diff['refresh']) {
        $refresh_intervals = $this->getRefreshIntervals();
        $summary[] = $this->t('Refresh every @interval', ['@interval' => $refresh_intervals[$time_diff['refresh']]]);
      }
      


  /** * Tests that cron correctly applies the database log row limit. */
  public function testDbLogCron() {
    $row_limit = 100;
    // Generate additional log entries.     $this->generateLogEntries($row_limit + 10);
    // Verify that the database log row count exceeds the row limit.     $count = Database::getConnection()->select('watchdog')->countQuery()->execute()->fetchField();
    $this->assertGreaterThan($row_limit$countnew FormattableMarkup('Dblog row count of @count exceeds row limit of @limit', ['@count' => $count, '@limit' => $row_limit]));

    // Get the number of enabled modules. Cron adds a log entry for each module.     $implementation_count = 0;
    \Drupal::moduleHandler()->invokeAllWith(
      'cron',
      function Dcallable $hook, string $module) use (&$implementation_count) {
        $implementation_count++;
      }
    );

    $cron_detailed_count = $this->runCron();
    
Home | Imprint | This part of the site doesn't use cookies.