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

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

namespace Drupal\Core\Entity;

use PDO;

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

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

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

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

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

51 52 53 54 55
  /**
   * Overrides DatabaseStorageController::__construct().
   */
  public function __construct($entityType) {
    parent::__construct($entityType);
56 57
    $this->bundleKey = !empty($this->entityInfo['entity_keys']['bundle']) ? $this->entityInfo['entity_keys']['bundle'] : FALSE;
    $this->entityClass = $this->entityInfo['class'];
58

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

64 65 66 67
    // 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.
68
    unset($this->entityInfo['class']);
69 70 71 72 73 74 75 76 77 78
  }

  /**
   * 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'
79
   *   field one can pass:
80 81 82 83 84 85 86 87
   *   @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
88 89
   *   setting its value by a string, it's also possible to just pass the name
   *   string:
90 91 92 93
   *   @code
   *     $values = array('name' => 'the name');
   *   @endcode
   *
94
   * @return \Drupal\Core\Entity\EntityInterface
95 96 97
   *   A new entity object.
   */
  public function create(array $values) {
98
    // We have to determine the bundle first.
99 100
    // @todo Throw an exception if no bundle is passed and we have a bundle key
    //   defined.
101 102
    $bundle = $this->bundleKey ? $values[$this->bundleKey] : FALSE;
    $entity = new $this->entityClass(array(), $this->entityType, $bundle);
103 104 105 106 107 108 109

    // Set all other given values.
    foreach ($values as $name => $value) {
      $entity->$name = $value;
    }

    // Assign a new UUID if there is none yet.
110
    if ($this->uuidKey && !isset($entity->{$this->uuidKey}->value)) {
111 112 113
      $uuid = new Uuid();
      $entity->{$this->uuidKey}->value = $uuid->generate();
    }
114 115 116 117 118

    // 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);

119 120 121
    return $entity;
  }

122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149
  /**
   * 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);
  }

150 151 152 153 154 155
  /**
   * Overrides DatabaseStorageController::attachLoad().
   *
   * Added mapping from storage records to entities.
   */
  protected function attachLoad(&$queried_entities, $load_revision = FALSE) {
156
    // Map the loaded stdclass records into entity objects and according fields.
157
    $queried_entities = $this->mapFromStorageRecords($queried_entities, $load_revision);
158

159
    // Activate backward-compatibility mode to attach fields.
160
    if ($this->entityInfo['fieldable']) {
161
      // Prepare BC compatible entities before passing them to the field API.
162 163 164 165 166
      $bc_entities = array();
      foreach ($queried_entities as $key => $entity) {
        $bc_entities[$key] = $entity->getBCEntity();
      }

167
      if ($load_revision) {
168
        field_attach_load_revision($this->entityType, $bc_entities);
169 170
      }
      else {
171
        field_attach_load($this->entityType, $bc_entities);
172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191
      }
    }

    // Call hook_entity_load().
    foreach (module_implements('entity_load') as $module) {
      $function = $module . '_entity_load';
      $function($queried_entities, $this->entityType);
    }
    // Call hook_TYPE_load(). The first argument for hook_TYPE_load() are
    // always the queried entities, followed by additional arguments set in
    // $this->hookLoadArguments.
    $args = array_merge(array($queried_entities), $this->hookLoadArguments);
    foreach (module_implements($this->entityType . '_load') as $module) {
      call_user_func_array($module . '_' . $this->entityType . '_load', $args);
    }
  }

  /**
   * Maps from storage records to entity objects.
   *
192 193 194 195 196
   * @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.
   *
197 198 199
   * @return array
   *   An array of entity objects implementing the EntityInterface.
   */
