ContentEntityStorageBase.php 24.3 KB
Newer Older
1 2 3 4
<?php

namespace Drupal\Core\Entity;

5 6
use Drupal\Core\Cache\Cache;
use Drupal\Core\Cache\CacheBackendInterface;
7 8
use Drupal\Core\Field\FieldDefinitionInterface;
use Drupal\Core\Field\FieldStorageDefinitionInterface;
9
use Symfony\Component\DependencyInjection\ContainerInterface;
10

11 12 13 14
/**
 * Base class for content entity storage handlers.
 */
abstract class ContentEntityStorageBase extends EntityStorageBase implements ContentEntityStorageInterface, DynamicallyFieldableEntityStorageInterface {
15

16 17 18 19 20 21 22
  /**
   * The entity bundle key.
   *
   * @var string|bool
   */
  protected $bundleKey = FALSE;

23 24 25 26 27 28 29 30 31 32 33 34 35 36
  /**
   * The entity manager.
   *
   * @var \Drupal\Core\Entity\EntityManagerInterface
   */
  protected $entityManager;

  /**
   * Cache backend.
   *
   * @var \Drupal\Core\Cache\CacheBackendInterface
   */
  protected $cacheBackend;

37
  /**
38
   * Constructs a ContentEntityStorageBase object.
39
   *
40 41
   * @param \Drupal\Core\Entity\EntityTypeInterface $entity_type
   *   The entity type definition.
42 43 44 45
   * @param \Drupal\Core\Entity\EntityManagerInterface $entity_manager
   *   The entity manager.
   * @param \Drupal\Core\Cache\CacheBackendInterface $cache
   *   The cache backend to be used.
46
   */
47
  public function __construct(EntityTypeInterface $entity_type, EntityManagerInterface $entity_manager, CacheBackendInterface $cache) {
48
    parent::__construct($entity_type);
49
    $this->bundleKey = $this->entityType->getKey('bundle');
50 51
    $this->entityManager = $entity_manager;
    $this->cacheBackend = $cache;
52 53 54 55 56
  }

  /**
   * {@inheritdoc}
   */
57
  public static function createInstance(ContainerInterface $container, EntityTypeInterface $entity_type) {
58
    return new static(
59 60 61
      $entity_type,
      $container->get('entity.manager'),
      $container->get('cache.entity')
62 63 64
    );
  }

65 66 67 68 69 70 71 72 73 74
  /**
   * {@inheritdoc}
   */
  public function hasData() {
    return (bool) $this->getQuery()
      ->accessCheck(FALSE)
      ->range(0, 1)
      ->execute();
  }

75 76 77
  /**
   * {@inheritdoc}
   */
78
  protected function doCreate(array $values) {
79 80 81 82
    // We have to determine the bundle first.
    $bundle = FALSE;
    if ($this->bundleKey) {
      if (!isset($values[$this->bundleKey])) {
83
        throw new EntityStorageException('Missing bundle for entity type ' . $this->entityTypeId);
84 85 86
      }
      $bundle = $values[$this->bundleKey];
    }
87
    $entity = new $this->entityClass(array(), $this->entityTypeId, $bundle);
88 89 90
    $this->initFieldValues($entity, $values);
    return $entity;
  }
91

92 93 94 95 96 97 98 99 100 101 102 103 104 105
  /**
   * Initializes field values.
   *
   * @param \Drupal\Core\Entity\ContentEntityInterface $entity
   *   An entity object.
   * @param array $values
   *   (optional) An associative array of initial field values keyed by field
   *   name. If none is provided default values will be applied.
   * @param array $field_names
   *   (optional) An associative array of field names to be initialized. If none
   *   is provided all fields will be initialized.
   */
  protected function initFieldValues(ContentEntityInterface $entity, array $values = [], array $field_names = []) {
    // Populate field values.
106
    foreach ($entity as $name => $field) {
107 108 109 110 111 112 113
      if (!$field_names || isset($field_names[$name])) {
        if (isset($values[$name])) {
          $entity->$name = $values[$name];
        }
        elseif (!array_key_exists($name, $values)) {
          $entity->get($name)->applyDefaultValue();
        }
114 115 116 117 118 119 120 121
      }
      unset($values[$name]);
    }

    // Set any passed values for non-defined fields also.
    foreach ($values as $name => $value) {
      $entity->$name = $value;
    }
122 123 124 125 126 127 128 129 130 131 132 133 134 135 136

    // Make sure modules can alter field initial values.
    $this->invokeHook('field_values_init', $entity);
  }

