DatabaseStorageControllerNG.php 21.1 KB
Newer Older
1 2 3 4
<?php

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

namespace Drupal\Core\Entity;

10
use Drupal\Core\Language\Language;
11 12
use PDO;

13
use Drupal\Core\Entity\Query\QueryInterface;
14 15 16 17
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Entity\DatabaseStorageController;
use Drupal\Core\Entity\EntityStorageException;
use Drupal\Component\Uuid\Uuid;
18
use Drupal\Core\Database\Connection;
19 20 21 22 23 24

/**
 * Implements Field API specific enhancements to the DatabaseStorageController class.
 *
 * @todo: Once all entity types have been converted, merge improvements into the
 * DatabaseStorageController class.
25 26 27 28
 *
 * See the EntityNG documentation for an explanation of "NG".
 *
 * @see \Drupal\Core\EntityNG
29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
 */
class DatabaseStorageControllerNG extends DatabaseStorageController {

  /**
   * The entity class to use.
   *
   * @var string
   */
  protected $entityClass;

  /**
   * The entity bundle key.
   *
   * @var string|bool
   */
  protected $bundleKey;

46 47 48 49 50 51 52
  /**
   * The table that stores properties, if the entity has multilingual support.
   *
   * @var string
   */
  protected $dataTable;

53 54 55
  /**
   * Overrides DatabaseStorageController::__construct().
   */
56 57
  public function __construct($entity_type, array $entity_info, Connection $database) {
    parent::__construct($entity_type,$entity_info, $database);
58 59
    $this->bundleKey = !empty($this->entityInfo['entity_keys']['bundle']) ? $this->entityInfo['entity_keys']['bundle'] : FALSE;
    $this->entityClass = $this->entityInfo['class'];
60

61 62 63 64 65
    // Check if the entity type has a dedicated table for properties.
    if (!empty($this->entityInfo['data_table'])) {
      $this->dataTable = $this->entityInfo['data_table'];
    }

66 67 68 69
    // Work-a-round to let load() get stdClass storage records without having to
    // override it. We map storage records to entities in
    // DatabaseStorageControllerNG:: mapFromStorageRecords().
    // @todo: Remove this once this is moved in the main controller.
70
    unset($this->entityInfo['class']);
71 72 73 74 75 76 77 78 79 80
  }

  /**
   * Overrides DatabaseStorageController::create().
   *
   * @param array $values
   *   An array of values to set, keyed by field name. The value has to be
   *   the plain value of an entity field, i.e. an array of field items.
   *   If no numerically indexed array is given, the value will be set for the
   *   first field item. For example, to set the first item of a 'name'
81
   *   field one can pass:
82 83 84 85 86 87 88 89
   *   @code
   *     $values = array('name' => array(0 => array('value' => 'the name')));
   *   @endcode
   *   or
   *   @code
   *     $values = array('name' => array('value' => 'the name'));
   *   @endcode
   *   If the 'name' field is a defined as 'string_item' which supports
90 91
   *   setting its value by a string, it's also possible to just pass the name
   *   string:
92 93 94 95
   *   @code
   *     $values = array('name' => 'the name');
   *   @endcode
   *
96
   * @return \Drupal\Core\Entity\EntityInterface
97 98 99
   *   A new entity object.
   */
  public function create(array $values) {
100 101 102
    $entity_class = $this->entityClass;
    $entity_class::preCreate($this, $values);

103
    // We have to determine the bundle first.
104 105 106
    $bundle = FALSE;
    if ($this->bundleKey) {
      if (!isset($values[$this->bundleKey])) {
107
        throw new EntityStorageException(format_string('Missing bundle for entity type @type', array('@type' => $this->entityType)));
108 109 110
      }
      $bundle = $values[$this->bundleKey];
    }
111
    $entity = new $this->entityClass(array(), $this->entityType, $bundle);
112

113 114 115 116 117 118 119 120
    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]);
121 122
    }

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

    // Modules might need to add or change the data initially held by the new
    // entity object, for instance to fill-in default values.
    $this->invokeHook('create', $entity);

133 134 135
    return $entity;
  }

