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 /** @var \Drupal\Core\Field\DeletedFieldsRepositoryInterface $deleted_fields_repository */
402 $deleted_fields_repository = \Drupal::service('entity_field.deleted_fields_repository');
404 // Set the static flag so that we don't delete field storages whilst
406 static::$inDeletion = TRUE;
408 // Delete or fix any configuration that is dependent, for example, fields.
409 parent::preDelete($storage, $field_storages);
411 // Keep the field storage definitions in the deleted fields repository so we
412 // can use them later during field_purge_batch().
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 $storage_definition = clone $field_storage;
420 $storage_definition->deleted = TRUE;
421 $deleted_fields_repository->addFieldStorageDefinition($storage_definition);
429 public static function postDelete(EntityStorageInterface $storage, array $fields) {
430 // Notify the storage.
431 foreach ($fields as $field) {
432 if (!$field->deleted) {
433 \Drupal::entityManager()->onFieldStorageDefinitionDelete($field);
434 $field->deleted = TRUE;
437 // Unset static flag.
438 static::$inDeletion = FALSE;
444 public function getSchema() {
445 if (!isset($this->schema)) {
446 // Get the schema from the field item class.
447 $class = $this->getFieldItemClass();
448 $schema = $class::schema($this);
449 // Fill in default values for optional entries.
454 'foreign keys' => [],
457 // Merge custom indexes with those specified by the field type. Custom
459 $schema['indexes'] = $this->indexes + $schema['indexes'];
461 $this->schema = $schema;
464 return $this->schema;
470 public function hasCustomStorage() {
471 return $this->custom_storage;
477 public function isBaseField() {
484 public function getColumns() {
485 $schema = $this->getSchema();
486 // A typical use case for the method is to iterate on the columns, while
487 // some other use cases rely on identifying the first column with the key()
488 // function. Since the schema is persisted in the Field object, we take care
489 // of resetting the array pointer so that the former does not interfere with
491 reset($schema['columns']);
492 return $schema['columns'];
498 public function getBundles() {
499 if (!$this->isDeleted()) {
500 $map = \Drupal::entityManager()->getFieldMap();
501 if (isset($map[$this->getTargetEntityTypeId()][$this->getName()]['bundles'])) {
502 return $map[$this->getTargetEntityTypeId()][$this->getName()]['bundles'];
511 public function getName() {
512 return $this->field_name;
518 public function isDeleted() {
519 return $this->deleted;
525 public function getTypeProvider() {
526 return $this->module;
532 public function getType() {
539 public function getSettings() {
540 // @todo FieldTypePluginManager maintains its own static cache. However, do
541 // some CPU and memory profiling to see if it's worth statically caching
542 // $field_type_info, or the default field storage and field settings,
544 $field_type_manager = \Drupal::service('plugin.manager.field.field_type');
546 $settings = $field_type_manager->getDefaultStorageSettings($this->getType());
547 return $this->settings + $settings;
553 public function getSetting($setting_name) {
554 // @todo See getSettings() about potentially statically caching this.
555 // We assume here that one call to array_key_exists() is more efficient
556 // than calling getSettings() when all we need is a single setting.
557 if (array_key_exists($setting_name, $this->settings)) {
558 return $this->settings[$setting_name];
560 $settings = $this->getSettings();
561 if (array_key_exists($setting_name, $settings)) {
562 return $settings[$setting_name];
572 public function setSetting($setting_name, $value) {
573 $this->settings[$setting_name] = $value;
580 public function setSettings(array $settings) {
581 $this->settings = $settings + $this->settings;
588 public function isTranslatable() {
589 return $this->translatable;
595 public function isRevisionable() {
596 // All configurable fields are revisionable.
603 public function setTranslatable($translatable) {
604 $this->translatable = $translatable;
611 public function getProvider() {
618 public function getLabel() {
619 return $this->label();
625 public function getDescription() {
632 public function getCardinality() {
633 /** @var \Drupal\Core\Field\FieldTypePluginManager $field_type_manager */
634 $field_type_manager = \Drupal::service('plugin.manager.field.field_type');
635 $definition = $field_type_manager->getDefinition($this->getType());
636 $enforced_cardinality = isset($definition['cardinality']) ? $definition['cardinality'] : NULL;
638 // Enforced cardinality is a positive integer or -1.
639 if ($enforced_cardinality !== NULL && $enforced_cardinality < 1 && $enforced_cardinality !== FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED) {
640 throw new FieldException("Invalid enforced cardinality '$enforced_cardinality'. Allowed values: a positive integer or -1.");
643 return $enforced_cardinality ?: $this->cardinality;
649 public function setCardinality($cardinality) {
650 $this->cardinality = $cardinality;
657 public function getOptionsProvider($property_name, FieldableEntityInterface $entity) {
658 // If the field item class implements the interface, create an orphaned
659 // runtime item object, so that it can be used as the options provider
660 // without modifying the entity being worked on.
661 if (is_subclass_of($this->getFieldItemClass(), OptionsProviderInterface::class)) {
662 $items = $entity->get($this->getName());
663 return \Drupal::service('plugin.manager.field.field_type')->createFieldItem($items, 0);
665 // @todo: Allow setting custom options provider, see
666 // https://www.drupal.org/node/2002138.
672 public function isMultiple() {
673 $cardinality = $this->getCardinality();
674 return ($cardinality == FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED) || ($cardinality > 1);
680 public function isLocked() {
681 return $this->locked;
687 public function setLocked($locked) {
688 $this->locked = $locked;
695 public function getTargetEntityTypeId() {
696 return $this->entity_type;
702 public function isQueryable() {
707 * Determines whether a field has any data.
710 * TRUE if the field has data for any entity; FALSE otherwise.
712 public function hasData() {
713 return \Drupal::entityManager()->getStorage($this->entity_type)->countFieldData($this, TRUE);
717 * Implements the magic __sleep() method.
719 * Using the Serialize interface and serialize() / unserialize() methods
720 * breaks entity forms in PHP 5.4.
721 * @todo Investigate in https://www.drupal.org/node/2074253.
723 public function __sleep() {
724 // Only serialize necessary properties, excluding those that can be
726 $properties = get_object_vars($this);
727 unset($properties['schema'], $properties['propertyDefinitions'], $properties['original']);
728 return array_keys($properties);
734 public function getConstraints() {
741 public function getConstraint($constraint_name) {
748 public function getPropertyDefinition($name) {
749 if (!isset($this->propertyDefinitions)) {
750 $this->getPropertyDefinitions();
752 if (isset($this->propertyDefinitions[$name])) {
753 return $this->propertyDefinitions[$name];
760 public function getPropertyDefinitions() {
761 if (!isset($this->propertyDefinitions)) {
762 $class = $this->getFieldItemClass();
763 $this->propertyDefinitions = $class::propertyDefinitions($this);
765 return $this->propertyDefinitions;
771 public function getPropertyNames() {
772 return array_keys($this->getPropertyDefinitions());
778 public function getMainPropertyName() {
779 $class = $this->getFieldItemClass();
780 return $class::mainPropertyName();
786 public function getUniqueStorageIdentifier() {
787 return $this->uuid();
791 * Helper to retrieve the field item class.
793 protected function getFieldItemClass() {
794 $type_definition = \Drupal::typedDataManager()
795 ->getDefinition('field_item:' . $this->getType());
796 return $type_definition['class'];
800 * Loads a field config entity based on the entity type and field name.
802 * @param string $entity_type_id
803 * ID of the entity type.
804 * @param string $field_name
808 * The field config entity if one exists for the provided field name,
811 public static function loadByName($entity_type_id, $field_name) {
812 return \Drupal::entityManager()->getStorage('field_storage_config')->load($entity_type_id . '.' . $field_name);
818 public function isDeletable() {
819 // The field storage is not deleted, is configured to be removed when there
820 // are no fields, the field storage has no bundles, and field storages are
821 // not in the process of being deleted.
822 return !$this->deleted && !$this->persist_with_no_fields && count($this->getBundles()) == 0 && !static::$inDeletion;
828 public function getIndexes() {
829 return $this->indexes;
835 public function setIndexes(array $indexes) {
836 $this->indexes = $indexes;