ThemeUninstallCommand.php 12.3 KB
Newer Older
Ketan's avatar
Ketan committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 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 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 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 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 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 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387
<?php
/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

namespace Magento\Theme\Console\Command;

use Magento\Framework\App\Cache;
use Magento\Framework\App\Console\MaintenanceModeEnabler;
use Magento\Framework\App\ObjectManager;
use Magento\Framework\App\MaintenanceMode;
use Magento\Framework\App\State\CleanupFiles;
use Magento\Framework\Composer\ComposerInformation;
use Magento\Framework\Composer\DependencyChecker;
use Magento\Theme\Model\Theme\Data\Collection;
use Magento\Theme\Model\Theme\ThemePackageInfo;
use Magento\Theme\Model\Theme\ThemeUninstaller;
use Magento\Theme\Model\Theme\ThemeDependencyChecker;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Input\InputArgument;
use Magento\Framework\Setup\BackupRollbackFactory;
use Magento\Theme\Model\ThemeValidator;

/**
 * Command for uninstalling theme and backup-code feature
 *
 * @SuppressWarnings(PHPMD.CouplingBetweenObjects)
 * @SuppressWarnings(PHPMD.ExcessiveParameterList)
 */
class ThemeUninstallCommand extends Command
{
    /**
     * Names of input arguments or options
     */
    const INPUT_KEY_BACKUP_CODE = 'backup-code';
    const INPUT_KEY_THEMES = 'theme';
    const INPUT_KEY_CLEAR_STATIC_CONTENT = 'clear-static-content';

    /**
     * Composer general dependency checker
     *
     * @var DependencyChecker
     */
    private $dependencyChecker;

    /**
     * Root composer.json information
     *
     * @var ComposerInformation
     */
    private $composer;

    /**
     * Theme collection in filesystem
     *
     * @var Collection
     */
    private $themeCollection;

    /**
     * System cache model
     *
     * @var Cache
     */
    private $cache;

    /**
     * Cleaning up application state service
     *
     * @var CleanupFiles
     */
    private $cleanupFiles;

    /**
     * BackupRollback factory
     *
     * @var BackupRollbackFactory
     */
    private $backupRollbackFactory;

    /**
     * Theme Validator
     *
     * @var ThemeValidator
     */
    private $themeValidator;

    /**
     * Package name finder
     *
     * @var ThemePackageInfo
     */
    private $themePackageInfo;

    /**
     * Theme Uninstaller
     *
     * @var ThemeUninstaller
     */
    private $themeUninstaller;

    /**
     * Theme Dependency Checker
     *
     * @var ThemeDependencyChecker
     */
    private $themeDependencyChecker;

    /**
     * @var MaintenanceModeEnabler
     */
    private $maintenanceModeEnabler;

    /**
     * Constructor
     *
     * @param Cache $cache
     * @param CleanupFiles $cleanupFiles
     * @param ComposerInformation $composer
     * @param MaintenanceMode $maintenanceMode deprecated, use $maintenanceModeEnabler instead
     * @param DependencyChecker $dependencyChecker
     * @param Collection $themeCollection
     * @param BackupRollbackFactory $backupRollbackFactory
     * @param ThemeValidator $themeValidator
     * @param ThemePackageInfo $themePackageInfo
     * @param ThemeUninstaller $themeUninstaller
     * @param ThemeDependencyChecker $themeDependencyChecker
     * @param MaintenanceModeEnabler $maintenanceModeEnabler
     *
     * @SuppressWarnings(PHPMD.UnusedFormalParameter)
     */
    public function __construct(
        Cache $cache,
        CleanupFiles $cleanupFiles,
        ComposerInformation $composer,
        MaintenanceMode $maintenanceMode,
        DependencyChecker $dependencyChecker,
        Collection $themeCollection,
        BackupRollbackFactory $backupRollbackFactory,
        ThemeValidator $themeValidator,
        ThemePackageInfo $themePackageInfo,
        ThemeUninstaller $themeUninstaller,
        ThemeDependencyChecker $themeDependencyChecker,
        MaintenanceModeEnabler $maintenanceModeEnabler = null
    ) {
        $this->cache = $cache;
        $this->cleanupFiles = $cleanupFiles;
        $this->composer = $composer;
        $this->dependencyChecker = $dependencyChecker;
        $this->themeCollection = $themeCollection;
        $this->backupRollbackFactory = $backupRollbackFactory;
        $this->themeValidator = $themeValidator;
        $this->themePackageInfo = $themePackageInfo;
        $this->themeUninstaller = $themeUninstaller;
        $this->themeDependencyChecker = $themeDependencyChecker;
        $this->maintenanceModeEnabler =
            $maintenanceModeEnabler ?: ObjectManager::getInstance()->get(MaintenanceModeEnabler::class);
        parent::__construct();
    }

