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

Breadcrumb

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

function InitCommand::interact

@inheritDoc

Return value

void

Overrides Command::interact

File

vendor/composer/composer/src/Composer/Command/InitCommand.php, line 220

Class

InitCommand
@author Justin Rainbow <justin.rainbow@gmail.com> @author Jordi Boggiano <j.boggiano@seld.be>

Namespace

Composer\Command

Code

protected function interact(InputInterface $input, OutputInterface $output) {
    $git = $this->getGitConfig();
    $io = $this->getIO();
    
    /** @var FormatterHelper $formatter */
    $formatter = $this->getHelperSet()
        ->get('formatter');
    // initialize repos if configured
    $repositories = $input->getOption('repository');
    if (count($repositories) > 0) {
        $config = Factory::createConfig($io);
        $io->loadConfiguration($config);
        $repoManager = RepositoryFactory::manager($io, $config);
        $repos = [
            new PlatformRepository(),
        ];
        $createDefaultPackagistRepo = true;
        foreach ($repositories as $repo) {
            $repoConfig = RepositoryFactory::configFromString($io, $config, $repo, true);
            if (isset($repoConfig['packagist']) && $repoConfig === [
                'packagist' => false,
            ] || isset($repoConfig['packagist.org']) && $repoConfig === [
                'packagist.org' => false,
            ]) {
                $createDefaultPackagistRepo = false;
                continue;
            }
            $repos[] = RepositoryFactory::createRepo($io, $config, $repoConfig, $repoManager);
        }
        if ($createDefaultPackagistRepo) {
            $repos[] = RepositoryFactory::createRepo($io, $config, [
                'type' => 'composer',
                'url' => 'https://repo.packagist.org',
            ], $repoManager);
        }
        $this->repos = new CompositeRepository($repos);
        unset($repos, $config, $repositories);
    }
    $io->writeError([
        '',
        $formatter->formatBlock('Welcome to the Composer config generator', 'bg=blue;fg=white', true),
        '',
    ]);
    // namespace
    $io->writeError([
        '',
        'This command will guide you through creating your composer.json config.',
        '',
    ]);
    $cwd = realpath(".");
    $name = $input->getOption('name');
    if (null === $name) {
        $name = basename($cwd);
        $name = Preg::replace('{(?:([a-z])([A-Z])|([A-Z])([A-Z][a-z]))}', '\\1\\3-\\2\\4', $name);
        $name = strtolower($name);
        if (!empty($_SERVER['COMPOSER_DEFAULT_VENDOR'])) {
            $name = $_SERVER['COMPOSER_DEFAULT_VENDOR'] . '/' . $name;
        }
        elseif (isset($git['github.user'])) {
            $name = $git['github.user'] . '/' . $name;
        }
        elseif (!empty($_SERVER['USERNAME'])) {
            $name = $_SERVER['USERNAME'] . '/' . $name;
        }
        elseif (!empty($_SERVER['USER'])) {
            $name = $_SERVER['USER'] . '/' . $name;
        }
        elseif (get_current_user()) {
            $name = get_current_user() . '/' . $name;
        }
        else {
            // package names must be in the format foo/bar
            $name .= '/' . $name;
        }
        $name = strtolower($name);
    }
    $name = $io->askAndValidate('Package name (<vendor>/<name>) [<comment>' . $name . '</comment>]: ', static function ($value) use ($name) {
        if (null === $value) {
            return $name;
        }
        if (!Preg::isMatch('{^[a-z0-9_.-]+/[a-z0-9_.-]+$}D', $value)) {
            throw new \InvalidArgumentException('The package name ' . $value . ' is invalid, it should be lowercase and have a vendor name, a forward slash, and a package name, matching: [a-z0-9_.-]+/[a-z0-9_.-]+');
        }
        return $value;
    }, null, $name);
    $input->setOption('name', $name);
    $description = $input->getOption('description') ?: null;
    $description = $io->ask('Description [<comment>' . $description . '</comment>]: ', $description);
    $input->setOption('description', $description);
    if (null === ($author = $input->getOption('author'))) {
        if (!empty($_SERVER['COMPOSER_DEFAULT_AUTHOR'])) {
            $author_name = $_SERVER['COMPOSER_DEFAULT_AUTHOR'];
        }
        elseif (isset($git['user.name'])) {
            $author_name = $git['user.name'];
        }
        if (!empty($_SERVER['COMPOSER_DEFAULT_EMAIL'])) {
            $author_email = $_SERVER['COMPOSER_DEFAULT_EMAIL'];
        }
        elseif (isset($git['user.email'])) {
            $author_email = $git['user.email'];
        }
        if (isset($author_name, $author_email)) {
            $author = sprintf('%s <%s>', $author_name, $author_email);
        }
    }
    $author = $io->askAndValidate('Author [' . (is_string($author) ? '<comment>' . $author . '</comment>, ' : '') . 'n to skip]: ', function ($value) use ($author) {
        if ($value === 'n' || $value === 'no') {
            return;
        }
        $value = $value ?: $author;
        $author = $this->parseAuthorString($value ?? '');
        if ($author['email'] === null) {
            return $author['name'];
        }
        return sprintf('%s <%s>', $author['name'], $author['email']);
    }, null, $author);
    $input->setOption('author', $author);
    $minimumStability = $input->getOption('stability') ?: null;
    $minimumStability = $io->askAndValidate('Minimum Stability [<comment>' . $minimumStability . '</comment>]: ', static function ($value) use ($minimumStability) {
        if (null === $value) {
            return $minimumStability;
        }
        if (!isset(BasePackage::STABILITIES[$value])) {
            throw new \InvalidArgumentException('Invalid minimum stability "' . $value . '". Must be empty or one of: ' . implode(', ', array_keys(BasePackage::STABILITIES)));
        }
        return $value;
    }, null, $minimumStability);
    $input->setOption('stability', $minimumStability);
    $type = $input->getOption('type');
    $type = $io->ask('Package Type (e.g. library, project, metapackage, composer-plugin) [<comment>' . $type . '</comment>]: ', $type);
    if ($type === '' || $type === false) {
        $type = null;
    }
    $input->setOption('type', $type);
    if (null === ($license = $input->getOption('license'))) {
        if (!empty($_SERVER['COMPOSER_DEFAULT_LICENSE'])) {
            $license = $_SERVER['COMPOSER_DEFAULT_LICENSE'];
        }
    }
    $license = $io->ask('License [<comment>' . $license . '</comment>]: ', $license);
    $spdx = new SpdxLicenses();
    if (null !== $license && !$spdx->validate($license) && $license !== 'proprietary') {
        throw new \InvalidArgumentException('Invalid license provided: ' . $license . '. Only SPDX license identifiers (https://spdx.org/licenses/) or "proprietary" are accepted.');
    }
    $input->setOption('license', $license);
    $io->writeError([
        '',
        'Define your dependencies.',
        '',
    ]);
    // prepare to resolve dependencies
    $repos = $this->getRepos();
    $preferredStability = $minimumStability ?: 'stable';
    $platformRepo = null;
    if ($repos instanceof CompositeRepository) {
        foreach ($repos->getRepositories() as $candidateRepo) {
            if ($candidateRepo instanceof PlatformRepository) {
                $platformRepo = $candidateRepo;
                break;
            }
        }
    }
    $question = 'Would you like to define your dependencies (require) interactively [<comment>yes</comment>]? ';
    $require = $input->getOption('require');
    $requirements = [];
    if (count($require) > 0 || $io->askConfirmation($question)) {
        $requirements = $this->determineRequirements($input, $output, $require, $platformRepo, $preferredStability);
    }
    $input->setOption('require', $requirements);
    $question = 'Would you like to define your dev dependencies (require-dev) interactively [<comment>yes</comment>]? ';
    $requireDev = $input->getOption('require-dev');
    $devRequirements = [];
    if (count($requireDev) > 0 || $io->askConfirmation($question)) {
        $devRequirements = $this->determineRequirements($input, $output, $requireDev, $platformRepo, $preferredStability);
    }
    $input->setOption('require-dev', $devRequirements);
    // --autoload - input and validation
    $autoload = $input->getOption('autoload') ?: 'src/';
    $namespace = $this->namespaceFromPackageName((string) $input->getOption('name'));
    $autoload = $io->askAndValidate('Add PSR-4 autoload mapping? Maps namespace "' . $namespace . '" to the entered relative path. [<comment>' . $autoload . '</comment>, n to skip]: ', static function ($value) use ($autoload) {
        if (null === $value) {
            return $autoload;
        }
        if ($value === 'n' || $value === 'no') {
            return;
        }
        $value = $value ?: $autoload;
        if (!Preg::isMatch('{^[^/][A-Za-z0-9\\-_/]+/$}', $value)) {
            throw new \InvalidArgumentException(sprintf('The src folder name "%s" is invalid. Please add a relative path with tailing forward slash. [A-Za-z0-9_-/]+/', $value));
        }
        return $value;
    }, null, $autoload);
    $input->setOption('autoload', $autoload);
}
RSS feed
Powered by Drupal