You are here

protected function TimestampFormatterTest::testTimestampAgoFormatter in Zircon Profile 8

Same name and namespace in other branches
  1. 8.0 core/modules/field/src/Tests/Timestamp/TimestampFormatterTest.php \Drupal\field\Tests\Timestamp\TimestampFormatterTest::testTimestampAgoFormatter()

Tests TimestampAgoFormatter.

File

core/modules/field/src/Tests/Timestamp/TimestampFormatterTest.php, line 145
Contains \Drupal\field\Tests\Timestamp\TimestampFormatterTest.

Class

TimestampFormatterTest
Tests the timestamp formatters.

Namespace

Drupal\field\Tests\Timestamp

Code

protected function testTimestampAgoFormatter() {
  $data = [];
  foreach (array(
    1,
    2,
    3,
    4,
    5,
    6,
  ) as $granularity) {
    $data[] = [
      'future_format' => '@interval hence',
      'past_format' => '@interval ago',
      'granularity' => $granularity,
    ];
  }
  foreach ($data as $settings) {
    $future_format = $settings['future_format'];
    $past_format = $settings['past_format'];
    $granularity = $settings['granularity'];
    $request_time = \Drupal::requestStack()
      ->getCurrentRequest()->server
      ->get('REQUEST_TIME');

    // Test a timestamp in the past
    $value = $request_time - 87654321;
    $expected = SafeMarkup::format($past_format, [
      '@interval' => \Drupal::service('date.formatter')
        ->formatTimeDiffSince($value, [
        'granularity' => $granularity,
      ]),
    ]);
    $component = $this->display
      ->getComponent($this->fieldName);
    $component['type'] = 'timestamp_ago';
    $component['settings'] = $settings;
    $this->display
      ->setComponent($this->fieldName, $component);
    $entity = EntityTest::create([]);
    $entity->{$this->fieldName}->value = $value;
    $this
      ->renderEntityFields($entity, $this->display);
    $this
      ->assertRaw($expected);

    // Test a timestamp in the future
    $value = $request_time + 87654321;
    $expected = SafeMarkup::format($future_format, [
      '@interval' => \Drupal::service('date.formatter')
        ->formatTimeDiffUntil($value, [
        'granularity' => $granularity,
      ]),
    ]);
    $component = $this->display
      ->getComponent($this->fieldName);
    $component['type'] = 'timestamp_ago';
    $component['settings'] = $settings;
    $this->display
      ->setComponent($this->fieldName, $component);
    $entity = EntityTest::create([]);
    $entity->{$this->fieldName}->value = $value;
    $this
      ->renderEntityFields($entity, $this->display);
    $this
      ->assertRaw($expected);
  }
}