Field.php 22.1 KB
Newer Older
1 2 3 4
<?php

/**
 * @file
5
 * Contains \Drupal\field\Entity\Field.
6 7
 */

8
namespace Drupal\field\Entity;
9

10
use Drupal\Core\Entity\Annotation\EntityType;
11 12 13
use Drupal\Core\Annotation\Translation;
use Drupal\Core\Config\Entity\ConfigEntityBase;
use Drupal\field\FieldException;
14
use Drupal\field\FieldInterface;
15 16 17 18 19 20 21

/**
 * Defines the Field entity.
 *
 * @todo use 'field' as the id once hook_field_load() and friends
 * are removed.
 *
22
 * @EntityType(
23 24 25
 *   id = "field_entity",
 *   label = @Translation("Field"),
 *   module = "field",
26
 *   controllers = {
27
 *     "storage" = "Drupal\field\FieldStorageController"
28
 *   },
29 30 31 32 33 34 35 36
 *   config_prefix = "field.field",
 *   entity_keys = {
 *     "id" = "id",
 *     "label" = "id",
 *     "uuid" = "uuid"
 *   }
 * )
 */
37
class Field extends ConfigEntityBase implements FieldInterface {
38 39 40 41 42 43 44 45 46 47 48 49 50 51 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 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94

  /**
   * The maximum length of the field ID (machine name), in characters.
   *
   * For fields created through Field UI, this includes the 'field_' prefix.
   */
  const ID_MAX_LENGTH = 32;

  /**
   * The field ID (machine name).
   *
   * This is the name of the property under which the field values are placed in
   * an entity : $entity-{>$field_id}. The maximum length is
   * Field:ID_MAX_LENGTH.
   *
   * Example: body, field_main_image.
   *
   * @var string
   */
  public $id;

  /**
   * The field UUID.
   *
   * This is assigned automatically when the field is created.
   *
   * @var string
   */
  public $uuid;

  /**
   * The field type.
   *
   * Example: text, number_integer.
   *
   * @var string
   */
  public $type;

  /**
   * The name of the module that provides the field type.
   *
   * @var string
   */
  public $module;

  /**
   * Flag indicating whether the field type module is enabled.
   *
   * @var bool
   */
  public $active;

  /**
   * Field-type specific settings.
   *
   * An array of key/value pairs, The keys and default values are defined by the
95
   * field type.
96 97 98
   *
   * @var array
   */
99
  public $settings = array();
100 101 102 103 104 105 106 107 108

  /**
   * The field cardinality.
   *
   * The maximum number of values the field can hold. Possible values are
   * positive integers or FIELD_CARDINALITY_UNLIMITED. Defaults to 1.
   *
   * @var integer
   */
109
  public $cardinality = 1;
110 111 112 113 114 115 116 117

  /**
   * Flag indicating whether the field is translatable.
   *
   * Defaults to FALSE.
   *
   * @var bool
   */
118
  public $translatable = FALSE;
119 120 121 122 123 124 125 126 127

  /**
   * The entity types on which the field is allowed to have instances.
   *
   * If empty or not specified, the field is allowed to have instances in any
   * entity type.
   *
   * @var array
   */
128
  public $entity_types = array();
129 130 131 132 133 134 135 136 137 138 139 140 141

  /**
   * Flag indicating whether the field is available for editing.
   *
   * If TRUE, some actions not available though the UI (but are still possible
   * through direct API manipulation):
   * - field settings cannot be changed,
   * - new instances cannot be created
   * - existing instances cannot be deleted.
   * Defaults to FALSE.
   *
   * @var bool
   */
142
  public $locked = FALSE;
143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160

  /**
   * The field storage definition.
   *
   * An array of key/value pairs identifying the storage backend to use for the
   * field:
   * - type: (string) The storage backend used by the field. Storage backends
   *   are defined by modules that implement hook_field_storage_info().
   * - settings: (array) A sub-array of key/value pairs of settings. The keys
   *   and default values are defined by the storage backend in the 'settings'
   *   entry of hook_field_storage_info().
   * - module: (string, read-only) The name of the module that implements the
   *   storage backend.
   * - active: (integer, read-only) TRUE if the module that implements the
   *   storage backend is currently enabled, FALSE otherwise.
   *
   * @var array
   */
161
  public $storage = array();
162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178

  /**
   * The custom storage indexes for the field data storage.
   *
   * This set of indexes is merged with the "default" indexes specified by the
   * field type in hook_field_schema() to determine the actual set of indexes
   * that get created.
   *
   * The indexes are defined using the same definition format as Schema API
   * index specifications. Only columns that are part of the field schema, as
   * defined by the field type in hook_field_schema(), are allowed.
   *
   * Some storage backends might not support indexes, and discard that
   * information.
   *
   * @var array
   */
179
  public $indexes = array();
180 181 182 183 184 185 186 187 188 189 190 191 192 193

