3 namespace Drupal\field\Entity;
5 use Drupal\Component\Utility\Unicode;
6 use Drupal\Core\Config\Entity\ConfigEntityBase;
7 use Drupal\Core\Entity\EntityStorageInterface;
8 use Drupal\Core\Entity\FieldableEntityInterface;
9 use Drupal\Core\Entity\FieldableEntityStorageInterface;
10 use Drupal\Core\Field\FieldException;
11 use Drupal\Core\Field\FieldStorageDefinitionInterface;
12 use Drupal\Core\TypedData\OptionsProviderInterface;
13 use Drupal\field\FieldStorageConfigInterface;
16 * Defines the Field storage configuration entity.
19 * id = "field_storage_config",
20 * label = @Translation("Field storage"),
22 * "access" = "Drupal\field\FieldStorageConfigAccessControlHandler",
23 * "storage" = "Drupal\field\FieldStorageConfigStorage"
25 * config_prefix = "storage",
41 * "persist_with_no_fields",
46 class FieldStorageConfig extends ConfigEntityBase implements FieldStorageConfigInterface {
49 * The maximum length of the field name, in characters.
51 * For fields created through Field UI, this includes the 'field_' prefix.
53 const NAME_MAX_LENGTH = 32;
58 * The ID consists of 2 parts: the entity type and the field name.
60 * Example: node.body, user.field_main_image.
69 * This is the name of the property under which the field values are placed in
70 * an entity: $entity->{$field_name}. The maximum length is
71 * Field:NAME_MAX_LENGTH.
73 * Example: body, field_main_image.
77 protected $field_name;
80 * The name of the entity type the field can be attached to.
84 protected $entity_type;
89 * Example: text, integer.
96 * The name of the module that provides the field type.
103 * Field-type specific settings.
105 * An array of key/value pairs, The keys and default values are defined by the
110 protected $settings = [];
113 * The field cardinality.
115 * The maximum number of values the field can hold. Possible values are
116 * positive integers or
117 * FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED. Defaults to 1.
121 protected $cardinality = 1;
124 * Flag indicating whether the field is translatable.
130 protected $translatable = TRUE;
133 * Flag indicating whether the field is available for editing.
135 * If TRUE, some actions not available though the UI (but are still possible
136 * through direct API manipulation):
137 * - field settings cannot be changed,
138 * - new fields cannot be created
139 * - existing fields cannot be deleted.
144 protected $locked = FALSE;
147 * Flag indicating whether the field storage should be deleted when orphaned.
149 * By default field storages for configurable fields are removed when there
150 * are no remaining fields using them. If multiple modules provide bundles
151 * which need to use the same field storage then setting this to TRUE will
152 * preserve the field storage regardless of what happens to the bundles. The
153 * classic use case for this is node body field storage since Book, Forum, the
154 * Standard profile and bundle (node type) creation through the UI all use
155 * same field storage.
159 protected $persist_with_no_fields = FALSE;
162 * A boolean indicating whether or not the field item uses custom storage.
166 public $custom_storage = FALSE;
169 * The custom storage indexes for the field data storage.
171 * This set of indexes is merged with the "default" indexes specified by the
172 * field type in hook_field_schema() to determine the actual set of indexes
175 * The indexes are defined using the same definition format as Schema API
176 * index specifications. Only columns that are part of the field schema, as
177 * defined by the field type in hook_field_schema(), are allowed.
179 * Some storage backends might not support indexes, and discard that
184 protected $indexes = [];
187 * Flag indicating whether the field is deleted.
189 * The delete() method marks the field as "deleted" and removes the
190 * corresponding entry from the config storage, but keeps its definition in
191 * the state storage while field data is purged by a separate
192 * garbage-collection process.
194 * Deleted fields stay out of the regular entity lifecycle (notably, their
195 * values are not populated in loaded entities, and are not saved back).
199 protected $deleted = FALSE;
209 * An array of field property definitions.
211 * @var \Drupal\Core\TypedData\DataDefinitionInterface[]
213 * @see \Drupal\Core\TypedData\ComplexDataDefinitionInterface::getPropertyDefinitions()
215 protected $propertyDefinitions;
218 * Static flag set to prevent recursion during field deletes.
222 protected static $inDeletion = FALSE;
225 * Constructs a FieldStorageConfig object.
227 * In most cases, Field entities are created via
228 * FieldStorageConfig::create($values)), where $values is the same parameter
229 * as in this constructor.
231 * @param array $values
232 * An array of field properties, keyed by property name. Most array
233 * elements will be used to set the corresponding properties on the class;
234 * see the class property documentation for details. Some array elements
235 * have special meanings and a few are required. Special elements are:
236 * - name: required. As a temporary Backwards Compatibility layer right now,
237 * a 'field_name' property can be accepted in place of 'id'.
238 * - entity_type: required.
241 * @see entity_create()
243 public function __construct(array $values, $entity_type = 'field_storage_config') {
244 // Check required properties.
245 if (empty($values['field_name'])) {
246 throw new FieldException('Attempt to create a field storage without a field name.');
248 if (!preg_match('/^[_a-z]+[_a-z0-9]*$/', $values['field_name'])) {
249 throw new FieldException("Attempt to create a field storage {$values['field_name']} with invalid characters. Only lowercase alphanumeric characters and underscores are allowed, and only lowercase letters and underscore are allowed as the first character");
251 if (empty($values['type'])) {
252 throw new FieldException("Attempt to create a field storage {$values['field_name']} with no type.");
254 if (empty($values['entity_type'])) {
255 throw new FieldException("Attempt to create a field storage {$values['field_name']} with no entity_type.");
258 parent::__construct($values, $entity_type);
264 public function id() {
265 return $this->getTargetEntityTypeId() . '.' . $this->getName();
269 * Overrides \Drupal\Core\Entity\Entity::preSave().
271 * @throws \Drupal\Core\Field\FieldException
272 * If the field definition is invalid.
273 * @throws \Drupal\Core\Entity\EntityStorageException
274 * In case of failures at the configuration storage level.
276 public function preSave(EntityStorageInterface $storage) {
277 // Clear the derived data about the field.
278 unset($this->schema);
280 // Filter out unknown settings and make sure all settings are present, so
281 // that a complete field definition is passed to the various hooks and
282 // written to config.
283 $field_type_manager = \Drupal::service('plugin.manager.field.field_type');
284 $default_settings = $field_type_manager->getDefaultStorageSettings($this->type);
285 $this->settings = array_intersect_key($this->settings, $default_settings) + $default_settings;
287 if ($this->isNew()) {
288 $this->preSaveNew($storage);
291 $this->preSaveUpdated($storage);
294 parent::preSave($storage);
298 * Prepares saving a new field definition.
300 * @param \Drupal\Core\Entity\EntityStorageInterface $storage
301 * The entity storage.
303 * @throws \Drupal\Core\Field\FieldException
304 * If the field definition is invalid.
306 protected function preSaveNew(EntityStorageInterface $storage) {
307 $entity_manager = \Drupal::entityManager();
308 $field_type_manager = \Drupal::service('plugin.manager.field.field_type');
311 $this->id = $this->id();
313 // Field name cannot be longer than FieldStorageConfig::NAME_MAX_LENGTH characters.
314 // We use Unicode::strlen() because the DB layer assumes that column widths
315 // are given in characters rather than bytes.
316 if (Unicode::strlen($this->getName()) > static::NAME_MAX_LENGTH) {
317 throw new FieldException('Attempt to create a field storage with an name longer than ' . static::NAME_MAX_LENGTH . ' characters: ' . $this->getName());
320 // Disallow reserved field names.
321 $disallowed_field_names = array_keys($entity_manager->getBaseFieldDefinitions($this->getTargetEntityTypeId()));
322 if (in_array($this->getName(), $disallowed_field_names)) {
323 throw new FieldException("Attempt to create field storage {$this->getName()} which is reserved by entity type {$this->getTargetEntityTypeId()}.");
326 // Check that the field type is known.
327 $field_type = $field_type_manager->getDefinition($this->getType(), FALSE);
329 throw new FieldException("Attempt to create a field storage of unknown type {$this->getType()}.");
331 $this->module = $field_type['provider'];
333 // Notify the entity manager.
334 $entity_manager->onFieldStorageDefinitionCreate($this);
340 public function calculateDependencies() {
341 parent::calculateDependencies();
342 // Ensure the field is dependent on the providing module.
343 $this->addDependency('module', $this->getTypeProvider());
344 // Ask the field type for any additional storage dependencies.
345 // @see \Drupal\Core\Field\FieldItemInterface::calculateStorageDependencies()
346 $definition = \Drupal::service('plugin.manager.field.field_type')->getDefinition($this->getType(), FALSE);
347 $this->addDependencies($definition['class']::calculateStorageDependencies($this));
349 // Ensure the field is dependent on the provider of the entity type.
350 $entity_type = \Drupal::entityManager()->getDefinition($this->entity_type);
351 $this->addDependency('module', $entity_type->getProvider());
356 * Prepares saving an updated field definition.
358 * @param \Drupal\Core\Entity\EntityStorageInterface $storage
359 * The entity storage.
361 protected function preSaveUpdated(EntityStorageInterface $storage) {
362 $module_handler = \Drupal::moduleHandler();
363 $entity_manager = \Drupal::entityManager();
365 // Some updates are always disallowed.
366 if ($this->getType() != $this->original->getType()) {
367 throw new FieldException("Cannot change the field type for an existing field storage.");
369 if ($this->getTargetEntityTypeId() != $this->original->getTargetEntityTypeId()) {
370 throw new FieldException("Cannot change the entity type for an existing field storage.");
373 // See if any module forbids the update by throwing an exception. This
374 // invokes hook_field_storage_config_update_forbid().
375 $module_handler->invokeAll('field_storage_config_update_forbid', [$this, $this->original]);
377 // Notify the entity manager. A listener can reject the definition
378 // update as invalid by raising an exception, which stops execution before
379 // the definition is written to config.
380 $entity_manager->onFieldStorageDefinitionUpdate($this, $this->original);
386 public function postSave(EntityStorageInterface $storage, $update = TRUE) {
388 // Invalidate the render cache for all affected entities.
389 $entity_manager = \Drupal::entityManager();
390 $entity_type = $this->getTargetEntityTypeId();
391 if ($entity_manager->hasHandler($entity_type, 'view_builder')) {
392 $entity_manager->getViewBuilder($entity_type)->resetCache();
400 public static function preDelete(EntityStorageInterface $storage, array $field_storages) {
401 $state = \Drupal::state();
403 // Set the static flag so that we don't delete field storages whilst
405 static::$inDeletion = TRUE;
407 // Delete or fix any configuration that is dependent, for example, fields.
408 parent::preDelete($storage, $field_storages);
410 // Keep the field definitions in the state storage so we can use them later
411 // during field_purge_batch().
412 $deleted_storages = $state->get('field.storage.deleted') ?: [];
413 /** @var \Drupal\field\FieldStorageConfigInterface $field_storage */
414 foreach ($field_storages as $field_storage) {
415 // Only mark a field for purging if there is data. Otherwise, just remove
417 $target_entity_storage = \Drupal::entityTypeManager()->getStorage($field_storage->getTargetEntityTypeId());
418 if (!$field_storage->deleted && $target_entity_storage instanceof FieldableEntityStorageInterface && $target_entity_storage->countFieldData($field_storage, TRUE)) {
419 $config = $field_storage->toArray();
420 $config['deleted'] = TRUE;
421 $config['bundles'] = $field_storage->getBundles();
422 $deleted_storages[$field_storage->uuid()] = $config;
426 $state->set('field.storage.deleted', $deleted_storages);
432 public static function postDelete(EntityStorageInterface $storage, array $fields) {
433 // Notify the storage.
434 foreach ($fields as $field) {
435 if (!$field->deleted) {
436 \Drupal::entityManager()->onFieldStorageDefinitionDelete($field);
437 $field->deleted = TRUE;
440 // Unset static flag.
441 static::$inDeletion = FALSE;
447 public function getSchema() {
448 if (!isset($this->schema)) {
449 // Get the schema from the field item class.
450 $class = $this->getFieldItemClass();
451 $schema = $class::schema($this);
452 // Fill in default values for optional entries.
457 'foreign keys' => [],
460 // Merge custom indexes with those specified by the field type. Custom
462 $schema['indexes'] = $this->indexes + $schema['indexes'];
464 $this->schema = $schema;
467 return $this->schema;
473 public function hasCustomStorage() {
474 return $this->custom_storage;
480 public function isBaseField() {
487 public function getColumns() {
488 $schema = $this->getSchema();
489 // A typical use case for the method is to iterate on the columns, while
490 // some other use cases rely on identifying the first column with the key()
491 // function. Since the schema is persisted in the Field object, we take care
492 // of resetting the array pointer so that the former does not interfere with
494 reset($schema['columns']);
495 return $schema['columns'];
501 public function getBundles() {
502 if (!$this->isDeleted()) {
503 $map = \Drupal::entityManager()->getFieldMap();
504 if (isset($map[$this->getTargetEntityTypeId()][$this->getName()]['bundles'])) {
505 return $map[$this->getTargetEntityTypeId()][$this->getName()]['bundles'];
514 public function getName() {
515 return $this->field_name;
521 public function isDeleted() {
522 return $this->deleted;
528 public function getTypeProvider() {
529 return $this->module;
535 public function getType() {
542 public function getSettings() {
543 // @todo FieldTypePluginManager maintains its own static cache. However, do
544 // some CPU and memory profiling to see if it's worth statically caching
545 // $field_type_info, or the default field storage and field settings,
547 $field_type_manager = \Drupal::service('plugin.manager.field.field_type');
549 $settings = $field_type_manager->getDefaultStorageSettings($this->getType());
550 return $this->settings + $settings;
556 public function getSetting($setting_name) {
557 // @todo See getSettings() about potentially statically caching this.
558 // We assume here that one call to array_key_exists() is more efficient
559 // than calling getSettings() when all we need is a single setting.
560 if (array_key_exists($setting_name, $this->settings)) {
561 return $this->settings[$setting_name];
563 $settings = $this->getSettings();
564 if (array_key_exists($setting_name, $settings)) {
565 return $settings[$setting_name];
575 public function setSetting($setting_name, $value) {
576 $this->settings[$setting_name] = $value;
583 public function setSettings(array $settings) {
584 $this->settings = $settings + $this->settings;
591 public function isTranslatable() {
592 return $this->translatable;
598 public function isRevisionable() {
599 // All configurable fields are revisionable.
606 public function setTranslatable($translatable) {
607 $this->translatable = $translatable;
614 public function getProvider() {
621 public function getLabel() {
622 return $this->label();
628 public function getDescription() {
635 public function getCardinality() {
636 /** @var \Drupal\Core\Field\FieldTypePluginManager $field_type_manager */
637 $field_type_manager = \Drupal::service('plugin.manager.field.field_type');
638 $definition = $field_type_manager->getDefinition($this->getType());
639 $enforced_cardinality = isset($definition['cardinality']) ? $definition['cardinality'] : NULL;
641 // Enforced cardinality is a positive integer or -1.
642 if ($enforced_cardinality !== NULL && $enforced_cardinality < 1 && $enforced_cardinality !== FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED) {
643 throw new FieldException("Invalid enforced cardinality '$enforced_cardinality'. Allowed values: a positive integer or -1.");
646 return $enforced_cardinality ?: $this->cardinality;
652 public function setCardinality($cardinality) {
653 $this->cardinality = $cardinality;
660 public function getOptionsProvider($property_name, FieldableEntityInterface $entity) {
661 // If the field item class implements the interface, create an orphaned
662 // runtime item object, so that it can be used as the options provider
663 // without modifying the entity being worked on.
664 if (is_subclass_of($this->getFieldItemClass(), OptionsProviderInterface::class)) {
665 $items = $entity->get($this->getName());
666 return \Drupal::service('plugin.manager.field.field_type')->createFieldItem($items, 0);
668 // @todo: Allow setting custom options provider, see
669 // https://www.drupal.org/node/2002138.
675 public function isMultiple() {
676 $cardinality = $this->getCardinality();
677 return ($cardinality == FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED) || ($cardinality > 1);
683 public function isLocked() {
684 return $this->locked;
690 public function setLocked($locked) {
691 $this->locked = $locked;
698 public function getTargetEntityTypeId() {
699 return $this->entity_type;
705 public function isQueryable() {
710 * Determines whether a field has any data.
713 * TRUE if the field has data for any entity; FALSE otherwise.
715 public function hasData() {
716 return \Drupal::entityManager()->getStorage($this->entity_type)->countFieldData($this, TRUE);
720 * Implements the magic __sleep() method.
722 * Using the Serialize interface and serialize() / unserialize() methods
723 * breaks entity forms in PHP 5.4.
724 * @todo Investigate in https://www.drupal.org/node/2074253.
726 public function __sleep() {
727 // Only serialize necessary properties, excluding those that can be
729 $properties = get_object_vars($this);
730 unset($properties['schema'], $properties['propertyDefinitions'], $properties['original']);
731 return array_keys($properties);
737 public function getConstraints() {
744 public function getConstraint($constraint_name) {
751 public function getPropertyDefinition($name) {
752 if (!isset($this->propertyDefinitions)) {
753 $this->getPropertyDefinitions();
755 if (isset($this->propertyDefinitions[$name])) {
756 return $this->propertyDefinitions[$name];
763 public function getPropertyDefinitions() {
764 if (!isset($this->propertyDefinitions)) {
765 $class = $this->getFieldItemClass();
766 $this->propertyDefinitions = $class::propertyDefinitions($this);
768 return $this->propertyDefinitions;
774 public function getPropertyNames() {
775 return array_keys($this->getPropertyDefinitions());
781 public function getMainPropertyName() {
782 $class = $this->getFieldItemClass();
783 return $class::mainPropertyName();
789 public function getUniqueStorageIdentifier() {
790 return $this->uuid();
794 * Helper to retrieve the field item class.
796 protected function getFieldItemClass() {
797 $type_definition = \Drupal::typedDataManager()
798 ->getDefinition('field_item:' . $this->getType());
799 return $type_definition['class'];
803 * Loads a field config entity based on the entity type and field name.
805 * @param string $entity_type_id
806 * ID of the entity type.
807 * @param string $field_name
811 * The field config entity if one exists for the provided field name,
814 public static function loadByName($entity_type_id, $field_name) {
815 return \Drupal::entityManager()->getStorage('field_storage_config')->load($entity_type_id . '.' . $field_name);
821 public function isDeletable() {
822 // The field storage is not deleted, is configured to be removed when there
823 // are no fields, the field storage has no bundles, and field storages are
824 // not in the process of being deleted.
825 return !$this->deleted && !$this->persist_with_no_fields && count($this->getBundles()) == 0 && !static::$inDeletion;
831 public function getIndexes() {
832 return $this->indexes;
838 public function setIndexes(array $indexes) {
839 $this->indexes = $indexes;