function ResourceTestBase::getModifiedEntityForPatchTesting

Same name in other branches
  1. 9 core/modules/jsonapi/tests/src/Functional/ResourceTestBase.php \Drupal\Tests\jsonapi\Functional\ResourceTestBase::getModifiedEntityForPatchTesting()
  2. 10 core/modules/jsonapi/tests/src/Functional/ResourceTestBase.php \Drupal\Tests\jsonapi\Functional\ResourceTestBase::getModifiedEntityForPatchTesting()
  3. 11.x core/modules/jsonapi/tests/src/Functional/ResourceTestBase.php \Drupal\Tests\jsonapi\Functional\ResourceTestBase::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 ResourceTestBase::getModifiedEntityForPatchTesting()
ResourceTestBase::testPatchIndividual in core/modules/jsonapi/tests/src/Functional/ResourceTestBase.php
Tests PATCHing an individual resource, plus edge cases to ensure good DX.

File

core/modules/jsonapi/tests/src/Functional/ResourceTestBase.php, line 2492

Class

ResourceTestBase
Subclass this for every JSON:API resource type.

Namespace

Drupal\Tests\jsonapi\Functional

Code

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 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,
    ];
}

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.