  /**
   * Flag indicating whether the field is deleted.
   *
   * The delete() method marks the field as "deleted" and removes the
   * corresponding entry from the config storage, but keeps its definition in
   * the state storage while field data is purged by a separate
   * garbage-collection process.
   *
   * Deleted fields stay out of the regular entity lifecycle (notably, their
   * values are not populated in loaded entities, and are not saved back).
   *
   * @var bool
   */
194
  public $deleted = FALSE;
195 196 197 198 199 200 201 202 203 204 205 206 207 208 209

  /**
   * The field schema.
   *
   * @var array
   */
  protected $schema;

  /**
   * The storage information for the field.
   *
   * @var array
   */
  protected $storageDetails;

210 211 212
  /**
   * The original field.
   *
213
   * @var \Drupal\field\Entity\Field
214 215 216
   */
  public $original = NULL;

217
  /**
218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235
   * Constructs a Field object.
   *
   * @param array $values
   *   An array of field properties, keyed by property name. Most array
   *   elements will be used to set the corresponding properties on the class;
   *   see the class property documentation for details. Some array elements
   *   have special meanings and a few are required. Special elements are:
   *   - id: required. As a temporary Backwards Compatibility layer right now,
   *     a 'field_name' property can be accepted in place of 'id'.
   *   - type: required.
   *
   * In most cases, Field entities are created via
   * entity_create('field_entity', $values)), where $values is the same
   * parameter as in this constructor.
   *
   * @see entity_create()
   *
   * @ingroup field_crud
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
   */
  public function __construct(array $values, $entity_type = 'field_entity') {
    // Check required properties.
    if (empty($values['type'])) {
      throw new FieldException('Attempt to create a field with no type.');
    }
    // Temporary BC layer: accept both 'id' and 'field_name'.
    // @todo $field_name and the handling for it will be removed in
    //   http://drupal.org/node/1953408.
    if (empty($values['field_name']) && empty($values['id'])) {
      throw new FieldException('Attempt to create an unnamed field.');
    }
    if (empty($values['id'])) {
      $values['id'] = $values['field_name'];
      unset($values['field_name']);
    }
    if (!preg_match('/^[_a-z]+[_a-z0-9]*$/', $values['id'])) {
      throw new FieldException('Attempt to create a field with invalid characters. Only lowercase alphanumeric characters and underscores are allowed, and only lowercase letters and underscore are allowed as the first character');
    }

    parent::__construct($values, $entity_type);
  }

  /**
   * {@inheritdoc}
   */
  public function getExportProperties() {
    $names = array(
      'id',
      'uuid',
      'status',
      'langcode',
      'type',
      'settings',
      'module',
      'active',
      'entity_types',
      'storage',
      'locked',
      'cardinality',
      'translatable',
      'indexes',
    );
    $properties = array();
    foreach ($names as $name) {
      $properties[$name] = $this->get($name);
    }
    return $properties;
  }