    /**
     * {@inheritdoc}
     */
    protected function configure()
    {
        $this->setName('theme:uninstall');
        $this->setDescription('Uninstalls theme');
        $this->addOption(
            self::INPUT_KEY_BACKUP_CODE,
            null,
            InputOption::VALUE_NONE,
            'Take code backup (excluding temporary files)'
        );
        $this->addArgument(
            self::INPUT_KEY_THEMES,
            InputArgument::IS_ARRAY | InputArgument::REQUIRED,
            'Path of the theme. Theme path should be specified as full path which is area/vendor/name.'
            . ' For example, frontend/Magento/blank'
        );
        $this->addOption(
            self::INPUT_KEY_CLEAR_STATIC_CONTENT,
            'c',
            InputOption::VALUE_NONE,
            'Clear generated static view files.'
        );
        parent::configure();
    }

    /**
     * {@inheritdoc}
     */
    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $messages = [];
        $themePaths = $input->getArgument(self::INPUT_KEY_THEMES);
        $messages = array_merge($messages, $this->validate($themePaths));
        if (!empty($messages)) {
            $output->writeln($messages);
            // we must have an exit code higher than zero to indicate something was wrong
            return \Magento\Framework\Console\Cli::RETURN_FAILURE;
        }
        $messages = array_merge(
            $messages,
            $this->themeValidator->validateIsThemeInUse($themePaths),
            $this->themeDependencyChecker->checkChildTheme($themePaths),
            $this->checkDependencies($themePaths)
        );
        if (!empty($messages)) {
            $output->writeln(
                '<error>Unable to uninstall. Please resolve the following issues:</error>'
                . PHP_EOL . implode(PHP_EOL, $messages)
            );
            // we must have an exit code higher than zero to indicate something was wrong
            return \Magento\Framework\Console\Cli::RETURN_FAILURE;
        }

        $result = $this->maintenanceModeEnabler->executeInMaintenanceMode(
            function () use ($input, $output, $themePaths) {
                try {
                    if ($input->getOption(self::INPUT_KEY_BACKUP_CODE)) {
                        $time = time();
                        $codeBackup = $this->backupRollbackFactory->create($output);
                        $codeBackup->codeBackup($time);
                    }

                    $this->themeUninstaller->uninstallRegistry($output, $themePaths);
                    $this->themeUninstaller->uninstallCode($output, $themePaths);

                    $this->cleanup($input, $output);
                    return \Magento\Framework\Console\Cli::RETURN_SUCCESS;
                } catch (\Exception $e) {
                    $output->writeln('<error>' . $e->getMessage() . '</error>');
                    $output->writeln('<error>Please disable maintenance mode after you resolved above issues</error>');
                    // we must have an exit code higher than zero to indicate something was wrong
                    return \Magento\Framework\Console\Cli::RETURN_FAILURE;
                }
            },
            $output,
            true
        );