136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163
  /**
   * Builds an entity query.
   *
   * @param \Drupal\Core\Entity\Query\QueryInterface $entity_query
   *   EntityQuery instance.
   * @param array $values
   *   An associative array of properties of the entity, where the keys are the
   *   property names and the values are the values those properties must have.
   */
  protected function buildPropertyQuery(QueryInterface $entity_query, array $values) {
    if ($this->dataTable) {
      // @todo We should not be using a condition to specify whether conditions
      //   apply to the default language. See http://drupal.org/node/1866330.
      // Default to the original entity language if not explicitly specified
      // otherwise.
      if (!array_key_exists('default_langcode', $values)) {
        $values['default_langcode'] = 1;
      }
      // If the 'default_langcode' flag is explicitly not set, we do not care
      // whether the queried values are in the original entity language or not.
      elseif ($values['default_langcode'] === NULL) {
        unset($values['default_langcode']);
      }
    }

    parent::buildPropertyQuery($entity_query, $values);
  }

164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 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
  /**
   * {@inheritdoc}
   */
  protected function buildQuery($ids, $revision_id = FALSE) {
    $query = $this->database->select($this->entityInfo['base_table'], 'base');
    $is_revision_query = $this->revisionKey && ($revision_id || !$this->dataTable);

    $query->addTag($this->entityType . '_load_multiple');

    if ($revision_id) {
      $query->join($this->revisionTable, 'revision', "revision.{$this->idKey} = base.{$this->idKey} AND revision.{$this->revisionKey} = :revisionId", array(':revisionId' => $revision_id));
    }
    elseif ($is_revision_query) {
      $query->join($this->revisionTable, 'revision', "revision.{$this->revisionKey} = base.{$this->revisionKey}");
    }

    // Add fields from the {entity} table.
    $entity_fields = drupal_schema_fields_sql($this->entityInfo['base_table']);

    if ($is_revision_query) {
      // Add all fields from the {entity_revision} table.
      $entity_revision_fields = drupal_map_assoc(drupal_schema_fields_sql($this->entityInfo['revision_table']));
      // The ID field is provided by entity, so remove it.
      unset($entity_revision_fields[$this->idKey]);

      // Remove all fields from the base table that are also fields by the same
      // name in the revision table.
      $entity_field_keys = array_flip($entity_fields);
      foreach ($entity_revision_fields as $key => $name) {
        if (isset($entity_field_keys[$name])) {
          unset($entity_fields[$entity_field_keys[$name]]);
        }
      }
      $query->fields('revision', $entity_revision_fields);

      // Compare revision ID of the base and revision table, if equal then this
      // is the default revision.
      $query->addExpression('base.' . $this->revisionKey . ' = revision.' . $this->revisionKey, 'isDefaultRevision');
    }

    $query->fields('base', $entity_fields);

    if ($ids) {
      $query->condition("base.{$this->idKey}", $ids, 'IN');
    }

    return $query;
  }

213 214 215 216 217 218
  /**
   * Overrides DatabaseStorageController::attachLoad().
   *
   * Added mapping from storage records to entities.
   */
  protected function attachLoad(&$queried_entities, $load_revision = FALSE) {
219
    // Map the loaded stdclass records into entity objects and according fields.
220
    $queried_entities = $this->mapFromStorageRecords($queried_entities, $load_revision);
221
    parent::attachLoad($queried_entities, $load_revision);
222 223 224 225 226
  }

  /**
   * Maps from storage records to entity objects.
   *
227 228 229 230 231
   * @param array $records
   *   Associative array of query results, keyed on the entity ID.
   * @param boolean $load_revision
   *   (optional) TRUE if the revision should be loaded, defaults to FALSE.
   *
232 233 234
   * @return array
   *   An array of entity objects implementing the EntityInterface.
   */
235
  protected function mapFromStorageRecords(array $records, $load_revision = FALSE) {
236
    $entities = array();
237
    foreach ($records as $id => $record) {
238
      $entities[$id] = array();
239
      foreach ($record as $name => $value) {
240 241 242
        // Skip the item delta and item value levels but let the field assign
        // the value as suiting. This avoids unnecessary array hierarchies and
        // saves memory here.
243 244 245 246 247 248 249 250
        $entities[$id][$name][Language::LANGCODE_DEFAULT] = $value;
      }
      // If we have no multilingual values we can instantiate entity objecs
      // right now, otherwise we need to collect all the field values first.
      if (!$this->dataTable) {
        $bundle = $this->bundleKey ? $record->{$this->bundleKey} : FALSE;
        // Turn the record into an entity class.
        $entities[$id] = new $this->entityClass($entities[$id], $this->entityType, $bundle);
251
      }
252 253 254 255 256 257 258 259 260 261
    }
    $this->attachPropertyData($entities, $load_revision);
    return $entities;
  }

  /**
   * Attaches property data in all languages for translatable properties.
   *
   * @param array &$entities
   *   Associative array of entities, keyed on the entity ID.
262 263
   * @param int $revision_id
   *   (optional) The revision to be loaded. Defaults to FALSE.
264
   */