  /**
   * {@inheritdoc}
   */
  public function createTranslation(ContentEntityInterface $entity, $langcode, array $values = []) {
    $translation = $entity->getTranslation($langcode);
    $definitions = array_filter($translation->getFieldDefinitions(), function(FieldDefinitionInterface $definition) { return $definition->isTranslatable(); });
    $field_names = array_map(function(FieldDefinitionInterface $definition) { return $definition->getName(); }, $definitions);
    $values[$this->langcodeKey] = $langcode;
    $values[$this->getEntityType()->getKey('default_langcode')] = FALSE;
    $this->initFieldValues($translation, $values, $field_names);
137
    $this->invokeHook('translation_create', $translation);
138
    return $translation;
139 140
  }

141 142 143
  /**
   * {@inheritdoc}
   */
144
  public function onFieldStorageDefinitionCreate(FieldStorageDefinitionInterface $storage_definition) { }
145 146 147 148

  /**
   * {@inheritdoc}
   */
149
  public function onFieldStorageDefinitionUpdate(FieldStorageDefinitionInterface $storage_definition, FieldStorageDefinitionInterface $original) { }
150 151 152 153

  /**
   * {@inheritdoc}
   */
154
  public function onFieldStorageDefinitionDelete(FieldStorageDefinitionInterface $storage_definition) { }
155 156 157 158

  /**
   * {@inheritdoc}
   */
159
  public function onFieldDefinitionCreate(FieldDefinitionInterface $field_definition) { }
160 161 162 163

  /**
   * {@inheritdoc}
   */
164
  public function onFieldDefinitionUpdate(FieldDefinitionInterface $field_definition, FieldDefinitionInterface $original) { }
165 166 167 168

  /**
   * {@inheritdoc}
   */
169
  public function onFieldDefinitionDelete(FieldDefinitionInterface $field_definition) { }
170 171 172 173

  /**
   * {@inheritdoc}
   */
174 175 176 177
  public function purgeFieldData(FieldDefinitionInterface $field_definition, $batch_size) {
    $items_by_entity = $this->readFieldItemsToPurge($field_definition, $batch_size);

    foreach ($items_by_entity as $items) {
178
      $items->delete();
179
      $this->purgeFieldItems($items->getEntity(), $field_definition);
180
    }
181
    return count($items_by_entity);
182 183 184
  }

  /**
185
   * Reads values to be purged for a single field.
186 187
   *
   * This method is called during field data purge, on fields for which
188
   * onFieldDefinitionDelete() has previously run.
189
   *
190 191 192 193
   * @param \Drupal\Core\Field\FieldDefinitionInterface $field_definition
   *   The field definition.
   * @param $batch_size
   *   The maximum number of field data records to purge before returning.
194
   *
195 196
   * @return \Drupal\Core\Field\FieldItemListInterface[]
   *   An array of field item lists, keyed by entity revision id.
197
   */
198
  abstract protected function readFieldItemsToPurge(FieldDefinitionInterface $field_definition, $batch_size);
199 200

  /**
201
   * Removes field items from storage per entity during purge.
202
   *
203 204 205
   * @param ContentEntityInterface $entity
   *   The entity revision, whose values are being purged.
   * @param \Drupal\Core\Field\FieldDefinitionInterface $field_definition
206 207
   *   The field whose values are bing purged.
   */
208
  abstract protected function purgeFieldItems(ContentEntityInterface $entity, FieldDefinitionInterface $field_definition);
209 210 211 212

  /**
   * {@inheritdoc}
   */
213
  public function finalizePurge(FieldStorageDefinitionInterface $storage_definition) { }
214

215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290
  /**
   * {@inheritdoc}
   */
  public function loadRevision($revision_id) {
    $revision = $this->doLoadRevisionFieldItems($revision_id);

    if ($revision) {
      $entities = [$revision->id() => $revision];
      $this->invokeStorageLoadHook($entities);
      $this->postLoad($entities);
    }

    return $revision;
  }

