DatabaseStorageControllerNG.php 10.1 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
<?php

/**
 * @file
 * Definition of Drupal\Core\Entity\DatabaseStorageControllerNG.
 */

namespace Drupal\Core\Entity;

use PDO;

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.
 */
class DatabaseStorageControllerNG extends DatabaseStorageController {

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

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

  /**
   * Overrides DatabaseStorageController::__construct().
   */
  public function __construct($entityType) {
    parent::__construct($entityType);
44 45
    $this->bundleKey = !empty($this->entityInfo['entity_keys']['bundle']) ? $this->entityInfo['entity_keys']['bundle'] : FALSE;
    $this->entityClass = $this->entityInfo['class'];
46 47 48 49 50

    // 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.
51
    unset($this->entityInfo['class']);
52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79
  }

  /**
   * 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'
   *   property one can pass:
   *   @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
   *   setting by string value, it's also possible to just pass the name string:
   *   @code
   *     $values = array('name' => 'the name');
   *   @endcode
   *
   * @return Drupal\Core\Entity\EntityInterface
   *   A new entity object.
   */
  public function create(array $values) {
80 81 82
    // We have to determine the bundle first.
    $bundle = $this->bundleKey ? $values[$this->bundleKey] : FALSE;
    $entity = new $this->entityClass(array(), $this->entityType, $bundle);
83 84 85 86 87 88 89

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

    // Assign a new UUID if there is none yet.
90
    if ($this->uuidKey && !isset($entity->{$this->uuidKey}->value)) {
91 92 93 94 95 96 97 98 99 100 101 102 103 104
      $uuid = new Uuid();
      $entity->{$this->uuidKey}->value = $uuid->generate();
    }
    return $entity;
  }

  /**
   * Overrides DatabaseStorageController::attachLoad().
   *
   * Added mapping from storage records to entities.
   */
  protected function attachLoad(&$queried_entities, $load_revision = FALSE) {
    // Now map the record values to the according entity properties and
    // activate compatibility mode.
105
    $queried_entities = $this->mapFromStorageRecords($queried_entities, $load_revision);
106 107 108

    // Attach fields.
    if ($this->entityInfo['fieldable']) {
109 110 111 112 113 114
      // Prepare BC compatible entities for field API.
      $bc_entities = array();
      foreach ($queried_entities as $key => $entity) {
        $bc_entities[$key] = $entity->getBCEntity();
      }

115
      if ($load_revision) {
116
        field_attach_load_revision($this->entityType, $bc_entities);
117 118
      }
      else {
119
        field_attach_load($this->entityType, $bc_entities);
120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139
      }
    }

    // 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.
   *
140 141 142 143 144
   * @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.
   *
145 146 147
   * @return array
   *   An array of entity objects implementing the EntityInterface.
   */
148
  protected function mapFromStorageRecords(array $records, $load_revision = FALSE) {
149 150

    foreach ($records as $id => $record) {
151
      $values = array();
152
      foreach ($record as $name => $value) {
153 154
        // Avoid unnecessary array hierarchies to save memory.
        $values[$name][LANGUAGE_DEFAULT] = $value;
155
      }
156 157 158
      $bundle = $this->bundleKey ? $record->{$this->bundleKey} : FALSE;
      // Turn the record into an entity class.
      $records[$id] = new $this->entityClass($values, $this->entityType, $bundle);
159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182
    }
    return $records;
  }

  /**
   * Overrides DatabaseStorageController::save().
   *
   * Added mapping from entities to storage records before saving.
   */
  public function save(EntityInterface $entity) {
    $transaction = db_transaction();
    try {
      // 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.
      $record = $this->maptoStorageRecord($entity);

      if (!$entity->isNew()) {
183 184 185 186 187 188 189 190 191 192 193
        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);
        }
194 195 196 197 198
        $this->resetCache(array($entity->id()));
        $this->postSave($entity, TRUE);
        $this->invokeHook('update', $entity);
      }
      else {
199
        $return = drupal_write_record($this->entityInfo['base_table'], $record);
200 201 202 203
        if ($this->revisionKey) {
          $entity->{$this->idKey}->value = $record->{$this->idKey};
          $record->{$this->revisionKey} = $this->saveRevision($entity);
        }
204 205 206 207 208 209 210 211
        // Reset general caches, but keep caches specific to certain entities.
        $this->resetCache(array());

        $entity->{$this->idKey}->value = $record->{$this->idKey};
        $entity->enforceIsNew(FALSE);
        $this->postSave($entity, FALSE);
        $this->invokeHook('insert', $entity);
      }
212
      $entity->updateOriginalValues();
213 214 215 216 217 218 219 220 221 222 223 224 225 226

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

      return $return;
    }
    catch (Exception $e) {
      $transaction->rollback();
      watchdog_exception($this->entityType, $e);
      throw new EntityStorageException($e->getMessage(), $e->getCode(), $e);
    }
  }

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

265 266 267
  /**
   * Overrides DatabaseStorageController::invokeHook().
   *
268
   * Invokes field API attachers with a BC entity.
269 270
   */
  protected function invokeHook($hook, EntityInterface $entity) {
271 272 273 274 275 276 277
    $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)) {
278
      $function($entity->getBCEntity());
279 280 281 282 283 284 285 286 287 288 289 290 291
    }

    // 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.
   */
  protected function mapToStorageRecord(EntityInterface $entity) {
    $record = new \stdClass();
292
    foreach ($this->entityInfo['schema_fields_sql']['base_table'] as $name) {
293 294 295 296
      $record->$name = $entity->$name->value;
    }
    return $record;
  }
297 298 299 300 301 302 303 304 305 306 307

  /**
   * Maps from an entity object to the storage record of the revision table.
   */
  protected function mapToRevisionStorageRecord(EntityInterface $entity) {
    $record = new \stdClass();
    foreach ($this->entityInfo['schema_fields_sql']['revision_table'] as $name) {
      $record->$name = $entity->$name->value;
    }
    return $record;
  }
308
}