265
  protected function attachPropertyData(array &$entities, $revision_id = FALSE) {
266
    if ($this->dataTable) {
267 268 269 270
      // If a revision table is available, we need all the properties of the
      // latest revision. Otherwise we fall back to the data table.
      $table = $this->revisionTable ?: $this->dataTable;
      $query = $this->database->select($table, 'data', array('fetch' => PDO::FETCH_ASSOC))
271 272 273
        ->fields('data')
        ->condition($this->idKey, array_keys($entities))
        ->orderBy('data.' . $this->idKey);
274 275 276 277 278 279 280 281 282 283 284 285

      if ($this->revisionTable) {
        if ($revision_id) {
          $query->condition($this->revisionKey, $revision_id);
        }
        else {
          // Get the revision IDs.
          $revision_ids = array();
          foreach ($entities as $id => $values) {
            $revision_ids[] = $values[$this->revisionKey];
          }
          $query->condition($this->revisionKey, $revision_ids);
286 287 288
        }
      }

289
      $data = $query->execute();
290
      $field_definition = \Drupal::entityManager()->getFieldDefinitions($this->entityType);
291
      $translations = array();
292 293 294 295 296 297
      if ($this->revisionTable) {
        $data_fields = array_flip(array_diff(drupal_schema_fields_sql($this->entityInfo['revision_table']), drupal_schema_fields_sql($this->entityInfo['base_table'])));
      }
      else {
        $data_fields = array_flip(drupal_schema_fields_sql($this->entityInfo['data_table']));
      }
298 299 300

      foreach ($data as $values) {
        $id = $values[$this->idKey];
301

302 303 304
        // Field values in default language are stored with
        // Language::LANGCODE_DEFAULT as key.
        $langcode = empty($values['default_langcode']) ? $values['langcode'] : Language::LANGCODE_DEFAULT;
305
        $translations[$id][$langcode] = TRUE;
306 307

        foreach ($field_definition as $name => $definition) {
308 309 310 311 312 313
          // Set only translatable properties, unless we are dealing with a
          // revisable entity, in which case we did not load the untranslatable
          // data before.
          $translatable = !empty($definition['translatable']);
          if (isset($data_fields[$name]) && ($this->revisionTable || $translatable)) {
            $entities[$id][$name][$langcode] = $values[$name];
314 315 316
          }
        }
      }
317 318 319 320

      foreach ($entities as $id => $values) {
        $bundle = $this->bundleKey ? $values[$this->bundleKey][Language::LANGCODE_DEFAULT] : FALSE;
        // Turn the record into an entity class.
321
        $entities[$id] = new $this->entityClass($values, $this->entityType, $bundle, array_keys($translations[$id]));
322
      }
323 324 325 326 327 328 329 330 331
    }
  }

  /**
   * Overrides DatabaseStorageController::save().
   *
   * Added mapping from entities to storage records before saving.
   */
  public function save(EntityInterface $entity) {
332
    $transaction = $this->database->startTransaction();
333
    try {
334
      // Ensure we are dealing with the actual entity.
335
      $entity = $entity->getNGEntity();
336 337 338 339

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

340 341 342 343 344
      // Load the stored entity, if any.
      if (!$entity->isNew() && !isset($entity->original)) {
        $entity->original = entity_load_unchanged($this->entityType, $entity->id());
      }

345
      $entity->preSave($this);
346
      $this->invokeFieldMethod('preSave', $entity);
347 348 349
      $this->invokeHook('presave', $entity);

      // Create the storage record to be saved.
350
      $record = $this->mapToStorageRecord($entity);
351 352

      if (!$entity->isNew()) {
353 354 355 356 357 358 359 360 361 362 363
        if ($entity->isDefaultRevision()) {
          $return = drupal_write_record($this->entityInfo['base_table'], $record, $this->idKey);
        }
        else {
          // @todo, should a different value be returned when saving an entity
          // with $isDefaultRevision = FALSE?
          $return = FALSE;
        }
        if ($this->revisionKey) {
          $record->{$this->revisionKey} = $this->saveRevision($entity);
        }
364 365 366
        if ($this->dataTable) {
          $this->savePropertyData($entity);
        }
367
        $this->resetCache(array($entity->id()));
368
        $entity->postSave($this, TRUE);
369
        $this->invokeFieldMethod('update', $entity);
370
        $this->invokeHook('update', $entity);
371 372 373
        if ($this->dataTable) {
          $this->invokeTranslationHooks($entity);
        }
374 375
      }
      else {
376
        $return = drupal_write_record($this->entityInfo['base_table'], $record);
377
        $entity->{$this->idKey}->value = $record->{$this->idKey};
378 379 380
        if ($this->revisionKey) {
          $record->{$this->revisionKey} = $this->saveRevision($entity);
        }
381 382 383 384 385
        $entity->{$this->idKey}->value = $record->{$this->idKey};
        if ($this->dataTable) {
          $this->savePropertyData($entity);
        }

386 387 388 389
        // Reset general caches, but keep caches specific to certain entities.
        $this->resetCache(array());

        $entity->enforceIsNew(FALSE);
390
        $entity->postSave($this, FALSE);
391
        $this->invokeFieldMethod('insert', $entity);
392 393 394 395 396 397 398 399 400
        $this->invokeHook('insert', $entity);
      }

      // Ignore slave server temporarily.
      db_ignore_slave();
      unset($entity->original);

      return $return;
    }
401
    catch (\Exception $e) {
402 403 404 405 406 407
      $transaction->rollback();
      watchdog_exception($this->entityType, $e);
      throw new EntityStorageException($e->getMessage(), $e->getCode(), $e);
    }
  }