  /**
287 288 289 290 291 292 293 294 295
   * Overrides \Drupal\Core\Entity\Entity::save().
   *
   * @return int
   *   Either SAVED_NEW or SAVED_UPDATED, depending on the operation performed.
   *
   * @throws \Drupal\field\FieldException
   *   If the field definition is invalid.
   * @throws \Drupal\Core\Entity\EntityStorageException
   *   In case of failures at the configuration storage level.
296 297 298 299 300 301
   */
  public function save() {
    // Clear the derived data about the field.
    unset($this->schema, $this->storageDetails);

    if ($this->isNew()) {
302 303 304 305 306 307
      return $this->saveNew();
    }
    else {
      return $this->saveUpdated();
    }
  }
308

309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335
  /**
   * Saves a new field definition.
   *
   * @return int
   *   SAVED_NEW if the definition was saved.
   *
   * @throws \Drupal\field\FieldException
   *   If the field definition is invalid.
   * @throws \Drupal\Core\Entity\EntityStorageException
   *   In case of failures at the configuration storage level.
   */
  protected function saveNew() {
    $module_handler = \Drupal::moduleHandler();
    $entity_manager = \Drupal::entityManager();
    $storage_controller = $entity_manager->getStorageController($this->entityType);

    // Field name cannot be longer than Field::ID_MAX_LENGTH characters. We
    // use drupal_strlen() because the DB layer assumes that column widths
    // are given in characters rather than bytes.
    if (drupal_strlen($this->id) > static::ID_MAX_LENGTH) {
      throw new FieldException(format_string(
        'Attempt to create a field with an ID longer than @max characters: %id', array(
          '@max' => static::ID_MAX_LENGTH,
          '%id' => $this->id,
        )
      ));
    }
336

337
    // Ensure the field name is unique (we do not care about deleted fields).
338
    if ($prior_field = $storage_controller->load($this->id)) {
339 340 341 342 343
      $message = $prior_field->active ?
        'Attempt to create field name %id which already exists and is active.' :
        'Attempt to create field name %id which already exists, although it is inactive.';
      throw new FieldException(format_string($message, array('%id' => $this->id)));
    }
344

345 346 347 348 349 350
    // Disallow reserved field names. This can't prevent all field name
    // collisions with existing entity properties, but some is better than
    // none.
    foreach ($entity_manager->getDefinitions() as $type => $info) {
      if (in_array($this->id, $info['entity_keys'])) {
        throw new FieldException(format_string('Attempt to create field %id which is reserved by entity type %type.', array('%id' => $this->id, '%type' => $type)));
351
      }
352 353 354
    }

    // Check that the field type is known.
355
    $field_type = \Drupal::service('plugin.manager.entity.field.field_type')->getDefinition($this->type);
356 357 358
    if (!$field_type) {
      throw new FieldException(format_string('Attempt to create a field of unknown type %type.', array('%type' => $this->type)));
    }
359
    $this->module = $field_type['provider'];
360
    $this->active = TRUE;
361

362 363 364
    // Make sure all settings are present, so that a complete field
    // definition is passed to the various hooks and written to config.
    $this->settings += $field_type['settings'];
365

366 367 368 369 370 371 372 373 374
    // Provide default storage.
    $this->storage += array(
      'type' => variable_get('field_storage_default', 'field_sql_storage'),
      'settings' => array(),
    );
    // Check that the storage type is known.
    $storage_type = field_info_storage_types($this->storage['type']);
    if (!$storage_type) {
      throw new FieldException(format_string('Attempt to create a field with unknown storage type %type.', array('%type' => $this->storage['type'])));
375
    }
376 377 378 379
    $this->storage['module'] = $storage_type['module'];
    $this->storage['active'] = TRUE;
    // Provide default storage settings.
    $this->storage['settings'] += $storage_type['settings'];
380

381 382
    // Invoke the storage backend's hook_field_storage_create_field().
    $module_handler->invoke($this->storage['module'], 'field_storage_create_field', array($this));
383

384 385 386
    // Save the configuration.
    $result = parent::save();
    field_cache_clear();
387

388 389
    return $result;
  }
390

391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406
  /**
   * Saves an updated field definition.
   *
   * @return int
   *   SAVED_UPDATED if the definition was saved.
   *
   * @throws \Drupal\field\FieldException
   *   If the field definition is invalid.
   * @throws \Drupal\Core\Entity\EntityStorageException
   *   In case of failures at the configuration storage level.
   */
  protected function saveUpdated() {
    $module_handler = \Drupal::moduleHandler();
    $storage_controller = \Drupal::entityManager()->getStorageController($this->entityType);

    $original = $storage_controller->loadUnchanged($this->id());
407
    $this->original = $original;
408

409 410 411 412 413 414
    // Some updates are always disallowed.
    if ($this->type != $original->type) {
      throw new FieldException("Cannot change an existing field's type.");
    }
    if ($this->entity_types != $original->entity_types) {
      throw new FieldException("Cannot change an existing field's entity_types property.");
415
    }
416 417 418 419 420 421 422 423 424 425 426
    if ($this->storage['type'] != $original->storage['type']) {
      throw new FieldException("Cannot change an existing field's storage type.");
    }

    // Make sure all settings are present, so that a complete field definition
    // is saved. This allows calling code to perform partial updates on field
    // objects.
    $this->settings += $original->settings;

    // See if any module forbids the update by throwing an exception. This
    // invokes hook_field_update_forbid().
427
    $module_handler->invokeAll('field_update_forbid', array($this, $original));
428 429 430 431 432

    // Tell the storage engine to update the field by invoking the
    // hook_field_storage_update_field(). The storage engine can reject the
    // definition update as invalid by raising an exception, which stops
    // execution before the definition is written to config.
433
    $module_handler->invoke($this->storage['module'], 'field_storage_update_field', array($this, $original));
434 435 436 437 438 439 440 441 442 443 444 445 446 447

    // Save the configuration.
    $result = parent::save();
    field_cache_clear();

    return $result;
  }

