InstallCommand.php 14.1 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 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436
<?php
/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */
declare(strict_types=1);

namespace Magento\Setup\Console\Command;

use Magento\Deploy\Console\Command\App\ConfigImportCommand;
use Magento\Framework\Setup\Declaration\Schema\DryRunLogger;
use Magento\Framework\Setup\Declaration\Schema\OperationsExecutor;
use Magento\Framework\Setup\Declaration\Schema\Request;
use Magento\Setup\Model\AdminAccount;
use Magento\Setup\Model\ConfigModel;
use Magento\Setup\Model\InstallerFactory;
use Magento\Framework\Setup\ConsoleLogger;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Input\ArrayInput;
use Symfony\Component\Console\Question\Question;
use Symfony\Component\Console\Question\ChoiceQuestion;
use Symfony\Component\Console\Helper\QuestionHelper;

/**
 * Command to install Magento application
 * @SuppressWarnings(PHPMD.CouplingBetweenObjects)
 */
class InstallCommand extends AbstractSetupCommand
{
    /**
     * Parameter indicating command whether to cleanup database in the install routine
     */
    const INPUT_KEY_CLEANUP_DB = 'cleanup-database';

    /**
     * Parameter to specify an order_increment_prefix
     */
    const INPUT_KEY_SALES_ORDER_INCREMENT_PREFIX = 'sales-order-increment-prefix';

    /**
     * Parameter indicating command whether to install Sample Data
     */
    const INPUT_KEY_USE_SAMPLE_DATA = 'use-sample-data';

    /**
     * List of comma-separated module names. That must be enabled during installation.
     * Available magic param all.
     */
    const INPUT_KEY_ENABLE_MODULES = 'enable-modules';

    /**
     * List of comma-separated module names. That must be avoided during installation.
     * List of comma-separated module names. That must be avoided during installation.
     * Available magic param all.
     */
    const INPUT_KEY_DISABLE_MODULES = 'disable-modules';

    /**
     * If this flag is enabled, than all your old scripts with format:
     * InstallSchema, UpgradeSchema will be converted to new db_schema.xml format.
     */
    const CONVERT_OLD_SCRIPTS_KEY = 'convert-old-scripts';

    /**
     * Parameter indicating command for interactive setup
     */
    const INPUT_KEY_INTERACTIVE_SETUP = 'interactive';

    /**
     * Parameter indicating command shortcut for interactive setup
     */
    const INPUT_KEY_INTERACTIVE_SETUP_SHORTCUT = 'i';

    /**
     * Parameter says that in this mode all destructive operations, like column removal will be dumped
     */
    const INPUT_KEY_SAFE_INSTALLER_MODE = 'safe-mode';

    /**
     * Parameter allows to restore data, that was dumped with safe mode before
     */
    const INPUT_KEY_DATA_RESTORE = 'data-restore';

    /**
     * Regex for sales_order_increment_prefix validation.
     */
    const SALES_ORDER_INCREMENT_PREFIX_RULE = '/^.{0,20}$/';

    /**
     * Installer service factory
     *
     * @var InstallerFactory
     */
    private $installerFactory;

    /**
     * @var ConfigModel
     */
    protected $configModel;

    /**
     * @var InstallStoreConfigurationCommand
     */
    protected $userConfig;

    /**
     * @var AdminUserCreateCommand
     */
    protected $adminUser;

    /**
     * Constructor
     *
     * @param InstallerFactory $installerFactory
     * @param ConfigModel $configModel
     * @param InstallStoreConfigurationCommand $userConfig
     * @param AdminUserCreateCommand $adminUser
     */
    public function __construct(
        InstallerFactory $installerFactory,
        ConfigModel $configModel,
        InstallStoreConfigurationCommand $userConfig,
        AdminUserCreateCommand $adminUser
    ) {
        $this->installerFactory = $installerFactory;
        $this->configModel = $configModel;
        $this->userConfig = $userConfig;
        $this->adminUser = $adminUser;
        parent::__construct();
    }

