Skip to main content
Drupal API
User account menu
  • Log in

Breadcrumb

  1. Drupal Core 11.1.x
  2. RemoveCommand.php

class RemoveCommand

Same name in this branch
  1. 11.1.x core/lib/Drupal/Core/Ajax/RemoveCommand.php \Drupal\Core\Ajax\RemoveCommand

@author Pierre du Plessis <pdples@gmail.com> @author Jordi Boggiano <j.boggiano@seld.be>

Hierarchy

  • class \Symfony\Component\Console\Command\Command
    • class \Composer\Command\BaseCommand extends \Symfony\Component\Console\Command\Command
      • class \Composer\Command\RemoveCommand extends \Composer\Command\BaseCommand uses \Composer\Command\CompletionTrait

Expanded class hierarchy of RemoveCommand

File

vendor/composer/composer/src/Composer/Command/RemoveCommand.php, line 35

Namespace

Composer\Command
View source
class RemoveCommand extends BaseCommand {
    use CompletionTrait;
    
    /**
     * @return void
     */
    protected function configure() {
        $this->setName('remove')
            ->setAliases([
            'rm',
            'uninstall',
        ])
            ->setDescription('Removes a package from the require or require-dev')
            ->setDefinition([
            new InputArgument('packages', InputArgument::IS_ARRAY, 'Packages that should be removed.', null, $this->suggestRootRequirement()),
            new InputOption('dev', null, InputOption::VALUE_NONE, 'Removes a package from the require-dev section.'),
            new InputOption('dry-run', null, InputOption::VALUE_NONE, 'Outputs the operations but will not execute anything (implicitly enables --verbose).'),
            new InputOption('no-progress', null, InputOption::VALUE_NONE, 'Do not output download progress.'),
            new InputOption('no-update', null, InputOption::VALUE_NONE, 'Disables the automatic update of the dependencies (implies --no-install).'),
            new InputOption('no-install', null, InputOption::VALUE_NONE, 'Skip the install step after updating the composer.lock file.'),
            new InputOption('no-audit', null, InputOption::VALUE_NONE, 'Skip the audit step after updating the composer.lock file (can also be set via the COMPOSER_NO_AUDIT=1 env var).'),
            new InputOption('audit-format', null, InputOption::VALUE_REQUIRED, 'Audit output format. Must be "table", "plain", "json", or "summary".', Auditor::FORMAT_SUMMARY, Auditor::FORMATS),
            new InputOption('update-no-dev', null, InputOption::VALUE_NONE, 'Run the dependency update with the --no-dev option.'),
            new InputOption('update-with-dependencies', 'w', InputOption::VALUE_NONE, 'Allows inherited dependencies to be updated with explicit dependencies. (Deprecated, is now default behavior)'),
            new InputOption('update-with-all-dependencies', 'W', InputOption::VALUE_NONE, 'Allows all inherited dependencies to be updated, including those that are root requirements.'),
            new InputOption('with-all-dependencies', null, InputOption::VALUE_NONE, 'Alias for --update-with-all-dependencies'),
            new InputOption('no-update-with-dependencies', null, InputOption::VALUE_NONE, 'Does not allow inherited dependencies to be updated with explicit dependencies.'),
            new InputOption('minimal-changes', 'm', InputOption::VALUE_NONE, 'During an update with -w/-W, only perform absolutely necessary changes to transitive dependencies (can also be set via the COMPOSER_MINIMAL_CHANGES=1 env var).'),
            new InputOption('unused', null, InputOption::VALUE_NONE, 'Remove all packages which are locked but not required by any other package.'),
            new InputOption('ignore-platform-req', null, InputOption::VALUE_REQUIRED | InputOption::VALUE_IS_ARRAY, 'Ignore a specific platform requirement (php & ext- packages).'),
            new InputOption('ignore-platform-reqs', null, InputOption::VALUE_NONE, 'Ignore all platform requirements (php & ext- packages).'),
            new InputOption('optimize-autoloader', 'o', InputOption::VALUE_NONE, 'Optimize autoloader during autoloader dump'),
            new InputOption('classmap-authoritative', 'a', InputOption::VALUE_NONE, 'Autoload classes from the classmap only. Implicitly enables `--optimize-autoloader`.'),
            new InputOption('apcu-autoloader', null, InputOption::VALUE_NONE, 'Use APCu to cache found/not-found classes.'),
            new InputOption('apcu-autoloader-prefix', null, InputOption::VALUE_REQUIRED, 'Use a custom prefix for the APCu autoloader cache. Implicitly enables --apcu-autoloader'),
        ])
            ->setHelp(<<<EOT
The <info>remove</info> command removes a package from the current
list of installed packages

<info>php composer.phar remove</info>

Read more at https://getcomposer.org/doc/03-cli.md#remove-rm
EOT
);
    }
    
