You are here

public function OfficeHoursItemTest::testOfficeHoursField in Office Hours 8

Tests the Office Hours field can be added to an entity type.

File

tests/src/Kernel/OfficeHoursItemTest.php, line 111

Class

OfficeHoursItemTest
Class that tests OfficeHoursField.

Namespace

Drupal\Tests\office_hours\Kernel

Code

public function testOfficeHoursField() {
  $this->fieldStorage
    ->setSetting('element_type', 'office_hours_datelist');
  $this->fieldStorage
    ->save();

  // Verify entity creation.

  /** @var \Drupal\entity_test\Entity\EntityTest $entity */
  $entity = EntityTest::create();
  $field_name = 'field_office_hours';
  $value = [
    [
      'day' => '2',
      'starthours' => '1330',
      'endhours' => '2000',
      'comment' => '',
    ],
    [
      'day' => '3',
      'starthours' => '900',
      'endhours' => '2000',
      'comment' => '',
    ],
  ];
  $entity
    ->set($field_name, $value);
  $entity
    ->setName($this
    ->randomMachineName());
  $this
    ->entityValidateAndSave($entity);

  // Verify entity has been created properly.
  $id = $entity
    ->id();
  $entity = EntityTest::load($id);
  $this
    ->assertInstanceOf(FieldItemListInterface::class, $entity
    ->get($field_name));
  $this
    ->assertInstanceOf(FieldItemInterface::class, $entity
    ->get($field_name)
    ->first());

  // Verify changing the field value.
  $new_value = [
    [
      'day' => '2',
      'starthours' => '1430',
      'endhours' => '2000',
      'comment' => '',
    ],
    [
      'day' => '3',
      'starthours' => '1900',
      'endhours' => '2000',
      'comment' => '',
    ],
  ];

  // $entity->$field_name->value = $new_value;
  $entity->{$field_name}
    ->setValue($new_value);
  $test_value = $entity->{$field_name}
    ->first()
    ->getValue();

  // Read changed entity and assert changed values.
  $this
    ->entityValidateAndSave($entity);
  $entity = EntityTest::load($id);
  $test_value = $entity->{$field_name}
    ->first()
    ->getValue();
  $this
    ->assertEquals(implode('/', $new_value[0]), implode('/', $test_value));

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