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

/**
 * @file
5
 * Contains \Drupal\Core\Entity\ContentEntityStorageBase.
6 7 8 9
 */

namespace Drupal\Core\Entity;

10 11
use Drupal\Core\Cache\Cache;
use Drupal\Core\Cache\CacheBackendInterface;
12 13
use Drupal\Core\Field\FieldDefinitionInterface;
use Drupal\Core\Field\FieldStorageDefinitionInterface;
14
use Symfony\Component\DependencyInjection\ContainerInterface;
15

16
abstract class ContentEntityStorageBase extends EntityStorageBase implements DynamicallyFieldableEntityStorageInterface {
17

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

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

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

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

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

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

77 78 79
  /**
   * {@inheritdoc}
   */
80
  protected function doCreate(array $values) {
81 82 83 84
    // We have to determine the bundle first.
    $bundle = FALSE;
    if ($this->bundleKey) {
      if (!isset($values[$this->bundleKey])) {
85
        throw new EntityStorageException('Missing bundle for entity type ' . $this->entityTypeId);
86 87 88
      }
      $bundle = $values[$this->bundleKey];
    }
89
    $entity = new $this->entityClass(array(), $this->entityTypeId, $bundle);
90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107

    foreach ($entity as $name => $field) {
      if (isset($values[$name])) {
        $entity->$name = $values[$name];
      }
      elseif (!array_key_exists($name, $values)) {
        $entity->get($name)->applyDefaultValue();
      }
      unset($values[$name]);
    }

    // Set any passed values for non-defined fields also.
    foreach ($values as $name => $value) {
      $entity->$name = $value;
    }
    return $entity;
  }

108 109 110
  /**
   * {@inheritdoc}
   */
111
  public function onFieldStorageDefinitionCreate(FieldStorageDefinitionInterface $storage_definition) { }
112 113 114 115

  /**
   * {@inheritdoc}
   */
116
  public function onFieldStorageDefinitionUpdate(FieldStorageDefinitionInterface $storage_definition, FieldStorageDefinitionInterface $original) { }
117 118 119 120

  /**
   * {@inheritdoc}
   */
121
  public function onFieldStorageDefinitionDelete(FieldStorageDefinitionInterface $storage_definition) { }
122 123 124 125

  /**
   * {@inheritdoc}
   */
126
  public function onFieldDefinitionCreate(FieldDefinitionInterface $field_definition) { }
127 128 129 130

  /**
   * {@inheritdoc}
   */
131
  public function onFieldDefinitionUpdate(FieldDefinitionInterface $field_definition, FieldDefinitionInterface $original) { }
132 133 134 135

  /**
   * {@inheritdoc}
   */
136
  public function onFieldDefinitionDelete(FieldDefinitionInterface $field_definition) { }
137 138 139 140

  /**
   * {@inheritdoc}
   */
141 142 143 144
  public function purgeFieldData(FieldDefinitionInterface $field_definition, $batch_size) {
    $items_by_entity = $this->readFieldItemsToPurge($field_definition, $batch_size);

    foreach ($items_by_entity as $items) {
145
      $items->delete();
146
      $this->purgeFieldItems($items->getEntity(), $field_definition);
147
    }
148
    return count($items_by_entity);
149 150 151
  }

  /**
152
   * Reads values to be purged for a single field.
153 154
   *
   * This method is called during field data purge, on fields for which
155
   * onFieldDefinitionDelete() has previously run.
156
   *
157 158 159 160
   * @param \Drupal\Core\Field\FieldDefinitionInterface $field_definition
   *   The field definition.
   * @param $batch_size
   *   The maximum number of field data records to purge before returning.
161
   *
162 163
   * @return \Drupal\Core\Field\FieldItemListInterface[]
   *   An array of field item lists, keyed by entity revision id.
164
   */
165
  abstract protected function readFieldItemsToPurge(FieldDefinitionInterface $field_definition, $batch_size);
166 167

  /**
168
   * Removes field items from storage per entity during purge.
169
   *
170 171 172
   * @param ContentEntityInterface $entity
   *   The entity revision, whose values are being purged.
   * @param \Drupal\Core\Field\FieldDefinitionInterface $field_definition
173 174
   *   The field whose values are bing purged.
   */
175
  abstract protected function purgeFieldItems(ContentEntityInterface $entity, FieldDefinitionInterface $field_definition);
176 177 178 179

  /**
   * {@inheritdoc}
   */
180
  public function finalizePurge(FieldStorageDefinitionInterface $storage_definition) { }
181

182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 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 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321
  /**
   * {@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();

    return parent::doPreSave($entity);
  }

  /**
   * {@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()) {
      $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);

322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343
  /**
   * 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])) {
        $this->invokeHook('translation_delete', $entity->getTranslation($langcode));
      }
    }
  }

344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364
  /**
   * 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);
      }
    }
  }

365 366 367 368
  /**
   * {@inheritdoc}
   */
  protected function invokeHook($hook, EntityInterface $entity) {
369 370 371 372 373 374 375 376 377 378 379 380 381 382
    /** @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;
383
    }
384

385 386 387
    parent::invokeHook($hook, $entity);
  }

388 389 390
  /**
   * Invokes a method on the Field objects within an entity.
   *
391 392
   * Any argument passed will be forwarded to the invoked method.
   *
393
   * @param string $method
394
   *   The name of the method to be invoked.
395 396
   * @param \Drupal\Core\Entity\ContentEntityInterface $entity
   *   The entity object.
397 398 399 400
   *
   * @return array
   *   A multidimensional associative array of results, keyed by entity
   *   translation language code and field name.
401 402
   */
  protected function invokeFieldMethod($method, ContentEntityInterface $entity) {
403 404
    $result = [];
    $args = array_slice(func_get_args(), 2);
405 406
    foreach (array_keys($entity->getTranslationLanguages()) as $langcode) {
      $translation = $entity->getTranslation($langcode);
407 408 409 410 411 412
      // 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) {
413 414 415
        // 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}();
416 417
      }
    }
418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438
    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));
    }
439 440
  }

441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472
  /**
   * 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;
  }

473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492
  /**
   * 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);
        }
      }
    }
  }

493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 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 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 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
  /**
   * 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);
    }
  }

  /**
   * {@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";
  }

607
}