  /**
   * Actually loads revision field item values from the storage.
   *
   * @param int|string $revision_id
   *   The revision identifier.
   *
   * @return \Drupal\Core\Entity\EntityInterface|null
   *   The specified entity revision or NULL if not found.
   */
  abstract protected function doLoadRevisionFieldItems($revision_id);

  /**
   * {@inheritdoc}
   */
  protected function doSave($id, EntityInterface $entity) {
    /** @var \Drupal\Core\Entity\ContentEntityInterface $entity */

    if ($entity->isNew()) {
      // Ensure the entity is still seen as new after assigning it an id, while
      // storing its data.
      $entity->enforceIsNew();
      if ($this->entityType->isRevisionable()) {
        $entity->setNewRevision();
      }
      $return = SAVED_NEW;
    }
    else {
      // @todo Consider returning a different value when saving a non-default
      //   entity revision. See https://www.drupal.org/node/2509360.
      $return = $entity->isDefaultRevision() ? SAVED_UPDATED : FALSE;
    }

    $this->populateAffectedRevisionTranslations($entity);
    $this->doSaveFieldItems($entity);

    return $return;
  }

  /**
   * Writes entity field values to the storage.
   *
   * This method is responsible for allocating entity and revision identifiers
   * and updating the entity object with their values.
   *
   * @param \Drupal\Core\Entity\ContentEntityInterface $entity
   *   The entity object.
   * @param string[] $names
   *   (optional) The name of the fields to be written to the storage. If an
   *   empty value is passed all field values are saved.
   */
  abstract protected function doSaveFieldItems(ContentEntityInterface $entity, array $names = []);

  /**
   * {@inheritdoc}
   */
  protected function doPreSave(EntityInterface $entity) {
    /** @var \Drupal\Core\Entity\ContentEntityBase $entity */

    // Sync the changes made in the fields array to the internal values array.
    $entity->updateOriginalValues();

291 292 293 294 295 296 297
    if ($entity->getEntityType()->isRevisionable() && !$entity->isNew() && empty($entity->getLoadedRevisionId())) {
      // Update the loaded revision id for rare special cases when no loaded
      // revision is given when updating an existing entity. This for example
      // happens when calling save() in hook_entity_insert().
      $entity->updateLoadedRevisionId();
    }

298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313
    $id = parent::doPreSave($entity);

    if (!$entity->isNew()) {
      // If the ID changed then original can't be loaded, throw an exception
      // in that case.
      if (empty($entity->original) || $entity->id() != $entity->original->id()) {
        throw new EntityStorageException("Update existing '{$this->entityTypeId}' entity while changing the ID is not supported.");
      }
      // Do not allow changing the revision ID when resaving the current
      // revision.
      if (!$entity->isNewRevision() && $entity->getRevisionId() != $entity->getLoadedRevisionId()) {
        throw new EntityStorageException("Update existing '{$this->entityTypeId}' entity revision while changing the revision ID is not supported.");
      }
    }

    return $id;
314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329
  }

  /**
   * {@inheritdoc}
   */
  protected function doPostSave(EntityInterface $entity, $update) {
    /** @var \Drupal\Core\Entity\ContentEntityInterface $entity */

    if ($update && $this->entityType->isTranslatable()) {
      $this->invokeTranslationHooks($entity);
    }

    parent::doPostSave($entity, $update);

    // The revision is stored, it should no longer be marked as new now.
    if ($this->entityType->isRevisionable()) {
330
      $entity->updateLoadedRevisionId();
331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377
      $entity->setNewRevision(FALSE);
    }
  }

  /**
   * {@inheritdoc}
   */
  protected function doDelete($entities) {
    /** @var \Drupal\Core\Entity\ContentEntityInterface[] $entities */
    foreach ($entities as $entity) {
      $this->invokeFieldMethod('delete', $entity);
    }
    $this->doDeleteFieldItems($entities);
  }

  /**
   * Deletes entity field values from the storage.
   *
   * @param \Drupal\Core\Entity\ContentEntityInterface[] $entities
   *   An array of entity objects to be deleted.
   */
  abstract protected function doDeleteFieldItems($entities);

  /**
   * {@inheritdoc}
   */
  public function deleteRevision($revision_id) {
    /** @var \Drupal\Core\Entity\ContentEntityInterface $revision */
    if ($revision = $this->loadRevision($revision_id)) {
      // Prevent deletion if this is the default revision.
      if ($revision->isDefaultRevision()) {
        throw new EntityStorageException('Default revision can not be deleted');
      }
      $this->invokeFieldMethod('deleteRevision', $revision);
      $this->doDeleteRevisionFieldItems($revision);
      $this->invokeHook('revision_delete', $revision);
    }
  }

