View source
<?php
namespace Drupal\KernelTests\Core\Entity;
use Drupal\Tests\SchemaCheckTestTrait;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Entity\EntityStorageException;
use Drupal\Core\Field\BaseFieldDefinition;
use Drupal\Core\Field\FieldStorageDefinitionInterface;
use Drupal\field\Entity\FieldConfig;
use Drupal\field\Entity\FieldStorageConfig;
use Drupal\Tests\field\Traits\EntityReferenceTestTrait;
use Drupal\user\Entity\Role;
use Drupal\user\Entity\User;
use Drupal\user\RoleInterface;
use Drupal\user\UserInterface;
use Drupal\entity_test\Entity\EntityTestStringId;
class EntityReferenceFieldTest extends EntityKernelTestBase {
use SchemaCheckTestTrait;
use EntityReferenceTestTrait;
protected $entityType = 'entity_test';
protected $referencedEntityType = 'entity_test_rev';
protected $bundle = 'entity_test';
protected $fieldName = 'field_test';
protected static $modules = [
'entity_reference_test',
'entity_test_update',
];
protected function setUp() : void {
parent::setUp();
$this
->installEntitySchema('entity_test_rev');
$this
->createEntityReferenceField($this->entityType, $this->bundle, $this->fieldName, 'Field test', $this->referencedEntityType, 'default', [
'target_bundles' => [
$this->bundle,
],
], FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED);
}
public function testEntityReferenceFieldValidation() {
$referenced_entity = $this->container
->get('entity_type.manager')
->getStorage($this->referencedEntityType)
->create([
'type' => $this->bundle,
]);
$referenced_entity
->save();
$entity = $this->container
->get('entity_type.manager')
->getStorage($this->entityType)
->create([
'type' => $this->bundle,
]);
$entity->{$this->fieldName}->target_id = $referenced_entity
->id();
$violations = $entity->{$this->fieldName}
->validate();
$this
->assertEquals(0, $violations
->count(), 'Validation passes.');
$entity->{$this->fieldName}->target_id = 9999;
$violations = $entity->{$this->fieldName}
->validate();
$this
->assertEquals(1, $violations
->count(), 'Validation throws a violation.');
$this
->assertEquals(t('The referenced entity (%type: %id) does not exist.', [
'%type' => $this->referencedEntityType,
'%id' => 9999,
]), $violations[0]
->getMessage());
entity_test_create_bundle('non_referenceable', NULL, $this->referencedEntityType);
$referenced_entity = $this->entityTypeManager
->getStorage($this->referencedEntityType)
->create([
'type' => 'non_referenceable',
]);
$referenced_entity
->save();
$entity->{$this->fieldName}->target_id = $referenced_entity
->id();
$violations = $entity->{$this->fieldName}
->validate();
$this
->assertEquals(1, $violations
->count(), 'Validation throws a violation.');
$this
->assertEquals(t('This entity (%type: %id) cannot be referenced.', [
'%type' => $this->referencedEntityType,
'%id' => $referenced_entity
->id(),
]), $violations[0]
->getMessage());
}
public function testReferencedEntitiesMultipleLoad() {
$entity = $this->container
->get('entity_type.manager')
->getStorage($this->entityType)
->create([
'type' => $this->bundle,
]);
$target_entities = [];
$reference_field = [];
for ($i = 0; $i < 3; $i++) {
$target_entity = $this->container
->get('entity_type.manager')
->getStorage($this->referencedEntityType)
->create([
'type' => $this->bundle,
]);
$target_entity
->save();
$target_entities[] = $target_entity;
$reference_field[]['target_id'] = $target_entity
->id();
}
$reference_field[3]['target_id'] = 99999;
$target_entities[3] = NULL;
$reference_field[4]['target_id'] = NULL;
$target_entities[4] = NULL;
$reference_field[5] = $reference_field[0];
$target_entities[5] = $target_entities[0];
$target_entity_unsaved = $this->container
->get('entity_type.manager')
->getStorage($this->referencedEntityType)
->create([
'type' => $this->bundle,
'name' => $this
->randomString(),
]);
$reference_field[6]['entity'] = $target_entity_unsaved;
$target_entities[6] = $target_entity_unsaved;
$entity->{$this->fieldName}
->setValue($reference_field);
$entities = $entity->{$this->fieldName}
->referencedEntities();
foreach ($target_entities as $delta => $target_entity) {
if (!empty($target_entity)) {
if (!$target_entity
->isNew()) {
$this
->assertEquals($entities[$delta]
->id(), $target_entity
->id());
}
else {
$this
->assertEquals($entities[$delta]
->label(), $target_entity
->label());
}
}
else {
$this
->assertFalse(isset($entities[$delta]));
}
}
}
public function testReferencedEntitiesStringId() {
$field_name = 'entity_reference_string_id';
$this
->installEntitySchema('entity_test_string_id');
$this
->createEntityReferenceField($this->entityType, $this->bundle, $field_name, 'Field test', 'entity_test_string_id', 'default', [
'target_bundles' => [
$this->bundle,
],
], FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED);
$entity = $this->container
->get('entity_type.manager')
->getStorage($this->entityType)
->create([
'type' => $this->bundle,
]);
$target_entity = EntityTestStringId::create([
'id' => $this
->randomString(),
'type' => $this->bundle,
]);
$target_entity
->save();
$entity->{$field_name}
->setValue([
[
'target_id' => $target_entity
->id(),
],
]);
$entities = $entity->{$field_name}
->referencedEntities();
$this
->assertEquals($target_entity
->id(), $entities[0]
->id());
$field = FieldConfig::loadByName($this->entityType, $this->bundle, $field_name);
$field
->setDefaultValue($target_entity
->id());
$field
->save();
$this
->assertConfigSchema(\Drupal::service('config.typed'), 'field.field.' . $field
->id(), $field
->toArray());
$entity = $this->container
->get('entity_type.manager')
->getStorage($this->entityType)
->create([
'type' => $this->bundle,
]);
$entities = $entity->{$field_name}
->referencedEntities();
$this
->assertEquals($target_entity
->id(), $entities[0]
->id());
}
public function testAutocreateApi() {
$entity = $this->entityTypeManager
->getStorage($this->entityType)
->create([
'name' => $this
->randomString(),
]);
$this
->assertUserAutocreate($entity, function (EntityInterface $entity, UserInterface $user) {
$entity
->set('user_id', $user);
});
$this
->assertUserAutocreate($entity, function (EntityInterface $entity, UserInterface $user) {
$entity
->set('user_id', $user, FALSE);
});
$this
->assertUserAutocreate($entity, function (EntityInterface $entity, UserInterface $user) {
$entity->user_id
->setValue($user);
});
$this
->assertUserAutocreate($entity, function (EntityInterface $entity, UserInterface $user) {
$entity->user_id[0]
->get('entity')
->setValue($user);
});
$this
->assertUserAutocreate($entity, function (EntityInterface $entity, UserInterface $user) {
$entity->user_id
->setValue([
'entity' => $user,
'target_id' => NULL,
]);
});
try {
$message = 'Setting both the entity and an invalid target_id property fails.';
$this
->assertUserAutocreate($entity, function (EntityInterface $entity, UserInterface $user) {
$user
->save();
$entity->user_id
->setValue([
'entity' => $user,
'target_id' => $this
->generateRandomEntityId(),
]);
});
$this
->fail($message);
} catch (\InvalidArgumentException $e) {
}
$this
->assertUserAutocreate($entity, function (EntityInterface $entity, UserInterface $user) {
$entity->user_id = $user;
});
$this
->assertUserAutocreate($entity, function (EntityInterface $entity, UserInterface $user) {
$entity->user_id->entity = $user;
});
$this
->assertUserRoleAutocreate($entity, function (EntityInterface $entity, RoleInterface $role) {
$entity
->set('user_role', $role);
});
$this
->assertUserRoleAutocreate($entity, function (EntityInterface $entity, RoleInterface $role) {
$entity
->set('user_role', $role, FALSE);
});
$this
->assertUserRoleAutocreate($entity, function (EntityInterface $entity, RoleInterface $role) {
$entity->user_role
->setValue($role);
});
$this
->assertUserRoleAutocreate($entity, function (EntityInterface $entity, RoleInterface $role) {
$entity->user_role[0]
->get('entity')
->setValue($role);
});
$this
->assertUserRoleAutocreate($entity, function (EntityInterface $entity, RoleInterface $role) {
$entity->user_role
->setValue([
'entity' => $role,
'target_id' => NULL,
]);
});
try {
$message = 'Setting both the entity and an invalid target_id property fails.';
$this
->assertUserRoleAutocreate($entity, function (EntityInterface $entity, RoleInterface $role) {
$role
->save();
$entity->user_role
->setValue([
'entity' => $role,
'target_id' => $this
->generateRandomEntityId(TRUE),
]);
});
$this
->fail($message);
} catch (\InvalidArgumentException $e) {
}
$this
->assertUserRoleAutocreate($entity, function (EntityInterface $entity, RoleInterface $role) {
$entity->user_role = $role;
});
$this
->assertUserRoleAutocreate($entity, function (EntityInterface $entity, RoleInterface $role) {
$entity->user_role->entity = $role;
});
$storage = $this->entityTypeManager
->getStorage('user');
$user_id = $this
->generateRandomEntityId();
$user = $storage
->create([
'uid' => $user_id,
'name' => $this
->randomString(),
]);
$entity->user_id = $user;
$user
->save();
$entity
->save();
$this
->assertEquals($user
->id(), $entity->user_id->target_id);
}
protected function assertUserAutocreate(EntityInterface $entity, $setter_callback) {
$storage = $this->entityTypeManager
->getStorage('user');
$user_id = $this
->generateRandomEntityId();
$user = $storage
->create([
'uid' => $user_id,
'name' => $this
->randomString(),
]);
$setter_callback($entity, $user);
$entity
->save();
$storage
->resetCache();
$user = User::load($user_id);
$this
->assertEquals($entity->user_id->target_id, $user
->id());
}
protected function assertUserRoleAutocreate(EntityInterface $entity, $setter_callback) {
$storage = $this->entityTypeManager
->getStorage('user_role');
$role_id = $this
->generateRandomEntityId(TRUE);
$role = $storage
->create([
'id' => $role_id,
'label' => $this
->randomString(),
]);
$setter_callback($entity, $role);
$entity
->save();
$storage
->resetCache();
$role = Role::load($role_id);
$this
->assertEquals($entity->user_role->target_id, $role
->id());
}
public function testTargetEntityNoLoad() {
$entity_type = clone $this->entityTypeManager
->getDefinition('entity_test_update');
$entity_type
->setHandlerClass('storage', '\\Drupal\\entity_test\\EntityTestNoLoadStorage');
$this->state
->set('entity_test_update.entity_type', $entity_type);
$definitions = [
'target_reference' => BaseFieldDefinition::create('entity_reference')
->setSetting('target_type', $entity_type
->id())
->setSetting('handler', 'default'),
];
$this->state
->set('entity_test_update.additional_base_field_definitions', $definitions);
$this->entityTypeManager
->clearCachedDefinitions();
$this
->installEntitySchema($entity_type
->id());
$storage = $this->entityTypeManager
->getStorage($entity_type
->id());
$target_id = $this
->generateRandomEntityId();
$target = $storage
->create([
'id' => $target_id,
'name' => $this
->randomString(),
]);
$target
->save();
$this
->assertEquals($target_id, $target
->id(), 'The target entity has a random identifier.');
$message = 'The target entity was not loaded.';
try {
$entity = $this->entityTypeManager
->getStorage($entity_type
->id())
->create([
'name' => $this
->randomString(),
]);
$entity->target_reference = $target_id;
} catch (EntityStorageException $e) {
$this
->fail($message);
}
$message = 'An exception is thrown when trying to load the target entity';
try {
$storage
->load($target_id);
$this
->fail($message);
} catch (EntityStorageException $e) {
}
}
public function testEntityReferenceFieldDependencies() {
$field_name = 'user_reference_field';
$entity_type = 'entity_test';
$field_storage = FieldStorageConfig::create([
'field_name' => $field_name,
'type' => 'entity_reference',
'entity_type' => $entity_type,
'settings' => [
'target_type' => 'user',
],
]);
$field_storage
->save();
$this
->assertEquals([
'module' => [
'entity_test',
'user',
],
], $field_storage
->getDependencies());
$field = FieldConfig::create([
'field_name' => $field_name,
'entity_type' => $entity_type,
'bundle' => 'entity_test',
'label' => $field_name,
'settings' => [
'handler' => 'default',
],
]);
$field
->save();
$this
->assertEquals([
'config' => [
'field.storage.entity_test.user_reference_field',
],
'module' => [
'entity_test',
],
], $field
->getDependencies());
}
}