    /**
     * @inheritdoc
     */
    protected function configure()
    {
        $inputOptions = $this->configModel->getAvailableOptions();
        $inputOptions = array_merge($inputOptions, $this->userConfig->getOptionsList());
        $inputOptions = array_merge($inputOptions, $this->adminUser->getOptionsList(InputOption::VALUE_OPTIONAL));
        $inputOptions = array_merge($inputOptions, [
            new InputOption(
                self::INPUT_KEY_CLEANUP_DB,
                null,
                InputOption::VALUE_NONE,
                'Cleanup the database before installation'
            ),
            new InputOption(
                self::INPUT_KEY_SALES_ORDER_INCREMENT_PREFIX,
                null,
                InputOption::VALUE_REQUIRED,
                'Sales order number prefix'
            ),
            new InputOption(
                self::INPUT_KEY_USE_SAMPLE_DATA,
                null,
                InputOption::VALUE_NONE,
                'Use sample data'
            ),
            new InputOption(
                self::INPUT_KEY_ENABLE_MODULES,
                null,
                InputOption::VALUE_OPTIONAL,
                'List of comma-separated module names. That must be included during installation. '
                . 'Available magic param "all".'
            ),
            new InputOption(
                self::INPUT_KEY_DISABLE_MODULES,
                null,
                InputOption::VALUE_OPTIONAL,
                'List of comma-separated module names. That must be avoided during installation. '
                . 'Available magic param "all".'
            ),
            new InputOption(
                self::CONVERT_OLD_SCRIPTS_KEY,
                null,
                InputOption::VALUE_OPTIONAL,
                'Allows to convert old scripts (InstallSchema, UpgradeSchema) to db_schema.xml format',
                false
            ),
            new InputOption(
                self::INPUT_KEY_INTERACTIVE_SETUP,
                self::INPUT_KEY_INTERACTIVE_SETUP_SHORTCUT,
                InputOption::VALUE_NONE,
                'Interactive Magento installation'
            ),
            new InputOption(
                OperationsExecutor::KEY_SAFE_MODE,
                null,
                InputOption::VALUE_OPTIONAL,
                'Safe installation of Magento with dumps on destructive operations, like column removal'
            ),
            new InputOption(
                OperationsExecutor::KEY_DATA_RESTORE,
                null,
                InputOption::VALUE_OPTIONAL,
                'Restore removed data from dumps'
            ),
            new InputOption(
                DryRunLogger::INPUT_KEY_DRY_RUN_MODE,
                null,
                InputOption::VALUE_OPTIONAL,
                'Magento Installation will be run in dry-run mode',
                false
            ),
        ]);
        $this->setName('setup:install')
            ->setDescription('Installs the Magento application')
            ->setDefinition($inputOptions);
        parent::configure();
    }

    /**
     * @inheritdoc
     */
    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $consoleLogger = new ConsoleLogger($output);
        $installer = $this->installerFactory->create($consoleLogger);
        $installer->install($input->getOptions());