  /**
   * Deletes field values of an entity revision from the storage.
   *
   * @param \Drupal\Core\Entity\ContentEntityInterface $revision
   *   An entity revision object to be deleted.
   */
  abstract protected function doDeleteRevisionFieldItems(ContentEntityInterface $revision);

378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394
  /**
   * Checks translation statuses and invoke the related hooks if needed.
   *
   * @param \Drupal\Core\Entity\ContentEntityInterface $entity
   *   The entity being saved.
   */
  protected function invokeTranslationHooks(ContentEntityInterface $entity) {
    $translations = $entity->getTranslationLanguages(FALSE);
    $original_translations = $entity->original->getTranslationLanguages(FALSE);
    $all_translations = array_keys($translations + $original_translations);

    // Notify modules of translation insertion/deletion.
    foreach ($all_translations as $langcode) {
      if (isset($translations[$langcode]) && !isset($original_translations[$langcode])) {
        $this->invokeHook('translation_insert', $entity->getTranslation($langcode));
      }
      elseif (!isset($translations[$langcode]) && isset($original_translations[$langcode])) {
395
        $this->invokeHook('translation_delete', $entity->original->getTranslation($langcode));
396 397 398 399
      }
    }
  }

400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420
  /**
   * Invokes hook_entity_storage_load().
   *
   * @param \Drupal\Core\Entity\ContentEntityInterface[] $entities
   *   List of entities, keyed on the entity ID.
   */
  protected function invokeStorageLoadHook(array &$entities) {
    if (!empty($entities)) {
      // Call hook_entity_storage_load().
      foreach ($this->moduleHandler()->getImplementations('entity_storage_load') as $module) {
        $function = $module . '_entity_storage_load';
        $function($entities, $this->entityTypeId);
      }
      // Call hook_TYPE_storage_load().
      foreach ($this->moduleHandler()->getImplementations($this->entityTypeId . '_storage_load') as $module) {
        $function = $module . '_' . $this->entityTypeId . '_storage_load';
        $function($entities);
      }
    }
  }

421 422 423 424
  /**
   * {@inheritdoc}
   */
  protected function invokeHook($hook, EntityInterface $entity) {
425 426 427 428 429 430 431 432 433 434 435 436 437 438
    /** @var \Drupal\Core\Entity\ContentEntityInterface $entity */

    switch ($hook) {
      case 'presave':
        $this->invokeFieldMethod('preSave', $entity);
        break;

      case 'insert':
        $this->invokeFieldPostSave($entity, FALSE);
        break;

      case 'update':
        $this->invokeFieldPostSave($entity, TRUE);
        break;
439
    }
440

441 442 443
    parent::invokeHook($hook, $entity);
  }

444 445 446
  /**
   * Invokes a method on the Field objects within an entity.
   *
447 448
   * Any argument passed will be forwarded to the invoked method.
   *
449
   * @param string $method
450
   *   The name of the method to be invoked.
451 452
   * @param \Drupal\Core\Entity\ContentEntityInterface $entity
   *   The entity object.
453 454 455 456
   *
   * @return array
   *   A multidimensional associative array of results, keyed by entity
   *   translation language code and field name.
457 458
   */
  protected function invokeFieldMethod($method, ContentEntityInterface $entity) {
459 460
    $result = [];
    $args = array_slice(func_get_args(), 2);
461
    $langcodes = array_keys($entity->getTranslationLanguages());
462 463 464 465 466 467 468
    // Ensure that the field method is invoked as first on the current entity
    // translation and then on all other translations.
    $current_entity_langcode = $entity->language()->getId();
    if (reset($langcodes) != $current_entity_langcode) {
      $langcodes = array_diff($langcodes, [$current_entity_langcode]);
      array_unshift($langcodes, $current_entity_langcode);
    }
469
    foreach ($langcodes as $langcode) {
470
      $translation = $entity->getTranslation($langcode);
471 472 473 474 475 476
      // For non translatable fields, there is only one field object instance
      // across all translations and it has as parent entity the entity in the
      // default entity translation. Therefore field methods on non translatable
      // fields should be invoked only on the default entity translation.
      $fields = $translation->isDefaultTranslation() ? $translation->getFields() : $translation->getTranslatableFields();
      foreach ($fields as $name => $items) {
477 478 479
        // call_user_func_array() is way slower than a direct call so we avoid
        // using it if have no parameters.
        $result[$langcode][$name] = $args ? call_user_func_array([$items, $method], $args) : $items->{$method}();
480 481
      }
    }
482 483 484 485 486 487 488 489 490 491 492 493 494 495

    // We need to call the delete method for field items of removed
    // translations.
    if ($method == 'postSave' && !empty($entity->original)) {
      $original_langcodes = array_keys($entity->original->getTranslationLanguages());
      foreach (array_diff($original_langcodes, $langcodes) as $removed_langcode) {
        $translation = $entity->original->getTranslation($removed_langcode);
        $fields = $translation->getTranslatableFields();
        foreach ($fields as $name => $items) {
          $items->delete();
        }
      }
    }

496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516
    return $result;
  }