200
  protected function mapFromStorageRecords(array $records, $load_revision = FALSE) {
201
    $entities = array();
202
    foreach ($records as $id => $record) {
203
      $values = array();
204
      foreach ($record as $name => $value) {
205 206 207
        // 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.
208
        $values[$name][LANGUAGE_DEFAULT] = $value;
209
      }
210 211
      $bundle = $this->bundleKey ? $record->{$this->bundleKey} : FALSE;
      // Turn the record into an entity class.
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
      $entities[$id] = new $this->entityClass($values, $this->entityType, $bundle);
    }
    $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.
   * @param boolean $load_revision
   *   (optional) TRUE if the revision should be loaded, defaults to FALSE.
   */
  protected function attachPropertyData(array &$entities, $load_revision = FALSE) {
    if ($this->dataTable) {
      $query = db_select($this->dataTable, 'data', array('fetch' => PDO::FETCH_ASSOC))
        ->fields('data')
        ->condition($this->idKey, array_keys($entities))
        ->orderBy('data.' . $this->idKey);
      if ($load_revision) {
        // Get revision ID's.
        $revision_ids = array();
        foreach ($entities as $id => $entity) {
          $revision_ids[] = $entity->get($this->revisionKey)->value;
        }
        $query->condition($this->revisionKey, $revision_ids);
      }
      $data = $query->execute();

      // Fetch the field definitions to check which field is translatable.
      $field_definition = $this->getFieldDefinitions(array());
      $data_fields = array_flip($this->entityInfo['schema_fields_sql']['data_table']);

      foreach ($data as $values) {
        $id = $values[$this->idKey];
        // Field values in default language are stored with LANGUAGE_DEFAULT as
        // key.
        $langcode = empty($values['default_langcode']) ? $values['langcode'] : LANGUAGE_DEFAULT;
        $translation = $entities[$id]->getTranslation($langcode);

        foreach ($field_definition as $name => $definition) {
          // Set translatable properties only.
          if (isset($data_fields[$name]) && !empty($definition['translatable'])) {
256 257 258 259
            // @todo Figure out how to determine which property has to be set.
            // Currently it's guessing, and guessing is evil!
            $property_definition = $translation->{$name}->getPropertyDefinitions();
            $translation->{$name}->{key($property_definition)} = $values[$name];
260 261 262 263 264 265 266
          }
          // Avoid initializing configurable fields before loading them.
          elseif (!empty($definition['configurable'])) {
            unset($entities[$id]->fields[$name]);
          }
        }
      }
267 268 269 270 271 272 273 274 275 276 277
    }
  }

  /**
   * Overrides DatabaseStorageController::save().
   *
   * Added mapping from entities to storage records before saving.
   */
  public function save(EntityInterface $entity) {
    $transaction = db_transaction();
    try {
278 279 280 281 282 283
      // Ensure we are dealing with the actual entity.
      $entity = $entity->getOriginalEntity();

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

284 285 286 287 288 289 290 291 292
      // Load the stored entity, if any.
      if (!$entity->isNew() && !isset($entity->original)) {
        $entity->original = entity_load_unchanged($this->entityType, $entity->id());
      }

      $this->preSave($entity);
      $this->invokeHook('presave', $entity);

      // Create the storage record to be saved.
293
      $record = $this->mapToStorageRecord($entity);
294 295

      if (!$entity->isNew()) {
296 297 298 299 300 301 302 303 304 305 306
        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);
        }
307 308 309
        if ($this->dataTable) {
          $this->savePropertyData($entity);
        }
310 311 312 313 314
        $this->resetCache(array($entity->id()));
        $this->postSave($entity, TRUE);
        $this->invokeHook('update', $entity);
      }
      else {
315
        $return = drupal_write_record($this->entityInfo['base_table'], $record);
316
        $entity->{$this->idKey}->value = $record->{$this->idKey};
317 318 319
        if ($this->revisionKey) {
          $record->{$this->revisionKey} = $this->saveRevision($entity);
        }
320 321 322 323 324
        $entity->{$this->idKey}->value = $record->{$this->idKey};
        if ($this->dataTable) {
          $this->savePropertyData($entity);
        }

325 326 327 328 329 330 331 332 333 334 335 336 337 338
        // Reset general caches, but keep caches specific to certain entities.
        $this->resetCache(array());

        $entity->enforceIsNew(FALSE);
        $this->postSave($entity, FALSE);
        $this->invokeHook('insert', $entity);
      }

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

      return $return;
    }
339
    catch (\Exception $e) {
340 341 342 343 344 345
      $transaction->rollback();
      watchdog_exception($this->entityType, $e);
      throw new EntityStorageException($e->getMessage(), $e->getCode(), $e);
    }
  }

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 378 379 380 381 382 383
  /**
   * Saves an entity revision.
   *
   * @param \Drupal\Core\Entity\EntityInterface $entity
   *   The entity object.
   *
   * @return integer
   *   The revision id.
   */
  protected function saveRevision(EntityInterface $entity) {
    $record = $this->mapToRevisionStorageRecord($entity);

    // 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;
    }

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

    if ($entity->isNewRevision()) {
      drupal_write_record($this->revisionTable, $record);
      if ($entity->isDefaultRevision()) {
        db_update($this->entityInfo['base_table'])
          ->fields(array($this->revisionKey => $record->{$this->revisionKey}))
          ->condition($this->idKey, $record->{$this->idKey})
          ->execute();
      }
      $entity->setNewRevision(FALSE);
    }
    else {
      drupal_write_record($this->revisionTable, $record, $this->revisionKey);
    }
    // Make sure to update the new revision key for the entity.
    $entity->{$this->revisionKey}->value = $record->{$this->revisionKey};
    return $record->{$this->revisionKey};
  }