    /**
     * @throws \Seld\JsonLint\ParsingException
     */
    protected function execute(InputInterface $input, OutputInterface $output) : int {
        if ($input->getArgument('packages') === [] && !$input->getOption('unused')) {
            throw new InvalidArgumentException('Not enough arguments (missing: "packages").');
        }
        $packages = $input->getArgument('packages');
        $packages = array_map('strtolower', $packages);
        if ($input->getOption('unused')) {
            $composer = $this->requireComposer();
            $locker = $composer->getLocker();
            if (!$locker->isLocked()) {
                throw new \UnexpectedValueException('A valid composer.lock file is required to run this command with --unused');
            }
            $lockedPackages = $locker->getLockedRepository()
                ->getPackages();
            $required = [];
            foreach (array_merge($composer->getPackage()
                ->getRequires(), $composer->getPackage()
                ->getDevRequires()) as $link) {
                $required[$link->getTarget()] = true;
            }
            do {
                $found = false;
                foreach ($lockedPackages as $index => $package) {
                    foreach ($package->getNames() as $name) {
                        if (isset($required[$name])) {
                            foreach ($package->getRequires() as $link) {
                                $required[$link->getTarget()] = true;
                            }
                            $found = true;
                            unset($lockedPackages[$index]);
                            break;
                        }
                    }
                }
            } while ($found);
            $unused = [];
            foreach ($lockedPackages as $package) {
                $unused[] = $package->getName();
            }
            $packages = array_merge($packages, $unused);
            if (count($packages) === 0) {
                $this->getIO()
                    ->writeError('<info>No unused packages to remove</info>');
                return 0;
            }
        }
        $file = Factory::getComposerFile();
        $jsonFile = new JsonFile($file);
        
        /** @var array{require?: array<string, string>, require-dev?: array<string, string>} $composer */
        $composer = $jsonFile->read();
        $composerBackup = file_get_contents($jsonFile->getPath());
        $json = new JsonConfigSource($jsonFile);
        $type = $input->getOption('dev') ? 'require-dev' : 'require';
        $altType = !$input->getOption('dev') ? 'require-dev' : 'require';
        $io = $this->getIO();
        if ($input->getOption('update-with-dependencies')) {
            $io->writeError('<warning>You are using the deprecated option "update-with-dependencies". This is now default behaviour. The --no-update-with-dependencies option can be used to remove a package without its dependencies.</warning>');
        }
        // make sure name checks are done case insensitively
        foreach ([
            'require',
            'require-dev',
        ] as $linkType) {
            if (isset($composer[$linkType])) {
                foreach ($composer[$linkType] as $name => $version) {
                    $composer[$linkType][strtolower($name)] = $name;
                }
            }
        }
        $dryRun = $input->getOption('dry-run');
        $toRemove = [];
        foreach ($packages as $package) {
            if (isset($composer[$type][$package])) {
                if ($dryRun) {
                    $toRemove[$type][] = $composer[$type][$package];
                }
                else {
                    $json->removeLink($type, $composer[$type][$package]);
                }
            }
            elseif (isset($composer[$altType][$package])) {
                $io->writeError('<warning>' . $composer[$altType][$package] . ' could not be found in ' . $type . ' but it is present in ' . $altType . '</warning>');
                if ($io->isInteractive()) {
                    if ($io->askConfirmation('Do you want to remove it from ' . $altType . ' [<comment>yes</comment>]? ')) {
                        if ($dryRun) {
                            $toRemove[$altType][] = $composer[$altType][$package];
                        }
                        else {
                            $json->removeLink($altType, $composer[$altType][$package]);
                        }
                    }
                }
            }
            elseif (isset($composer[$type]) && count($matches = Preg::grep(BasePackage::packageNameToRegexp($package), array_keys($composer[$type]))) > 0) {
                foreach ($matches as $matchedPackage) {
                    if ($dryRun) {
                        $toRemove[$type][] = $matchedPackage;
                    }
                    else {
                        $json->removeLink($type, $matchedPackage);
                    }
                }
            }
            elseif (isset($composer[$altType]) && count($matches = Preg::grep(BasePackage::packageNameToRegexp($package), array_keys($composer[$altType]))) > 0) {
                foreach ($matches as $matchedPackage) {
                    $io->writeError('<warning>' . $matchedPackage . ' could not be found in ' . $type . ' but it is present in ' . $altType . '</warning>');
                    if ($io->isInteractive()) {
                        if ($io->askConfirmation('Do you want to remove it from ' . $altType . ' [<comment>yes</comment>]? ')) {
                            if ($dryRun) {
                                $toRemove[$altType][] = $matchedPackage;
                            }
                            else {
                                $json->removeLink($altType, $matchedPackage);
                            }
                        }
                    }
                }
            }
            else {
                $io->writeError('<warning>' . $package . ' is not required in your composer.json and has not been removed</warning>');
            }
        }
        $io->writeError('<info>' . $file . ' has been updated</info>');
        if ($input->getOption('no-update')) {
            return 0;
        }
        if ($composer = $this->tryComposer()) {
            $composer->getPluginManager()
                ->deactivateInstalledPlugins();
        }
        // Update packages
        $this->resetComposer();
        $composer = $this->requireComposer();
        if ($dryRun) {
            $rootPackage = $composer->getPackage();
            $links = [
                'require' => $rootPackage->getRequires(),
                'require-dev' => $rootPackage->getDevRequires(),
            ];
            foreach ($toRemove as $type => $names) {
                foreach ($names as $name) {
                    unset($links[$type][$name]);
                }
            }
            $rootPackage->setRequires($links['require']);
            $rootPackage->setDevRequires($links['require-dev']);
        }
        $commandEvent = new CommandEvent(PluginEvents::COMMAND, 'remove', $input, $output);
        $composer->getEventDispatcher()
            ->dispatch($commandEvent->getName(), $commandEvent);
        $allowPlugins = $composer->getConfig()
            ->get('allow-plugins');
        $removedPlugins = is_array($allowPlugins) ? array_intersect(array_keys($allowPlugins), $packages) : [];
        if (!$dryRun && is_array($allowPlugins) && count($removedPlugins) > 0) {
            if (count($allowPlugins) === count($removedPlugins)) {
                $json->removeConfigSetting('allow-plugins');
            }
            else {
                foreach ($removedPlugins as $plugin) {
                    $json->removeConfigSetting('allow-plugins.' . $plugin);
                }
            }
        }
        $composer->getInstallationManager()
            ->setOutputProgress(!$input->getOption('no-progress'));
        $install = Installer::create($io, $composer);
        $updateDevMode = !$input->getOption('update-no-dev');
        $optimize = $input->getOption('optimize-autoloader') || $composer->getConfig()
            ->get('optimize-autoloader');
        $authoritative = $input->getOption('classmap-authoritative') || $composer->getConfig()
            ->get('classmap-authoritative');
        $apcuPrefix = $input->getOption('apcu-autoloader-prefix');
        $apcu = $apcuPrefix !== null || $input->getOption('apcu-autoloader') || $composer->getConfig()
            ->get('apcu-autoloader');
        $updateAllowTransitiveDependencies = Request::UPDATE_LISTED_WITH_TRANSITIVE_DEPS_NO_ROOT_REQUIRE;
        $flags = '';
        if ($input->getOption('update-with-all-dependencies') || $input->getOption('with-all-dependencies')) {
            $updateAllowTransitiveDependencies = Request::UPDATE_LISTED_WITH_TRANSITIVE_DEPS;
            $flags .= ' --with-all-dependencies';
        }
        elseif ($input->getOption('no-update-with-dependencies')) {
            $updateAllowTransitiveDependencies = Request::UPDATE_ONLY_LISTED;
            $flags .= ' --with-dependencies';
        }
        $io->writeError('<info>Running composer update ' . implode(' ', $packages) . $flags . '</info>');
        $install->setVerbose($input->getOption('verbose'))
            ->setDevMode($updateDevMode)
            ->setOptimizeAutoloader($optimize)
            ->setClassMapAuthoritative($authoritative)
            ->setApcuAutoloader($apcu, $apcuPrefix)
            ->setUpdate(true)
            ->setInstall(!$input->getOption('no-install'))
            ->setUpdateAllowTransitiveDependencies($updateAllowTransitiveDependencies)
            ->setPlatformRequirementFilter($this->getPlatformRequirementFilter($input))
            ->setDryRun($dryRun)
            ->setAudit(!$input->getOption('no-audit'))
            ->setAuditFormat($this->getAuditFormat($input))
            ->setMinimalUpdate($input->getOption('minimal-changes'));
        // if no lock is present, we do not do a partial update as
        // this is not supported by the Installer
        if ($composer->getLocker()
            ->isLocked()) {
            $install->setUpdateAllowList($packages);
        }
        $status = $install->run();
        if ($status !== 0) {
            $io->writeError("\n" . '<error>Removal failed, reverting ' . $file . ' to its original content.</error>');
            file_put_contents($jsonFile->getPath(), $composerBackup);
        }
        if (!$dryRun) {
            foreach ($packages as $package) {
                if ($composer->getRepositoryManager()
                    ->getLocalRepository()
                    ->findPackages($package)) {
                    $io->writeError('<error>Removal failed, ' . $package . ' is still present, it may be required by another package. See `composer why ' . $package . '`.</error>');
                    return 2;
                }
            }
        }
        return $status;
    }

}

