EmailItemTest.php 2.33 KB
Newer Older
1 2
<?php

3
namespace Drupal\Tests\field\Kernel\Email;
4

5 6
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Field\FieldItemInterface;
7
use Drupal\entity_test\Entity\EntityTest;
8
use Drupal\field\Entity\FieldConfig;
9
use Drupal\Tests\field\Kernel\FieldKernelTestBase;
10
use Drupal\field\Entity\FieldStorageConfig;
11 12 13

/**
 * Tests the new entity API for the email field type.
14 15
 *
 * @group field
16
 */
17
class EmailItemTest extends FieldKernelTestBase {
18

19
  protected function setUp(): void {
20 21
    parent::setUp();

22
    // Create an email field storage and field for validation.
23
    FieldStorageConfig::create([
24
      'field_name' => 'field_email',
25
      'entity_type' => 'entity_test',
26
      'type' => 'email',
27
    ])->save();
28
    FieldConfig::create([
29 30 31
      'entity_type' => 'entity_test',
      'field_name' => 'field_email',
      'bundle' => 'entity_test',
32
    ])->save();
33 34

    // Create a form display for the default form mode.
35 36
    \Drupal::service('entity_display.repository')
      ->getFormDisplay('entity_test', 'entity_test')
37
      ->setComponent('field_email', [
38
        'type' => 'email_default',
39
      ])
40
      ->save();
41 42 43 44 45 46 47
  }

  /**
   * Tests using entity fields of the email field type.
   */
  public function testEmailItem() {
    // Verify entity creation.
48
    $entity = EntityTest::create();
49 50
    $value = 'test@example.com';
    $entity->field_email = $value;
51
    $entity->name->value = $this->randomMachineName();
52 53 54 55
    $entity->save();

    // Verify entity has been created properly.
    $id = $entity->id();
56
    $entity = EntityTest::load($id);
57 58
    $this->assertInstanceOf(FieldItemListInterface::class, $entity->field_email);
    $this->assertInstanceOf(FieldItemInterface::class, $entity->field_email[0]);
59 60 61 62
    $this->assertEqual($entity->field_email->value, $value);
    $this->assertEqual($entity->field_email[0]->value, $value);

    // Verify changing the email value.
63
    $new_value = $this->randomMachineName();
64 65 66 67 68
    $entity->field_email->value = $new_value;
    $this->assertEqual($entity->field_email->value, $new_value);

    // Read changed entity and assert changed values.
    $entity->save();
69
    $entity = EntityTest::load($id);
70
    $this->assertEqual($entity->field_email->value, $new_value);
71 72

    // Test sample item generation.
73
    $entity = EntityTest::create();
74 75
    $entity->field_email->generateSampleItems();
    $this->entityValidateAndSave($entity);
76 77 78
  }

}