  /**
   * Invokes the post save method on the Field objects within an entity.
   *
   * @param \Drupal\Core\Entity\ContentEntityInterface $entity
   *   The entity object.
   * @param bool $update
   *   Specifies whether the entity is being updated or created.
   */
  protected function invokeFieldPostSave(ContentEntityInterface $entity, $update) {
    // For each entity translation this returns an array of resave flags keyed
    // by field name, thus we merge them to obtain a list of fields to resave.
    $resave = [];
    foreach ($this->invokeFieldMethod('postSave', $entity, $update) as $translation_results) {
      $resave += array_filter($translation_results);
    }
    if ($resave) {
      $this->doSaveFieldItems($entity, array_keys($resave));
    }
517 518
  }

519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550
  /**
   * Checks whether the field values changed compared to the original entity.
   *
   * @param \Drupal\Core\Field\FieldDefinitionInterface $field_definition
   *   Field definition of field to compare for changes.
   * @param \Drupal\Core\Entity\ContentEntityInterface $entity
   *   Entity to check for field changes.
   * @param \Drupal\Core\Entity\ContentEntityInterface $original
   *   Original entity to compare against.
   *
   * @return bool
   *   True if the field value changed from the original entity.
   */
  protected function hasFieldValueChanged(FieldDefinitionInterface $field_definition, ContentEntityInterface $entity, ContentEntityInterface $original) {
    $field_name = $field_definition->getName();
    $langcodes = array_keys($entity->getTranslationLanguages());
    if ($langcodes !== array_keys($original->getTranslationLanguages())) {
      // If the list of langcodes has changed, we need to save.
      return TRUE;
    }
    foreach ($langcodes as $langcode) {
      $items = $entity->getTranslation($langcode)->get($field_name)->filterEmptyItems();
      $original_items = $original->getTranslation($langcode)->get($field_name)->filterEmptyItems();
      // If the field items are not equal, we need to save.
      if (!$items->equals($original_items)) {
        return TRUE;
      }
    }

    return FALSE;
  }

551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570
  /**
   * Populates the affected flag for all the revision translations.
   *
   * @param \Drupal\Core\Entity\ContentEntityInterface $entity
   *   An entity object being saved.
   */
  protected function populateAffectedRevisionTranslations(ContentEntityInterface $entity) {
    if ($this->entityType->isTranslatable() && $this->entityType->isRevisionable()) {
      $languages = $entity->getTranslationLanguages();
      foreach ($languages as $langcode => $language) {
        $translation = $entity->getTranslation($langcode);
        // Avoid populating the value if it was already manually set.
        $affected = $translation->isRevisionTranslationAffected();
        if (!isset($affected) && $translation->hasTranslationChanges()) {
          $translation->setRevisionTranslationAffected(TRUE);
        }
      }
    }
  }

571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649
  /**
   * Ensures integer entity IDs are valid.
   *
   * The identifier sanitization provided by this method has been introduced
   * as Drupal used to rely on the database to facilitate this, which worked
   * correctly with MySQL but led to errors with other DBMS such as PostgreSQL.
   *
   * @param array $ids
   *   The entity IDs to verify.
   *
   * @return array
   *   The sanitized list of entity IDs.
   */
  protected function cleanIds(array $ids) {
    $definitions = $this->entityManager->getBaseFieldDefinitions($this->entityTypeId);
    $id_definition = $definitions[$this->entityType->getKey('id')];
    if ($id_definition->getType() == 'integer') {
      $ids = array_filter($ids, function ($id) {
        return is_numeric($id) && $id == (int) $id;
      });
      $ids = array_map('intval', $ids);
    }
    return $ids;
  }