408 409 410 411 412 413 414 415 416 417
  /**
   * Saves an entity revision.
   *
   * @param \Drupal\Core\Entity\EntityInterface $entity
   *   The entity object.
   *
   * @return integer
   *   The revision id.
   */
  protected function saveRevision(EntityInterface $entity) {
418
    $return = $entity->id();
419
    $default_langcode = $entity->getUntranslated()->language()->id;
420

421 422 423 424 425 426
    if (!$entity->isNewRevision()) {
      // Delete to handle removed values.
      $this->database->delete($this->revisionTable)
        ->condition($this->idKey, $entity->id())
        ->condition($this->revisionKey, $entity->getRevisionId())
        ->execute();
427 428
    }

429
    $languages = $this->dataTable ? $entity->getTranslationLanguages() : array($default_langcode => $entity->language());
430
    foreach ($languages as $langcode => $language) {
431
      $translation = $entity->getTranslation($langcode);
432 433 434 435 436 437 438 439 440 441
      $record = $this->mapToRevisionStorageRecord($translation);
      $record->langcode = $langcode;
      $record->default_langcode = $langcode == $default_langcode;

      // When saving a new revision, set any existing revision ID to NULL so as
      // to ensure that a new revision will actually be created.
      if ($entity->isNewRevision() && isset($record->{$this->revisionKey})) {
        $record->{$this->revisionKey} = NULL;
      }

442
      $entity->preSaveRevision($this, $record);
443

444 445 446 447 448 449 450 451 452
      if ($entity->isNewRevision()) {
        drupal_write_record($this->revisionTable, $record);
        if ($entity->isDefaultRevision()) {
          $this->database->update($this->entityInfo['base_table'])
            ->fields(array($this->revisionKey => $record->{$this->revisionKey}))
            ->condition($this->idKey, $record->{$this->idKey})
            ->execute();
        }
        $entity->setNewRevision(FALSE);
453
      }
454 455 456 457 458 459 460 461
      else {
        // @todo Use multiple insertions to improve performance.
        drupal_write_record($this->revisionTable, $record);
      }

      // Make sure to update the new revision key for the entity.
      $entity->{$this->revisionKey}->value = $record->{$this->revisionKey};
      $return = $record->{$this->revisionKey};
462
    }
463 464

    return $return;
465 466
  }

467 468 469 470 471 472 473 474
  /**
   * Stores the entity property language-aware data.
   *
   * @param \Drupal\Core\Entity\EntityInterface $entity
   *   The entity object.
   */
  protected function savePropertyData(EntityInterface $entity) {
    // Delete and insert to handle removed values.
475
    $this->database->delete($this->dataTable)
476 477 478
      ->condition($this->idKey, $entity->id())
      ->execute();

479
    $query = $this->database->insert($this->dataTable);
480 481 482 483 484 485 486 487 488 489 490 491

    foreach ($entity->getTranslationLanguages() as $langcode => $language) {
      $record = $this->mapToDataStorageRecord($entity, $langcode);
      $values = (array) $record;
      $query
        ->fields(array_keys($values))
        ->values($values);
    }

    $query->execute();
  }