        return $result;
    }

    /**
     * Validate given full theme paths
     *
     * @param string[] $themePaths
     * @return string[]
     */
    private function validate($themePaths)
    {
        $messages = [];

        $incorrectThemes = $this->getIncorrectThemes($themePaths);
        if (!empty($incorrectThemes)) {
            $text = 'Theme path should be specified as full path which is area/vendor/name.';
            $messages[] = '<error>Incorrect theme(s) format: ' . implode(', ', $incorrectThemes)
                . '. ' . $text . '</error>';
            return $messages;
        }

        $unknownPackages = $this->getUnknownPackages($themePaths);
        $unknownThemes = $this->getUnknownThemes($themePaths);

        $unknownPackages = array_diff($unknownPackages, $unknownThemes);
        if (!empty($unknownPackages)) {
            $text = count($unknownPackages) > 1 ?
                ' are not installed Composer packages' : ' is not an installed Composer package';
            $messages[] = '<error>' . implode(', ', $unknownPackages) . $text . '</error>';
        }

        if (!empty($unknownThemes)) {
            $messages[] = '<error>Unknown theme(s): ' . implode(', ', $unknownThemes) . '</error>';
        }

        return $messages;
    }

    /**
     * Retrieve list of themes with wrong name format
     *
     * @param string[] $themePaths
     * @return string[]
     */
    protected function getIncorrectThemes($themePaths)
    {
        $result = [];
        foreach ($themePaths as $themePath) {
            if (!preg_match('/^[^\/]+\/[^\/]+\/[^\/]+$/', $themePath)) {
                $result[] = $themePath;
                continue;
            }
        }
        return $result;
    }

    /**
     * Retrieve list of unknown packages
     *
     * @param string[] $themePaths
     * @return string[]
     */
    protected function getUnknownPackages($themePaths)
    {
        $installedPackages = $this->composer->getRootRequiredPackages();

        $result = [];
        foreach ($themePaths as $themePath) {
            if (array_search($this->themePackageInfo->getPackageName($themePath), $installedPackages) === false) {
                $result[] = $themePath;
            }
        }
        return $result;
    }

    /**
     * Retrieve list of unknown themes
     *
     * @param string[] $themePaths
     * @return string[]
     */
    protected function getUnknownThemes($themePaths)
    {
        $result = [];
        foreach ($themePaths as $themePath) {
            if (!$this->themeCollection->hasTheme($this->themeCollection->getThemeByFullPath($themePath))) {
                $result[] = $themePath;
            }
        }
        return $result;
    }

    /**
     * Check dependencies to given full theme paths
     *
     * @param string[] $themePaths
     * @return string[]
     */
    private function checkDependencies($themePaths)
    {
        $messages = [];
        $packageToPath = [];
        foreach ($themePaths as $themePath) {
            $packageToPath[$this->themePackageInfo->getPackageName($themePath)] = $themePath;
        }
        $dependencies = $this->dependencyChecker->checkDependencies(array_keys($packageToPath), true);
        foreach ($dependencies as $package => $dependingPackages) {
            if (!empty($dependingPackages)) {
                $messages[] =
                    '<error>' . $packageToPath[$package] .
                    " has the following dependent package(s):</error>" .
                    PHP_EOL . "\t<error>" . implode('</error>' . PHP_EOL . "\t<error>", $dependingPackages)
                    . "</error>";
            }
        }
        return $messages;
    }

    /**
     * Cleanup after updated modules status
     *
     * @param InputInterface $input
     * @param OutputInterface $output
     * @return void
     */
    private function cleanup(InputInterface $input, OutputInterface $output)
    {
        $this->cache->clean();
        $output->writeln('<info>Cache cleared successfully.</info>');

        if ($input->getOption(self::INPUT_KEY_CLEAR_STATIC_CONTENT)) {
            $this->cleanupFiles->clearMaterializedViewFiles();
            $output->writeln('<info>Generated static view files cleared successfully.</info>');
        } else {
            $output->writeln(
                '<error>Alert: Generated static view files were not cleared.'
                . ' You can clear them using the --' . self::INPUT_KEY_CLEAR_STATIC_CONTENT . ' option.'
                . ' Failure to clear static view files might cause display issues in the Admin and storefront.</error>'
            );
        }
    }
}