protected static function EntityResourceTestBase::getModifiedEntityForPatchTesting in Drupal 8
Same name and namespace in other branches
- 9 core/modules/rest/tests/src/Functional/EntityResource/EntityResourceTestBase.php \Drupal\Tests\rest\Functional\EntityResource\EntityResourceTestBase::getModifiedEntityForPatchTesting()
- 10 core/modules/rest/tests/src/Functional/EntityResource/EntityResourceTestBase.php \Drupal\Tests\rest\Functional\EntityResource\EntityResourceTestBase::getModifiedEntityForPatchTesting()
Clones the given entity and modifies all PATCH-protected fields.
@internal
Parameters
\Drupal\Core\Entity\EntityInterface $entity: The entity being tested and to modify.
Return value
array Contains two items: 1. The modified entity object. 2. The original field values, keyed by field name.
1 call to EntityResourceTestBase::getModifiedEntityForPatchTesting()
- EntityResourceTestBase::testPatch in core/
modules/ rest/ tests/ src/ Functional/ EntityResource/ EntityResourceTestBase.php - Tests a PATCH request for an entity, plus edge cases to ensure good DX.
File
- core/
modules/ rest/ tests/ src/ Functional/ EntityResource/ EntityResourceTestBase.php, line 1457
Class
- EntityResourceTestBase
- Even though there is the generic EntityResource, it's necessary for every entity type to have its own test, because they each have different fields, validation constraints, et cetera. It's not because the generic case works, that every case…
Namespace
Drupal\Tests\rest\Functional\EntityResourceCode
protected static function getModifiedEntityForPatchTesting(EntityInterface $entity) {
$modified_entity = clone $entity;
$original_values = [];
foreach (array_keys(static::$patchProtectedFieldNames) as $field_name) {
$field = $modified_entity
->get($field_name);
$original_values[$field_name] = $field
->getValue();
switch ($field
->getItemDefinition()
->getClass()) {
case EntityReferenceItem::class:
// EntityReferenceItem::generateSampleValue() picks one of the last 50
// entities of the supported type & bundle. We don't care if the value
// is valid, we only care that it's different.
$field
->setValue([
'target_id' => 99999,
]);
break;
case BooleanItem::class:
// BooleanItem::generateSampleValue() picks either 0 or 1. So a 50%
// chance of not picking a different value.
$field->value = (int) $field->value === 1 ? '0' : '1';
break;
case PathItem::class:
// PathItem::generateSampleValue() doesn't set a PID, which causes
// PathItem::postSave() to fail. Keep the PID (and other properties),
// just modify the alias.
$field->alias = str_replace(' ', '-', strtolower((new Random())
->sentences(3)));
break;
default:
$original_field = clone $field;
while ($field
->equals($original_field)) {
$field
->generateSampleItems();
}
break;
}
}
return [
$modified_entity,
$original_values,
];
}