You are here

protected static function ResourceTestBase::getModifiedEntityForPatchTesting in JSON:API 8

Same name and namespace in other branches
  1. 8.2 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 tests/src/Functional/ResourceTestBase.php
Tests PATCHing an individual resource, plus edge cases to ensure good DX.

File

tests/src/Functional/ResourceTestBase.php, line 2445

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