You are here

public function DateTimeItemTest::testDateTime in Drupal 9

Same name and namespace in other branches
  1. 8 core/modules/datetime/tests/src/Kernel/DateTimeItemTest.php \Drupal\Tests\datetime\Kernel\DateTimeItemTest::testDateTime()
  2. 10 core/modules/datetime/tests/src/Kernel/DateTimeItemTest.php \Drupal\Tests\datetime\Kernel\DateTimeItemTest::testDateTime()

Tests using entity fields of the datetime field type.

File

core/modules/datetime/tests/src/Kernel/DateTimeItemTest.php, line 67

Class

DateTimeItemTest
Tests the new entity API for the date field type.

Namespace

Drupal\Tests\datetime\Kernel

Code

public function testDateTime() {
  $this->fieldStorage
    ->setSetting('datetime_type', DateTimeItem::DATETIME_TYPE_DATETIME);
  $this->fieldStorage
    ->save();

  // Verify entity creation.
  $entity = EntityTest::create();
  $value = '2014-01-01T20:00:00';
  $entity->field_datetime = $value;
  $entity->name->value = $this
    ->randomMachineName();
  $this
    ->entityValidateAndSave($entity);

  // Verify entity has been created properly.
  $id = $entity
    ->id();
  $entity = EntityTest::load($id);
  $this
    ->assertInstanceOf(FieldItemListInterface::class, $entity->field_datetime);
  $this
    ->assertInstanceOf(FieldItemInterface::class, $entity->field_datetime[0]);
  $this
    ->assertEquals($value, $entity->field_datetime->value);
  $this
    ->assertEquals($value, $entity->field_datetime[0]->value);
  $this
    ->assertEquals(DateTimeItemInterface::STORAGE_TIMEZONE, $entity->field_datetime[0]
    ->getProperties()['value']
    ->getDateTime()
    ->getTimeZone()
    ->getName());
  $this
    ->assertEquals(DateTimeItemInterface::STORAGE_TIMEZONE, $entity->field_datetime->date
    ->getTimeZone()
    ->getName());

  // Verify changing the date value.
  $new_value = '2016-11-04T00:21:00';
  $entity->field_datetime->value = $new_value;
  $this
    ->assertEquals($new_value, $entity->field_datetime->value);
  $this
    ->assertEquals(DateTimeItemInterface::STORAGE_TIMEZONE, $entity->field_datetime[0]
    ->getProperties()['value']
    ->getDateTime()
    ->getTimeZone()
    ->getName());
  $this
    ->assertEquals(DateTimeItemInterface::STORAGE_TIMEZONE, $entity->field_datetime->date
    ->getTimeZone()
    ->getName());

  // Read changed entity and assert changed values.
  $this
    ->entityValidateAndSave($entity);
  $entity = EntityTest::load($id);
  $this
    ->assertEquals($new_value, $entity->field_datetime->value);
  $this
    ->assertEquals(DateTimeItemInterface::STORAGE_TIMEZONE, $entity->field_datetime[0]
    ->getProperties()['value']
    ->getDateTime()
    ->getTimeZone()
    ->getName());
  $this
    ->assertEquals(DateTimeItemInterface::STORAGE_TIMEZONE, $entity->field_datetime->date
    ->getTimeZone()
    ->getName());

  // Test the generateSampleValue() method.
  $entity = EntityTest::create();
  $entity->field_datetime
    ->generateSampleItems();
  $this
    ->entityValidateAndSave($entity);
}