  /**
   * Gets entities from the persistent cache backend.
   *
   * @param array|null &$ids
   *   If not empty, return entities that match these IDs. IDs that were found
   *   will be removed from the list.
   *
   * @return \Drupal\Core\Entity\ContentEntityInterface[]
   *   Array of entities from the persistent cache.
   */
  protected function getFromPersistentCache(array &$ids = NULL) {
    if (!$this->entityType->isPersistentlyCacheable() || empty($ids)) {
      return array();
    }
    $entities = array();
    // Build the list of cache entries to retrieve.
    $cid_map = array();
    foreach ($ids as $id) {
      $cid_map[$id] = $this->buildCacheId($id);
    }
    $cids = array_values($cid_map);
    if ($cache = $this->cacheBackend->getMultiple($cids)) {
      // Get the entities that were found in the cache.
      foreach ($ids as $index => $id) {
        $cid = $cid_map[$id];
        if (isset($cache[$cid])) {
          $entities[$id] = $cache[$cid]->data;
          unset($ids[$index]);
        }
      }
    }
    return $entities;
  }

  /**
   * Stores entities in the persistent cache backend.
   *
   * @param \Drupal\Core\Entity\ContentEntityInterface[] $entities
   *   Entities to store in the cache.
   */
  protected function setPersistentCache($entities) {
    if (!$this->entityType->isPersistentlyCacheable()) {
      return;
    }

    $cache_tags = array(
      $this->entityTypeId . '_values',
      'entity_field_info',
    );
    foreach ($entities as $id => $entity) {
      $this->cacheBackend->set($this->buildCacheId($id), $entity, CacheBackendInterface::CACHE_PERMANENT, $cache_tags);
    }
  }

650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689
  /**
   * {@inheritdoc}
   */
  public function loadUnchanged($id) {
    $ids = [$id];

    // The cache invalidation in the parent has the side effect that loading the
    // same entity again during the save process (for example in
    // hook_entity_presave()) will load the unchanged entity. Simulate this
    // by explicitly removing the entity from the static cache.
    parent::resetCache($ids);

    // The default implementation in the parent class unsets the current cache
    // and then reloads the entity. That is slow, especially if this is done
    // repeatedly in the same request, e.g. when validating and then saving
    // an entity. Optimize this for content entities by trying to load them
    // directly from the persistent cache again, as in contrast to the static
    // cache the persistent one will never be changed until the entity is saved.
    $entities = $this->getFromPersistentCache($ids);

    if (!$entities) {
      $entities[$id] = $this->load($id);
    }
    else {
      // As the entities are put into the persistent cache before the post load
      // has been executed we have to execute it if we have retrieved the
      // entity directly from the persistent cache.
      $this->postLoad($entities);

      if ($this->entityType->isStaticallyCacheable()) {
        // As we've removed the entity from the static cache already we have to
        // put the loaded unchanged entity there to simulate the behavior of the
        // parent.
        $this->setStaticCache($entities);
      }
    }

    return $entities[$id];
  }

690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724
  /**
   * {@inheritdoc}
   */
  public function resetCache(array $ids = NULL) {
    if ($ids) {
      $cids = array();
      foreach ($ids as $id) {
        unset($this->entities[$id]);
        $cids[] = $this->buildCacheId($id);
      }
      if ($this->entityType->isPersistentlyCacheable()) {
        $this->cacheBackend->deleteMultiple($cids);
      }
    }
    else {
      $this->entities = array();
      if ($this->entityType->isPersistentlyCacheable()) {
        Cache::invalidateTags(array($this->entityTypeId . '_values'));
      }
    }
  }

  /**
   * Builds the cache ID for the passed in entity ID.
   *
   * @param int $id
   *   Entity ID for which the cache ID should be built.
   *
   * @return string
   *   Cache ID that can be passed to the cache backend.
   */
  protected function buildCacheId($id) {
    return "values:{$this->entityTypeId}:$id";
  }

725
}