492 493
  /**
   * Maps from an entity object to the storage record of the base table.
494 495 496 497 498 499
   *
   * @param \Drupal\Core\Entity\EntityInterface $entity
   *   The entity object.
   *
   * @return \stdClass
   *   The record to store.
500 501 502
   */
  protected function mapToStorageRecord(EntityInterface $entity) {
    $record = new \stdClass();
503
    foreach (drupal_schema_fields_sql($this->entityInfo['base_table']) as $name) {
504 505 506 507
      $record->$name = $entity->$name->value;
    }
    return $record;
  }
508 509 510

  /**
   * Maps from an entity object to the storage record of the revision table.
511 512 513 514 515 516
   *
   * @param \Drupal\Core\Entity\EntityInterface $entity
   *   The entity object.
   *
   * @return \stdClass
   *   The record to store.
517
   */
518
  protected function mapToRevisionStorageRecord(EntityInterface $entity) {
519
    $record = new \stdClass();
520
    $definitions = $entity->getPropertyDefinitions();
521
    foreach (drupal_schema_fields_sql($this->entityInfo['revision_table']) as $name) {
522
      if (isset($definitions[$name]) && isset($entity->$name->value)) {
523 524
        $record->$name = $entity->$name->value;
      }
525 526 527
    }
    return $record;
  }
528 529 530 531 532 533 534 535 536 537 538 539 540

  /**
   * Maps from an entity object to the storage record of the data table.
   *
   * @param \Drupal\Core\Entity\EntityInterface $entity
   *   The entity object.
   * @param $langcode
   *   The language code of the translation to get.
   *
   * @return \stdClass
   *   The record to store.
   */
  protected function mapToDataStorageRecord(EntityInterface $entity, $langcode) {
541
    $default_langcode = $entity->getUntranslated()->language()->id;
542 543
    // Don't use strict mode, this way there's no need to do checks here, as
    // non-translatable properties are replicated for each language.
544
    $translation = $entity->getTranslation($langcode);
545 546
    $definitions = $translation->getPropertyDefinitions();
    $schema = drupal_get_schema($this->entityInfo['data_table']);
547 548

    $record = new \stdClass();
549
    foreach (drupal_schema_fields_sql($this->entityInfo['data_table']) as $name) {
550 551 552
      $info = $schema['fields'][$name];
      $value = isset($definitions[$name]) && isset($translation->$name->value) ? $translation->$name->value : NULL;
      $record->$name = drupal_schema_get_field_value($info, $value);
553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568
    }
    $record->langcode = $langcode;
    $record->default_langcode = intval($default_langcode == $langcode);

    return $record;
  }

  /**
   * Overwrites \Drupal\Core\Entity\DatabaseStorageController::delete().
   */
  public function delete(array $entities) {
    if (!$entities) {
      // If no IDs or invalid IDs were passed, do nothing.
      return;
    }

569
    $transaction = $this->database->startTransaction();
570
    try {
571 572 573
      $entity_class = $this->entityClass;
      $entity_class::preDelete($this, $entities);

574 575
      // Ensure we are dealing with the actual entities.
      foreach ($entities as $id => $entity) {
576
        $entities[$id] = $entity->getNGEntity();
577 578
      }

579 580 581 582 583
      foreach ($entities as $id => $entity) {
        $this->invokeHook('predelete', $entity);
      }
      $ids = array_keys($entities);

584
      $this->database->delete($this->entityInfo['base_table'])
585 586 587 588
        ->condition($this->idKey, $ids)
        ->execute();

      if ($this->revisionKey) {
589
        $this->database->delete($this->revisionTable)
590 591 592 593 594
          ->condition($this->idKey, $ids)
          ->execute();
      }

      if ($this->dataTable) {
595
        $this->database->delete($this->dataTable)
596 597 598 599 600 601 602
          ->condition($this->idKey, $ids)
          ->execute();
      }

      // Reset the cache as soon as the changes have been applied.
      $this->resetCache($ids);

603
      $entity_class::postDelete($this, $entities);
604
      foreach ($entities as $id => $entity) {
605
        $this->invokeFieldMethod('delete', $entity);
606 607 608 609 610
        $this->invokeHook('delete', $entity);
      }
      // Ignore slave server temporarily.
      db_ignore_slave();
    }
611
    catch (\Exception $e) {
612 613
      $transaction->rollback();
      watchdog_exception($this->entityType, $e);
614
      throw new EntityStorageException($e->getMessage(), $e->getCode(), $e);
615 616
    }
  }
617
}