384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408
  /**
   * 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.
    db_delete($this->dataTable)
      ->condition($this->idKey, $entity->id())
      ->execute();

    $query = db_insert($this->dataTable);

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

    $query->execute();
  }

409 410 411
  /**
   * Overrides DatabaseStorageController::invokeHook().
   *
412
   * Invokes field API attachers with a BC entity.
413 414
   */
  protected function invokeHook($hook, EntityInterface $entity) {
415 416 417 418 419 420 421
    $function = 'field_attach_' . $hook;
    // @todo: field_attach_delete_revision() is named the wrong way round,
    // consider renaming it.
    if ($function == 'field_attach_revision_delete') {
      $function = 'field_attach_delete_revision';
    }
    if (!empty($this->entityInfo['fieldable']) && function_exists($function)) {
422
      $function($entity->getBCEntity());
423 424 425 426 427 428 429 430 431 432
    }

    // Invoke the hook.
    module_invoke_all($this->entityType . '_' . $hook, $entity);
    // Invoke the respective entity-level hook.
    module_invoke_all('entity_' . $hook, $entity, $this->entityType);
  }

  /**
   * Maps from an entity object to the storage record of the base table.
433 434 435 436 437 438
   *
   * @param \Drupal\Core\Entity\EntityInterface $entity
   *   The entity object.
   *
   * @return \stdClass
   *   The record to store.
439 440 441
   */
  protected function mapToStorageRecord(EntityInterface $entity) {
    $record = new \stdClass();
442
    foreach ($this->entityInfo['schema_fields_sql']['base_table'] as $name) {
443 444 445 446
      $record->$name = $entity->$name->value;
    }
    return $record;
  }
447 448 449

  /**
   * Maps from an entity object to the storage record of the revision table.
450 451 452 453 454 455
   *
   * @param \Drupal\Core\Entity\EntityInterface $entity
   *   The entity object.
   *
   * @return \stdClass
   *   The record to store.
456 457 458 459
   */
  protected function mapToRevisionStorageRecord(EntityInterface $entity) {
    $record = new \stdClass();
    foreach ($this->entityInfo['schema_fields_sql']['revision_table'] as $name) {
460 461 462
      if (isset($entity->$name->value)) {
        $record->$name = $entity->$name->value;
      }
463 464 465
    }
    return $record;
  }
466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504

  /**
   * 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) {
    $default_langcode = $entity->language()->langcode;
    // Don't use strict mode, this way there's no need to do checks here, as
    // non-translatable properties are replicated for each language.
    $translation = $entity->getTranslation($langcode, FALSE);

    $record = new \stdClass();
    foreach ($this->entityInfo['schema_fields_sql']['data_table'] as $name) {
      $record->$name = $translation->$name->value;
    }
    $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;
    }

    $transaction = db_transaction();
    try {
505 506 507 508 509
      // Ensure we are dealing with the actual entities.
      foreach ($entities as $id => $entity) {
        $entities[$id] = $entity->getOriginalEntity();
      }

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
      $this->preDelete($entities);
      foreach ($entities as $id => $entity) {
        $this->invokeHook('predelete', $entity);
      }
      $ids = array_keys($entities);

      db_delete($this->entityInfo['base_table'])
        ->condition($this->idKey, $ids)
        ->execute();

      if ($this->revisionKey) {
        db_delete($this->revisionTable)
          ->condition($this->idKey, $ids)
          ->execute();
      }

      if ($this->dataTable) {
        db_delete($this->dataTable)
          ->condition($this->idKey, $ids)
          ->execute();
      }

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

      $this->postDelete($entities);
      foreach ($entities as $id => $entity) {
        $this->invokeHook('delete', $entity);
      }
      // Ignore slave server temporarily.
      db_ignore_slave();
    }
    catch (Exception $e) {
      $transaction->rollback();
      watchdog_exception($this->entityType, $e);
      throw new EntityStorageException($e->getMessage, $e->getCode, $e);
    }
  }
548
}