  /**
   * {@inheritdoc}
   */
  public function delete() {
    if (!$this->deleted) {
      $module_handler = \Drupal::moduleHandler();
448
      $instance_controller = \Drupal::entityManager()->getStorageController('field_instance');
449 450 451 452 453 454 455 456 457
      $state = \Drupal::state();

      // Delete all non-deleted instances.
      $instance_ids = array();
      foreach ($this->getBundles() as $entity_type => $bundles) {
        foreach ($bundles as $bundle) {
          $instance_ids[] = "$entity_type.$bundle.$this->id";
        }
      }
458
      foreach ($instance_controller->loadMultiple($instance_ids) as $instance) {
459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487
        // By default, FieldInstance::delete() will automatically try to delete
        // a field definition when it is deleting the last instance of the
        // field. Since the whole field is being deleted here, pass FALSE as
        // the $field_cleanup parameter to prevent a loop.
        $instance->delete(FALSE);
      }

      // Mark field data for deletion by invoking
      // hook_field_storage_delete_field().
      $module_handler->invoke($this->storage['module'], 'field_storage_delete_field', array($this));

      // Delete the configuration of this field and save the field configuration
      // in the key_value table so we can use it later during
      // field_purge_batch(). This makes sure a new field can be created
      // immediately with the same name.
      $deleted_fields = $state->get('field.field.deleted') ?: array();
      $config = $this->getExportProperties();
      $config['deleted'] = TRUE;
      $deleted_fields[$this->uuid] = $config;
      $state->set('field.field.deleted', $deleted_fields);

      parent::delete();

      // Clear the cache.
      field_cache_clear();
    }
  }

  /**
488
   * {@inheritdoc}
489 490 491
   */
  public function getSchema() {
    if (!isset($this->schema)) {
492 493 494 495 496 497
      // Get the schema from the field item class.
      $definition = \Drupal::service('plugin.manager.entity.field.field_type')->getDefinition($this->type);
      $class = $definition['class'];
      $schema = $class::schema($this);
      // Fill in default values for optional entries.
      $schema += array('indexes' => array(), 'foreign keys' => array());
498 499

      // Check that the schema does not include forbidden column names.
500
      if (array_intersect(array_keys($schema['columns']), static::getReservedColumns())) {
501 502 503 504 505 506 507 508 509 510 511 512 513
        throw new FieldException('Illegal field type columns.');
      }

      // Merge custom indexes with those specified by the field type. Custom
      // indexes prevail.
      $schema['indexes'] = $this->indexes + $schema['indexes'];

      $this->schema = $schema;
    }

    return $this->schema;
  }

514 515 516 517 518 519 520 521 522 523 524 525 526 527
  /**
   * {@inheritdoc}
   */
  public function getColumns() {
    $schema = $this->getSchema();
    // A typical use case for the method is to iterate on the columns, while
    // some other use cases rely on identifying the first column with the key()
    // function. Since the schema is persisted in the Field object, we take care
    // of resetting the array pointer so that the former does not interfere with
    // the latter.
    reset($schema['columns']);
    return $schema['columns'];
  }

528
  /**
529
   * {@inheritdoc}
530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547
   */
  public function getStorageDetails() {
    if (!isset($this->storageDetails)) {
      $module_handler = \Drupal::moduleHandler();

      // Collect the storage details from the storage backend, and let other
      // modules alter it. This invokes hook_field_storage_details() and
      // hook_field_storage_details_alter().
      $details = (array) $module_handler->invoke($this->storage['module'], 'field_storage_details', array($this));
      $module_handler->alter('field_storage_details', $details, $this);

      $this->storageDetails = $details;
    }

    return $this->storageDetails;
  }

  /**
548
   * {@inheritdoc}
549 550 551 552 553 554 555 556 557 558 559
   */
  public function getBundles() {
    if (empty($this->deleted)) {
      $map = field_info_field_map();
      if (isset($map[$this->id]['bundles'])) {
        return $map[$this->id]['bundles'];
      }
    }
    return array();
  }

560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581
  /**
   * {@inheritdoc}
   */
  public function getFieldName() {
    return $this->id;
  }

  /**
   * {@inheritdoc}
   */
  public function getFieldType() {
    return $this->type;
  }

  /**
   * {@inheritdoc}
   */
  public function getFieldSettings() {
    // @todo field_info_field_types() calls _field_info_collate_types() which
    //   maintains its own static cache. However, do some CPU and memory
    //   profiling to see if it's worth statically caching $field_type_info, or
    //   the default field and instance settings, within $this.
582
    $field_type_info = \Drupal::service('plugin.manager.entity.field.field_type')->getDefinition($this->type);
583

584
    $settings = $this->settings + $field_type_info['settings'] + $field_type_info['instance_settings'];
585 586 587 588 589 590 591 592
    return $settings;
  }