Members

Title Sort descending Deprecated Modifiers Object type Summary Overriden Title Overrides
BaseCommand::$composer private property
BaseCommand::$io private property
BaseCommand::complete public function @inheritdoc Overrides Command::complete 1
BaseCommand::createComposerInstance protected function Calls {
BaseCommand::formatRequirements protected function
BaseCommand::getApplication public function Gets the application instance for this command. Overrides Command::getApplication
BaseCommand::getAuditFormat protected function @internal
BaseCommand::getComposer Deprecated public function
BaseCommand::getIO public function
BaseCommand::getPlatformRequirementFilter protected function
BaseCommand::getPreferredInstallOptions protected function Returns preferSource and preferDist values based on the configuration.
BaseCommand::getTerminalWidth protected function
BaseCommand::initialize protected function @inheritDoc Overrides Command::initialize 1
BaseCommand::isProxyCommand public function Whether or not this command is meant to call another command. 2
BaseCommand::normalizeRequirements protected function
BaseCommand::renderTable protected function
BaseCommand::resetComposer public function Removes the cached composer instance
BaseCommand::setComposer public function
BaseCommand::setIO public function
BaseCommand::tryComposer public function Retrieves the default Composer\Composer instance or null
Command::$aliases private property 1
Command::$application private property
Command::$code private property
Command::$definition private property
Command::$description private property 1
Command::$fullDefinition private property
Command::$help private property
Command::$helperSet private property
Command::$hidden private property
Command::$ignoreValidationErrors private property 2
Command::$name private property
Command::$processTitle private property
Command::$synopsis private property
Command::$usages private property
Command::addArgument public function Adds an argument. 2
Command::addOption public function Adds an option. 2
Command::addUsage public function Add a command usage example, it&#039;ll be prefixed with the command name. 2
Command::FAILURE public constant
Command::getAliases public function Returns the aliases for the command.
Command::getDefaultDescription public static function
Command::getDefaultName public static function
Command::getDefinition public function Gets the InputDefinition attached to this Command. 2
Command::getDescription public function Returns the description for the command.
Command::getHelp public function Returns the help for the command. 2
Command::getHelper public function Gets a helper instance by name. 2
Command::getHelperSet public function Gets the helper set. 1
Command::getName public function Returns the command name.
Command::getNativeDefinition public function Gets the InputDefinition to be used to create representations of this Command. 2
Command::getProcessedHelp public function Returns the processed help for the command replacing the %command.name% and
%command.full_name% patterns with the real values dynamically.
2
Command::getSynopsis public function Returns the synopsis for the command. 2
Command::getUsages public function Returns alternative usages of the command. 2
Command::ignoreValidationErrors public function Ignores validation errors. 2
Command::interact protected function Interacts with the user. 5
Command::INVALID public constant
Command::isEnabled public function Checks whether the command is enabled or not in the current environment. 2
Command::isHidden public function
Command::mergeApplicationDefinition public function Merges the application definition with the command definition. 2
Command::run public function Runs the command. 4
Command::setAliases public function Sets the aliases for the command.
Command::setApplication public function 2
Command::setCode public function Sets the code to execute when running this command. 2
Command::setDefinition public function Sets an array of argument and option instances. 2
Command::setDescription public function Sets the description for the command.
Command::setHelp public function Sets the help for the command. 2
Command::setHelperSet public function 2
Command::setHidden public function
Command::setName public function Sets the name of the command.
Command::setProcessTitle public function Sets the process title of the command. 2
Command::SUCCESS public constant
Command::validateName private function Validates a command name.
Command::__construct public function 15
CompletionTrait::requireComposer abstract public function
CompletionTrait::suggestAvailablePackage private function Suggest package names available on all configured repositories.
CompletionTrait::suggestAvailablePackageInclPlatform private function Suggest package names available on all configured repositories or
platform packages from the ones available on the currently-running PHP
CompletionTrait::suggestInstalledPackage private function Suggest package names from installed.
CompletionTrait::suggestInstalledPackageTypes private function Suggest package names from installed.
CompletionTrait::suggestPlatformPackage private function Suggest platform packages from the ones available on the currently-running PHP
CompletionTrait::suggestPreferInstall private function Suggestion values for &quot;prefer-install&quot; option
CompletionTrait::suggestRootRequirement private function Suggest package names from root requirements.
RemoveCommand::configure protected function Overrides Command::configure
RemoveCommand::execute protected function Overrides Command::execute
RSS feed
Powered by Drupal