        $importConfigCommand = $this->getApplication()->find(ConfigImportCommand::COMMAND_NAME);
        $arrayInput = new ArrayInput([]);
        $arrayInput->setInteractive($input->isInteractive());
        $importConfigCommand->run($arrayInput, $output);
    }

    /**
     * @inheritdoc
     */
    protected function initialize(InputInterface $input, OutputInterface $output)
    {
        $inputOptions = $input->getOptions();

        if ($inputOptions['interactive']) {
            $configOptionsToValidate = $this->interactiveQuestions($input, $output);
        } else {
            $configOptionsToValidate = [];
            foreach ($this->configModel->getAvailableOptions() as $option) {
                if (array_key_exists($option->getName(), $inputOptions)) {
                    $configOptionsToValidate[$option->getName()] = $inputOptions[$option->getName()];
                }
            }
        }

        if ($inputOptions['interactive']) {
            $command = '';
            foreach ($configOptionsToValidate as $key => $value) {
                $command .= " --{$key}={$value}";
            }
            $output->writeln("<comment>Try re-running command: php bin/magento setup:install{$command}</comment>");
        }

        $errors = $this->configModel->validate($configOptionsToValidate);
        $errors = array_merge($errors, $this->validateAdmin($input));
        $errors = array_merge($errors, $this->validate($input));
        $errors = array_merge($errors, $this->userConfig->validate($input));

        if (!empty($errors)) {
            foreach ($errors as $error) {
                $output->writeln("<error>$error</error>");
            }
            throw new \InvalidArgumentException('Parameter validation failed');
        }
    }

    /**
     * Validate sales_order_increment_prefix value
     *
     * It will save the value which discarding characters after 20th to the database so it should be
     * validated in advance.
     *
     * @param InputInterface $input
     * @return string[] Array of error messages
     */
    public function validate(InputInterface $input) : array
    {
        $errors = [];
        $value = $input->getOption(self::INPUT_KEY_SALES_ORDER_INCREMENT_PREFIX);
        if (preg_match(self::SALES_ORDER_INCREMENT_PREFIX_RULE, (string) $value) != 1) {
            $errors[] = 'Validation failed, ' . self::INPUT_KEY_SALES_ORDER_INCREMENT_PREFIX
                . ' must be 20 characters or less';
        }
        return $errors;
    }

    /**
     * Runs interactive questions
     *
     * It will ask users for interactive questionst regarding setup configuration.
     *
     * @param InputInterface $input
     * @param OutputInterface $output
     * @return string[] Array of inputs
     */
    private function interactiveQuestions(InputInterface $input, OutputInterface $output) : array
    {
        $helper = $this->getHelper('question');
        $configOptionsToValidate = [];

        foreach ($this->configModel->getAvailableOptions() as $option) {
            $configOptionsToValidate[$option->getName()] = $this->askQuestion(
                $input,
                $output,
                $helper,
                $option,
                true
            );
        }

        $output->writeln("");

        foreach ($this->userConfig->getOptionsList() as $option) {
            $configOptionsToValidate[$option->getName()] = $this->askQuestion(
                $input,
                $output,
                $helper,
                $option
            );
        }

        $output->writeln("");

        foreach ($this->adminUser->getOptionsList(InputOption::VALUE_OPTIONAL) as $option) {
            $configOptionsToValidate[$option->getName()] = $this->askQuestion(
                $input,
                $output,
                $helper,
                $option
            );
        }

        $output->writeln("");

        $returnConfigOptionsToValidate = [];
        foreach ($configOptionsToValidate as $key => $value) {
            if ($value != '') {
                $returnConfigOptionsToValidate[$key] = $value;
            }
        }

        return $returnConfigOptionsToValidate;
    }

    /**
     * Runs interactive questions
     *
     * It will ask users for interactive questionst regarding setup configuration.
     *
     * @param InputInterface $input
     * @param OutputInterface $output
     * @param QuestionHelper $helper
     * @param TextConfigOption|FlagConfigOption\SelectConfigOption $option
     * @param Boolean $validateInline
     * @return string[] Array of inputs
     */
    private function askQuestion(
        InputInterface $input,
        OutputInterface $output,
        QuestionHelper $helper,
        $option,
        $validateInline = false
    ) {
        if ($option instanceof \Magento\Framework\Setup\Option\SelectConfigOption) {
            if ($option->isValueRequired()) {
                $question = new ChoiceQuestion(
                    $option->getDescription() . '? ',
                    $option->getSelectOptions(),
                    $option->getDefault()
                );
            } else {
                $question = new ChoiceQuestion(
                    $option->getDescription() . ' [optional]? ',
                    $option->getSelectOptions(),
                    $option->getDefault()
                );
            }
        } else {
            if ($option->isValueRequired()) {
                $question = new Question(
                    $option->getDescription() . '? ',
                    $option->getDefault()
                );
            } else {
                $question = new Question(
                    $option->getDescription() . ' [optional]? ',
                    $option->getDefault()
                );
            }
        }

        $question->setValidator(function ($answer) use ($option, $validateInline) {

            if ($option instanceof \Magento\Framework\Setup\Option\SelectConfigOption) {
                $answer = $option->getSelectOptions()[$answer];
            }

            if ($answer == null) {
                $answer = '';
            } else {
                $answer = trim($answer);
            }

            if ($validateInline) {
                $option->validate($answer);
            }

            return $answer;
        });

        $value = $helper->ask($input, $output, $question);

        return $value;
    }

    /**
     * Performs validation of admin options if at least one of them was set.
     *
     * @param InputInterface $input
     * @return array
     */
    private function validateAdmin(InputInterface $input): array
    {
        if ($input->getOption(AdminAccount::KEY_FIRST_NAME)
            || $input->getOption(AdminAccount::KEY_LAST_NAME)
            || $input->getOption(AdminAccount::KEY_EMAIL)
            || $input->getOption(AdminAccount::KEY_USER)
            || $input->getOption(AdminAccount::KEY_PASSWORD)
        ) {
            return $this->adminUser->validate($input);
        }

        return [];
    }
}