  /**
   * {@inheritdoc}
   */
  public function getFieldSetting($setting_name) {
    // @todo See getFieldSettings() about potentially statically caching this.
593
    $field_type_info = \Drupal::service('plugin.manager.entity.field.field_type')->getDefinition($this->type);
594 595 596

    // We assume here that consecutive array_key_exists() is more efficient than
    // calling getFieldSettings() when all we need is a single setting.
597
    if (array_key_exists($setting_name, $this->settings)) {
598 599
      return $this->settings[$setting_name];
    }
600
    elseif (array_key_exists($setting_name, $field_type_info['settings'])) {
601 602
      return $field_type_info['settings'][$setting_name];
    }
603 604 605
    else {
      return $field_type_info['instance_settings'][$setting_name];
    }
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 650
  }

  /**
   * {@inheritdoc}
   */
  public function getFieldPropertyNames() {
    $schema = $this->getSchema();
    return array_keys($schema['columns']);
  }

  /**
   * {@inheritdoc}
   */
  public function isFieldTranslatable() {
    return $this->translatable;
  }

  /**
   * {@inheritdoc}
   */
  public function getFieldLabel() {
    return $this->label();
  }

  /**
   * {@inheritdoc}
   */
  public function getFieldDescription() {
    return '';
  }

  /**
   * {@inheritdoc}
   */
  public function getFieldCardinality() {
    return $this->cardinality;
  }

  /**
   * {@inheritdoc}
   */
  public function isFieldRequired() {
    return FALSE;
  }

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 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706
  /**
   * {@inheritdoc}
   */
  public function offsetExists($offset) {
    return isset($this->{$offset}) || in_array($offset, array('columns', 'foreign keys', 'bundles', 'storage_details'));
  }

  /**
   * {@inheritdoc}
   */
  public function &offsetGet($offset) {
    switch ($offset) {
      case 'id':
        return $this->uuid;

      case 'field_name':
        return $this->id;

      case 'columns':
        $this->getSchema();
        return $this->schema['columns'];

      case 'foreign keys':
        $this->getSchema();
        return $this->schema['foreign keys'];

      case 'bundles':
        $bundles = $this->getBundles();
        return $bundles;

      case 'storage_details':
        $this->getStorageDetails();
        return $this->storageDetails;
    }

    return $this->{$offset};
  }

  /**
   * {@inheritdoc}
   */
  public function offsetSet($offset, $value) {
    if (!in_array($offset, array('columns', 'foreign keys', 'bundles', 'storage_details'))) {
      $this->{$offset} = $value;
    }
  }

  /**
   * {@inheritdoc}
   */
  public function offsetUnset($offset) {
    if (!in_array($offset, array('columns', 'foreign keys', 'bundles', 'storage_details'))) {
      unset($this->{$offset});
    }
  }

707 708 709 710 711 712 713 714 715 716 717 718 719 720 721
  /**
   * {@inheritdoc}
   */
  public function serialize() {
    // Only store the definition, not external objects or derived data.
    return serialize($this->getExportProperties());
  }

  /**
   * {@inheritdoc}
   */
  public function unserialize($serialized) {
    $this->__construct(unserialize($serialized));
  }

722 723 724 725 726 727 728 729
  /**
   * A list of columns that can not be used as field type columns.
   *
   * @return array
   */
  public static function getReservedColumns() {
    return array('deleted');
  }
730

731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764
  /**
   * Determines whether a field has any data.
   *
   * @return
   *   TRUE if the field has data for any entity; FALSE otherwise.
   */
  public function hasData() {
    $storage_details = $this->getSchema();
    $columns = array_keys($storage_details['columns']);
    $factory = \Drupal::service('entity.query');
    foreach ($this->getBundles() as $entity_type => $bundle) {
      // Entity Query throws an exception if there is no base table.
      $entity_info = \Drupal::entityManager()->getDefinition($entity_type);
      if (!isset($entity_info['base_table'])) {
        continue;
      }
      $query = $factory->get($entity_type);
      $group = $query->orConditionGroup();
      foreach ($columns as $column) {
        $group->exists($this->id() . '.' . $column);
      }
      $result = $query
        ->condition($group)
        ->count()
        ->accessCheck(FALSE)
        ->range(0, 1)
        ->execute();
      if ($result) {
        return TRUE;
      }
    }

    return FALSE;
  }
765
}