Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add field:delete command #4926

Merged
merged 7 commits into from Dec 16, 2021
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
75 changes: 2 additions & 73 deletions src/Drupal/Commands/core/FieldCreateCommands.php
Expand Up @@ -26,7 +26,9 @@

class FieldCreateCommands extends DrushCommands implements CustomEventAwareInterface
{
use AskBundleTrait;
use CustomEventAwareTrait;
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks like we don't use a CustomEvent directly.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We do call the getCustomEventHandlers method in FieldCreateCommands, right?

use ValidateEntityTypeTrait;

/** @var FieldTypePluginManagerInterface */
protected $fieldTypePluginManager;
Expand Down Expand Up @@ -216,41 +218,6 @@ public function create(string $entityType, ?string $bundle = null, array $option
$this->logResult($field);
}

protected function validateEntityType(string $entityTypeId): void
{
if (!$this->entityTypeManager->hasDefinition($entityTypeId)) {
throw new \InvalidArgumentException(
t("Entity type with id ':entityType' does not exist.", [':entityType' => $entityTypeId])
);
}
}

protected function validateBundle(string $entityTypeId, string $bundle): void
{
if (!$entityTypeDefinition = $this->entityTypeManager->getDefinition($entityTypeId)) {
return;
}

$bundleEntityType = $entityTypeDefinition->getBundleEntityType();

if ($bundleEntityType === null && $bundle === $entityTypeId) {
return;
}

$bundleDefinition = $this->entityTypeManager
->getStorage($bundleEntityType)
->load($bundle);

if (!$bundleDefinition) {
throw new \InvalidArgumentException(
t("Bundle ':bundle' does not exist on entity type with id ':entityType'.", [
':bundle' => $bundle,
':entityType' => $entityTypeId,
])
);
}
}

protected function askExistingFieldName(): ?string
{
$entityType = $this->input->getArgument('entityType');
Expand Down Expand Up @@ -361,44 +328,6 @@ protected function askTranslatable(): bool
return $this->io()->confirm('Translatable', false);
}

protected function askBundle(): ?string
{
$entityTypeId = $this->input->getArgument('entityType');
$entityTypeDefinition = $this->entityTypeManager->getDefinition($entityTypeId);
$bundleEntityType = $entityTypeDefinition->getBundleEntityType();
$bundleInfo = $this->entityTypeBundleInfo->getBundleInfo($entityTypeId);
$choices = [];

// If the entity type has one fixed bundle (eg. user), return it.
if ($bundleEntityType === null && count($bundleInfo) === 1) {
return key($bundleInfo);
}

// If the entity type doesn't have bundles, return null
// TODO Find an example
if ($bundleEntityType === null && count($bundleInfo) === 0) {
return null;
}

// If the entity type can have multiple bundles but it doesn't have any, throw an error
if ($bundleEntityType !== null && count($bundleInfo) === 0) {
throw new \InvalidArgumentException(
t("Entity type with id ':entityType' does not have any bundles.", [':entityType' => $entityTypeId])
);
}

foreach ($bundleInfo as $bundle => $data) {
$label = $this->input->getOption('show-machine-names') ? $bundle : $data['label'];
$choices[$bundle] = $label;
}

if (!$this->input->isInteractive() || !$answer = $this->io()->choice('Bundle', $choices)) {
throw new \InvalidArgumentException(t('The bundle argument is required.'));
}

return $answer;
}

protected function askCardinality(): int
{
$fieldType = $this->input->getOption('field-type');
Expand Down
150 changes: 150 additions & 0 deletions src/Drupal/Commands/core/FieldDeleteCommands.php
@@ -0,0 +1,150 @@
<?php

namespace Drush\Drupal\Commands\core;

use Drupal\Core\Entity\EntityTypeBundleInfo;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\field\Entity\FieldConfig;
use Drupal\field\FieldConfigInterface;
use Drush\Commands\DrushCommands;
use Symfony\Component\Console\Input\InputOption;

class FieldDeleteCommands extends DrushCommands
{
use AskBundleTrait;
use ValidateEntityTypeTrait;

/** @var EntityTypeManagerInterface */
protected $entityTypeManager;
/** @var EntityTypeBundleInfo */
protected $entityTypeBundleInfo;

public function __construct(
EntityTypeManagerInterface $entityTypeManager,
EntityTypeBundleInfo $entityTypeBundleInfo
) {
$this->entityTypeManager = $entityTypeManager;
$this->entityTypeBundleInfo = $entityTypeBundleInfo;
}

/**
* Delete a field
*
* @command field:delete
* @aliases field-delete,fd
*
* @param string $entityType
* The machine name of the entity type
* @param string $bundle
* The machine name of the bundle
*
* @option field-name
* The machine name of the field
*
* @option show-machine-names
* Show machine names instead of labels in option lists.
*
* @usage drush field:delete
DieterHolvoet marked this conversation as resolved.
Show resolved Hide resolved
* Delete a field by answering the prompts.
* @usage drush field-delete taxonomy_term tag
* Delete a field and fill in the remaining information through prompts.
* @usage drush field-delete taxonomy_term tag --field-name=field_tag_label
* Delete a field in a completely non-interactive way.
*
* @version 11.0
*/
public function delete(string $entityType, ?string $bundle = null, array $options = [
'field-name' => InputOption::VALUE_REQUIRED,
'show-machine-names' => InputOption::VALUE_OPTIONAL,
]): void
{
$this->validateEntityType($entityType);

$this->input->setArgument('bundle', $bundle = $bundle ?? $this->askBundle());
$this->validateBundle($entityType, $bundle);

$fieldName = $this->input->getOption('field-name') ?? $this->askExisting($entityType, $bundle);
$this->input->setOption('field-name', $fieldName);

if ($fieldName === '') {
throw new \InvalidArgumentException(dt('The %optionName option is required.', [
'%optionName' => 'field-name',
]));
}

/** @var FieldConfig[] $results */
$results = $this->entityTypeManager
->getStorage('field_config')
->loadByProperties([
'field_name' => $fieldName,
'entity_type' => $entityType,
'bundle' => $bundle,
]);

if ($results === []) {
throw new \InvalidArgumentException(
t("Field with name ':fieldName' does not exist on bundle ':bundle'.", [
':fieldName' => $fieldName,
':bundle' => $bundle,
])
);
}

$this->deleteFieldConfig(reset($results));

// Fields are purged on cron. However field module prevents disabling modules
// when field types they provided are used in a field until it is fully
// purged. In the case that a field has minimal or no content, a single call
// to field_purge_batch() will remove it from the system. Call this with a
// low batch limit to avoid administrators having to wait for cron runs when
// removing fields that meet this criteria.
field_purge_batch(10);
}

protected function askExisting(string $entityType, string $bundle): string
{
$choices = [];
/** @var FieldConfigInterface[] $fieldConfigs */
$fieldConfigs = $this->entityTypeManager
->getStorage('field_config')
->loadByProperties([
'entity_type' => $entityType,
'bundle' => $bundle,
]);

foreach ($fieldConfigs as $fieldConfig) {
$label = $this->input->getOption('show-machine-names')
? $fieldConfig->get('field_name')
: $fieldConfig->get('label');

$choices[$fieldConfig->get('field_name')] = $label;
}

return $this->io()->choice('Choose a field to delete', $choices);
}

protected function deleteFieldConfig(FieldConfigInterface $fieldConfig): void
{
$fieldStorage = $fieldConfig->getFieldStorageDefinition();
$bundles = $this->entityTypeBundleInfo->getBundleInfo($fieldConfig->getTargetEntityTypeId());
$bundleLabel = $bundles[$fieldConfig->getTargetBundle()]['label'];

if ($fieldStorage && !$fieldStorage->isLocked()) {
$fieldConfig->delete();

// If there is only one bundle left for this field storage, it will be
// deleted too, notify the user about dependencies.
if (count($fieldStorage->getBundles()) <= 1) {
$fieldStorage->delete();
}

$message = 'The field :field has been deleted from the :type content type.';
} else {
$message = 'There was a problem removing the :field from the :type content type.';
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Drupal will not let you delete a field with data in it. Can we show that exception message, instead of "there was a problem"?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I used the exact same error message as shown in the UI: https://git.drupalcode.org/project/drupal/-/blob/9.3.x/core/modules/field_ui/src/Form/FieldConfigDeleteForm.php#L104

Isn't it possible that the field storage being locked can have other causes? Because if that's the case, we should keep the error message generic, just like field_ui does. Btw, I just tested it and I can delete fields with data in them using field:delete.

}

$this->logger()->success(
t($message, [':field' => $fieldConfig->label(), ':type' => $bundleLabel])
);
}
}
7 changes: 7 additions & 0 deletions src/Drupal/Commands/core/drush.services.yml
Expand Up @@ -42,6 +42,13 @@ services:
- '@entity_type.bundle.info'
tags:
- { name: drush.command }
field.delete.commands:
class: \Drush\Drupal\Commands\core\FieldDeleteCommands
arguments:
- '@entity_type.manager'
- '@entity_type.bundle.info'
tags:
- { name: drush.command }
link.hooks:
class: \Drush\Drupal\Commands\core\LinkHooks
arguments:
Expand Down