You are here

public function BackendTest::testDateIndexing in Search API 8

Tests whether indexing of dates works correctly.

File

modules/search_api_db/tests/src/Kernel/BackendTest.php, line 1053

Class

BackendTest
Tests index and search capabilities using the Database search backend.

Namespace

Drupal\Tests\search_api_db\Kernel

Code

public function testDateIndexing() {

  // Load all existing entities.
  $storage = \Drupal::entityTypeManager()
    ->getStorage('entity_test_mulrev_changed');
  $storage
    ->delete($storage
    ->loadMultiple());
  $index = Index::load('database_search_index');
  $index
    ->getField('name')
    ->setType('date');
  $index
    ->save();

  // Simulate date field creation in one timezone and indexing in another.
  date_default_timezone_set('America/Chicago');

  // Test different input values, similar to @dataProvider (but with less
  // overhead).
  $t = 1400000000;
  $date_time_format = DateTimeItemInterface::DATETIME_STORAGE_FORMAT;
  $date_format = DateTimeItemInterface::DATE_STORAGE_FORMAT;
  $test_values = [
    'null' => [
      NULL,
      NULL,
    ],
    'timestamp' => [
      $t,
      $t,
    ],
    'string timestamp' => [
      "{$t}",
      $t,
    ],
    'float timestamp' => [
      $t + 0.12,
      $t,
    ],
    'date string' => [
      gmdate($date_time_format, $t),
      $t,
    ],
    'date string with timezone' => [
      date($date_time_format . 'P', $t),
      $t,
    ],
    'date only' => [
      date($date_format, $t),
      // Date-only fields are stored with the default time (12:00:00).
      strtotime(date($date_format, $t) . 'T12:00:00+00:00'),
    ],
  ];

  // Get storage information for quickly checking the indexed value.
  $db_info = $this
    ->getIndexDbInfo();
  $table = $db_info['index_table'];
  $column = $db_info['field_tables']['name']['column'];
  $sql = "SELECT {$column} FROM {{$table}} WHERE item_id = :id";
  $id = 0;
  date_default_timezone_set('Asia/Seoul');
  foreach ($test_values as $label => list($field_value, $expected)) {
    $entity = $this
      ->addTestEntity(++$id, [
      'name' => $field_value,
      'type' => 'item',
    ]);
    $item_id = $this
      ->getItemIds([
      $id,
    ])[0];
    $index
      ->indexSpecificItems([
      $item_id => $entity
        ->getTypedData(),
    ]);
    $args[':id'] = $item_id;
    $indexed_value = \Drupal::database()
      ->query($sql, $args)
      ->fetchField();
    if ($expected === NULL) {
      $this
        ->assertSame($expected, $indexed_value, "Indexing of date field with {$label} value.");
    }
    else {
      $this
        ->assertEquals($expected, $indexed_value, "Indexing of date field with {$label} value.");
    }
  }
}