InitCommand.php 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827
  1. <?php
  2. /*
  3. * This file is part of Composer.
  4. *
  5. * (c) Nils Adermann <naderman@naderman.de>
  6. * Jordi Boggiano <j.boggiano@seld.be>
  7. *
  8. * For the full copyright and license information, please view the LICENSE
  9. * file that was distributed with this source code.
  10. */
  11. namespace Composer\Command;
  12. use Composer\DependencyResolver\Pool;
  13. use Composer\Factory;
  14. use Composer\Json\JsonFile;
  15. use Composer\Package\BasePackage;
  16. use Composer\Package\Version\VersionParser;
  17. use Composer\Package\Version\VersionSelector;
  18. use Composer\Repository\CompositeRepository;
  19. use Composer\Repository\PlatformRepository;
  20. use Composer\Repository\RepositoryFactory;
  21. use Composer\Util\ProcessExecutor;
  22. use Symfony\Component\Console\Input\ArrayInput;
  23. use Symfony\Component\Console\Input\InputInterface;
  24. use Symfony\Component\Console\Input\InputOption;
  25. use Symfony\Component\Console\Output\OutputInterface;
  26. use Symfony\Component\Process\ExecutableFinder;
  27. use Symfony\Component\Process\Process;
  28. /**
  29. * @author Justin Rainbow <justin.rainbow@gmail.com>
  30. * @author Jordi Boggiano <j.boggiano@seld.be>
  31. */
  32. class InitCommand extends BaseCommand
  33. {
  34. /** @var CompositeRepository */
  35. protected $repos;
  36. /** @var array */
  37. private $gitConfig;
  38. /** @var Pool[] */
  39. private $pools;
  40. /**
  41. * {@inheritdoc}
  42. */
  43. protected function configure()
  44. {
  45. $this
  46. ->setName('init')
  47. ->setDescription('Creates a basic composer.json file in current directory.')
  48. ->setDefinition(array(
  49. new InputOption('name', null, InputOption::VALUE_REQUIRED, 'Name of the package'),
  50. new InputOption('description', null, InputOption::VALUE_REQUIRED, 'Description of package'),
  51. new InputOption('author', null, InputOption::VALUE_REQUIRED, 'Author name of package'),
  52. // new InputOption('version', null, InputOption::VALUE_NONE, 'Version of package'),
  53. new InputOption('type', null, InputOption::VALUE_OPTIONAL, 'Type of package (e.g. library, project, metapackage, composer-plugin)'),
  54. new InputOption('homepage', null, InputOption::VALUE_REQUIRED, 'Homepage of package'),
  55. new InputOption('require', null, InputOption::VALUE_IS_ARRAY | InputOption::VALUE_REQUIRED, 'Package to require with a version constraint, e.g. foo/bar:1.0.0 or foo/bar=1.0.0 or "foo/bar 1.0.0"'),
  56. new InputOption('require-dev', null, InputOption::VALUE_IS_ARRAY | InputOption::VALUE_REQUIRED, 'Package to require for development with a version constraint, e.g. foo/bar:1.0.0 or foo/bar=1.0.0 or "foo/bar 1.0.0"'),
  57. new InputOption('stability', 's', InputOption::VALUE_REQUIRED, 'Minimum stability (empty or one of: '.implode(', ', array_keys(BasePackage::$stabilities)).')'),
  58. new InputOption('license', 'l', InputOption::VALUE_REQUIRED, 'License of package'),
  59. new InputOption('repository', null, InputOption::VALUE_REQUIRED | InputOption::VALUE_IS_ARRAY, 'Add custom repositories, either by URL or using JSON arrays'),
  60. ))
  61. ->setHelp(
  62. <<<EOT
  63. The <info>init</info> command creates a basic composer.json file
  64. in the current directory.
  65. <info>php composer.phar init</info>
  66. Read more at https://getcomposer.org/doc/03-cli.md#init
  67. EOT
  68. )
  69. ;
  70. }
  71. /**
  72. * {@inheritdoc}
  73. */
  74. protected function execute(InputInterface $input, OutputInterface $output)
  75. {
  76. $io = $this->getIO();
  77. $whitelist = array('name', 'description', 'author', 'type', 'homepage', 'require', 'require-dev', 'stability', 'license');
  78. $options = array_filter(array_intersect_key($input->getOptions(), array_flip($whitelist)));
  79. if (isset($options['author'])) {
  80. $options['authors'] = $this->formatAuthors($options['author']);
  81. unset($options['author']);
  82. }
  83. $repositories = $input->getOption('repository');
  84. if ($repositories) {
  85. $config = Factory::createConfig($io);
  86. foreach ($repositories as $repo) {
  87. $options['repositories'][] = RepositoryFactory::configFromString($io, $config, $repo);
  88. }
  89. }
  90. if (isset($options['stability'])) {
  91. $options['minimum-stability'] = $options['stability'];
  92. unset($options['stability']);
  93. }
  94. $options['require'] = isset($options['require']) ? $this->formatRequirements($options['require']) : new \stdClass;
  95. if (array() === $options['require']) {
  96. $options['require'] = new \stdClass;
  97. }
  98. if (isset($options['require-dev'])) {
  99. $options['require-dev'] = $this->formatRequirements($options['require-dev']);
  100. if (array() === $options['require-dev']) {
  101. $options['require-dev'] = new \stdClass;
  102. }
  103. }
  104. $file = new JsonFile(Factory::getComposerFile());
  105. $json = $file->encode($options);
  106. if ($input->isInteractive()) {
  107. $io->writeError(array('', $json, ''));
  108. if (!$io->askConfirmation('Do you confirm generation [<comment>yes</comment>]? ', true)) {
  109. $io->writeError('<error>Command aborted</error>');
  110. return 1;
  111. }
  112. }
  113. $file->write($options);
  114. if ($input->isInteractive() && is_dir('.git')) {
  115. $ignoreFile = realpath('.gitignore');
  116. if (false === $ignoreFile) {
  117. $ignoreFile = realpath('.') . '/.gitignore';
  118. }
  119. if (!$this->hasVendorIgnore($ignoreFile)) {
  120. $question = 'Would you like the <info>vendor</info> directory added to your <info>.gitignore</info> [<comment>yes</comment>]? ';
  121. if ($io->askConfirmation($question, true)) {
  122. $this->addVendorIgnore($ignoreFile);
  123. }
  124. }
  125. }
  126. $question = 'Would you like to install dependencies now [<comment>yes</comment>]? ';
  127. if ($input->isInteractive() && $this->hasDependencies($options) && $io->askConfirmation($question, true)) {
  128. $this->installDependencies($output);
  129. }
  130. }
  131. /**
  132. * {@inheritdoc}
  133. */
  134. protected function interact(InputInterface $input, OutputInterface $output)
  135. {
  136. $git = $this->getGitConfig();
  137. $io = $this->getIO();
  138. $formatter = $this->getHelperSet()->get('formatter');
  139. // initialize repos if configured
  140. $repositories = $input->getOption('repository');
  141. if ($repositories) {
  142. $config = Factory::createConfig($io);
  143. $repos = array(new PlatformRepository);
  144. $createDefaultPackagistRepo = true;
  145. foreach ($repositories as $repo) {
  146. $repoConfig = RepositoryFactory::configFromString($io, $config, $repo);
  147. if (
  148. (isset($repoConfig['packagist']) && $repoConfig === array('packagist' => false))
  149. || (isset($repoConfig['packagist.org']) && $repoConfig === array('packagist.org' => false))
  150. ) {
  151. $createDefaultPackagistRepo = false;
  152. continue;
  153. }
  154. $repos[] = RepositoryFactory::createRepo($io, $config, $repoConfig);
  155. }
  156. if ($createDefaultPackagistRepo) {
  157. $repos[] = RepositoryFactory::createRepo($io, $config, array(
  158. 'type' => 'composer',
  159. 'url' => 'https://repo.packagist.org',
  160. ));
  161. }
  162. $this->repos = new CompositeRepository($repos);
  163. unset($repos, $config, $repositories);
  164. }
  165. $io->writeError(array(
  166. '',
  167. $formatter->formatBlock('Welcome to the Composer config generator', 'bg=blue;fg=white', true),
  168. '',
  169. ));
  170. // namespace
  171. $io->writeError(array(
  172. '',
  173. 'This command will guide you through creating your composer.json config.',
  174. '',
  175. ));
  176. $cwd = realpath(".");
  177. if (!$name = $input->getOption('name')) {
  178. $name = basename($cwd);
  179. $name = preg_replace('{(?:([a-z])([A-Z])|([A-Z])([A-Z][a-z]))}', '\\1\\3-\\2\\4', $name);
  180. $name = strtolower($name);
  181. if (!empty($_SERVER['COMPOSER_DEFAULT_VENDOR'])) {
  182. $name = $_SERVER['COMPOSER_DEFAULT_VENDOR'] . '/' . $name;
  183. } elseif (isset($git['github.user'])) {
  184. $name = $git['github.user'] . '/' . $name;
  185. } elseif (!empty($_SERVER['USERNAME'])) {
  186. $name = $_SERVER['USERNAME'] . '/' . $name;
  187. } elseif (!empty($_SERVER['USER'])) {
  188. $name = $_SERVER['USER'] . '/' . $name;
  189. } elseif (get_current_user()) {
  190. $name = get_current_user() . '/' . $name;
  191. } else {
  192. // package names must be in the format foo/bar
  193. $name .= '/' . $name;
  194. }
  195. $name = strtolower($name);
  196. } else {
  197. if (!preg_match('{^[a-z0-9_.-]+/[a-z0-9_.-]+$}D', $name)) {
  198. throw new \InvalidArgumentException(
  199. 'The package name '.$name.' 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_.-]+'
  200. );
  201. }
  202. }
  203. $name = $io->askAndValidate(
  204. 'Package name (<vendor>/<name>) [<comment>'.$name.'</comment>]: ',
  205. function ($value) use ($name) {
  206. if (null === $value) {
  207. return $name;
  208. }
  209. if (!preg_match('{^[a-z0-9_.-]+/[a-z0-9_.-]+$}D', $value)) {
  210. throw new \InvalidArgumentException(
  211. '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_.-]+'
  212. );
  213. }
  214. return $value;
  215. },
  216. null,
  217. $name
  218. );
  219. $input->setOption('name', $name);
  220. $description = $input->getOption('description') ?: false;
  221. $description = $io->ask(
  222. 'Description [<comment>'.$description.'</comment>]: ',
  223. $description
  224. );
  225. $input->setOption('description', $description);
  226. if (null === $author = $input->getOption('author')) {
  227. if (!empty($_SERVER['COMPOSER_DEFAULT_AUTHOR'])) {
  228. $author_name = $_SERVER['COMPOSER_DEFAULT_AUTHOR'];
  229. } elseif (isset($git['user.name'])) {
  230. $author_name = $git['user.name'];
  231. }
  232. if (!empty($_SERVER['COMPOSER_DEFAULT_EMAIL'])) {
  233. $author_email = $_SERVER['COMPOSER_DEFAULT_EMAIL'];
  234. } elseif (isset($git['user.email'])) {
  235. $author_email = $git['user.email'];
  236. }
  237. if (isset($author_name) && isset($author_email)) {
  238. $author = sprintf('%s <%s>', $author_name, $author_email);
  239. }
  240. }
  241. $self = $this;
  242. $author = $io->askAndValidate(
  243. 'Author [<comment>'.$author.'</comment>, n to skip]: ',
  244. function ($value) use ($self, $author) {
  245. if ($value === 'n' || $value === 'no') {
  246. return;
  247. }
  248. $value = $value ?: $author;
  249. $author = $self->parseAuthorString($value);
  250. return sprintf('%s <%s>', $author['name'], $author['email']);
  251. },
  252. null,
  253. $author
  254. );
  255. $input->setOption('author', $author);
  256. $minimumStability = $input->getOption('stability') ?: null;
  257. $minimumStability = $io->askAndValidate(
  258. 'Minimum Stability [<comment>'.$minimumStability.'</comment>]: ',
  259. function ($value) use ($minimumStability) {
  260. if (null === $value) {
  261. return $minimumStability;
  262. }
  263. if (!isset(BasePackage::$stabilities[$value])) {
  264. throw new \InvalidArgumentException(
  265. 'Invalid minimum stability "'.$value.'". Must be empty or one of: '.
  266. implode(', ', array_keys(BasePackage::$stabilities))
  267. );
  268. }
  269. return $value;
  270. },
  271. null,
  272. $minimumStability
  273. );
  274. $input->setOption('stability', $minimumStability);
  275. $type = $input->getOption('type') ?: false;
  276. $type = $io->ask(
  277. 'Package Type (e.g. library, project, metapackage, composer-plugin) [<comment>'.$type.'</comment>]: ',
  278. $type
  279. );
  280. $input->setOption('type', $type);
  281. if (null === $license = $input->getOption('license')) {
  282. if (!empty($_SERVER['COMPOSER_DEFAULT_LICENSE'])) {
  283. $license = $_SERVER['COMPOSER_DEFAULT_LICENSE'];
  284. }
  285. }
  286. $license = $io->ask(
  287. 'License [<comment>'.$license.'</comment>]: ',
  288. $license
  289. );
  290. $input->setOption('license', $license);
  291. $io->writeError(array('', 'Define your dependencies.', ''));
  292. // prepare to resolve dependencies
  293. $repos = $this->getRepos();
  294. $preferredStability = $minimumStability ?: 'stable';
  295. $phpVersion = $repos->findPackage('php', '*')->getPrettyVersion();
  296. $question = 'Would you like to define your dependencies (require) interactively [<comment>yes</comment>]? ';
  297. $require = $input->getOption('require');
  298. $requirements = array();
  299. if ($require || $io->askConfirmation($question, true)) {
  300. $requirements = $this->determineRequirements($input, $output, $require, $phpVersion, $preferredStability);
  301. }
  302. $input->setOption('require', $requirements);
  303. $question = 'Would you like to define your dev dependencies (require-dev) interactively [<comment>yes</comment>]? ';
  304. $requireDev = $input->getOption('require-dev');
  305. $devRequirements = array();
  306. if ($requireDev || $io->askConfirmation($question, true)) {
  307. $devRequirements = $this->determineRequirements($input, $output, $requireDev, $phpVersion, $preferredStability);
  308. }
  309. $input->setOption('require-dev', $devRequirements);
  310. }
  311. /**
  312. * @private
  313. * @param string $author
  314. * @return array
  315. */
  316. public function parseAuthorString($author)
  317. {
  318. if (preg_match('/^(?P<name>[- .,\p{L}\p{N}\p{Mn}\'’"()]+) <(?P<email>.+?)>$/u', $author, $match)) {
  319. if ($this->isValidEmail($match['email'])) {
  320. return array(
  321. 'name' => trim($match['name']),
  322. 'email' => $match['email'],
  323. );
  324. }
  325. }
  326. throw new \InvalidArgumentException(
  327. 'Invalid author string. Must be in the format: '.
  328. 'John Smith <john@example.com>'
  329. );
  330. }
  331. protected function findPackages($name)
  332. {
  333. return $this->getRepos()->search($name);
  334. }
  335. protected function getRepos()
  336. {
  337. if (!$this->repos) {
  338. $this->repos = new CompositeRepository(array_merge(
  339. array(new PlatformRepository),
  340. RepositoryFactory::defaultRepos($this->getIO())
  341. ));
  342. }
  343. return $this->repos;
  344. }
  345. final protected function determineRequirements(InputInterface $input, OutputInterface $output, $requires = array(), $phpVersion = null, $preferredStability = 'stable', $checkProvidedVersions = true, $fixed = false)
  346. {
  347. if ($requires) {
  348. $requires = $this->normalizeRequirements($requires);
  349. $result = array();
  350. $io = $this->getIO();
  351. foreach ($requires as $requirement) {
  352. if (!isset($requirement['version'])) {
  353. // determine the best version automatically
  354. list($name, $version) = $this->findBestVersionAndNameForPackage($input, $requirement['name'], $phpVersion, $preferredStability, null, null, $fixed);
  355. $requirement['version'] = $version;
  356. // replace package name from packagist.org
  357. $requirement['name'] = $name;
  358. $io->writeError(sprintf(
  359. 'Using version <info>%s</info> for <info>%s</info>',
  360. $requirement['version'],
  361. $requirement['name']
  362. ));
  363. } else {
  364. // check that the specified version/constraint exists before we proceed
  365. list($name, $version) = $this->findBestVersionAndNameForPackage($input, $requirement['name'], $phpVersion, $preferredStability, $checkProvidedVersions ? $requirement['version'] : null, 'dev', $fixed);
  366. // replace package name from packagist.org
  367. $requirement['name'] = $name;
  368. }
  369. $result[] = $requirement['name'] . ' ' . $requirement['version'];
  370. }
  371. return $result;
  372. }
  373. $versionParser = new VersionParser();
  374. $io = $this->getIO();
  375. while (null !== $package = $io->ask('Search for a package: ')) {
  376. $matches = $this->findPackages($package);
  377. if (count($matches)) {
  378. $exactMatch = null;
  379. $choices = array();
  380. foreach ($matches as $position => $foundPackage) {
  381. $abandoned = '';
  382. if (isset($foundPackage['abandoned'])) {
  383. if (is_string($foundPackage['abandoned'])) {
  384. $replacement = sprintf('Use %s instead', $foundPackage['abandoned']);
  385. } else {
  386. $replacement = 'No replacement was suggested';
  387. }
  388. $abandoned = sprintf('<warning>Abandoned. %s.</warning>', $replacement);
  389. }
  390. $choices[] = sprintf(' <info>%5s</info> %s %s', "[$position]", $foundPackage['name'], $abandoned);
  391. if ($foundPackage['name'] === $package) {
  392. $exactMatch = true;
  393. break;
  394. }
  395. }
  396. // no match, prompt which to pick
  397. if (!$exactMatch) {
  398. $io->writeError(array(
  399. '',
  400. sprintf('Found <info>%s</info> packages matching <info>%s</info>', count($matches), $package),
  401. '',
  402. ));
  403. $io->writeError($choices);
  404. $io->writeError('');
  405. $validator = function ($selection) use ($matches, $versionParser) {
  406. if ('' === $selection) {
  407. return false;
  408. }
  409. if (is_numeric($selection) && isset($matches[(int) $selection])) {
  410. $package = $matches[(int) $selection];
  411. return $package['name'];
  412. }
  413. if (preg_match('{^\s*(?P<name>[\S/]+)(?:\s+(?P<version>\S+))?\s*$}', $selection, $packageMatches)) {
  414. if (isset($packageMatches['version'])) {
  415. // parsing `acme/example ~2.3`
  416. // validate version constraint
  417. $versionParser->parseConstraints($packageMatches['version']);
  418. return $packageMatches['name'].' '.$packageMatches['version'];
  419. }
  420. // parsing `acme/example`
  421. return $packageMatches['name'];
  422. }
  423. throw new \Exception('Not a valid selection');
  424. };
  425. $package = $io->askAndValidate(
  426. 'Enter package # to add, or the complete package name if it is not listed: ',
  427. $validator,
  428. 3,
  429. false
  430. );
  431. }
  432. // no constraint yet, determine the best version automatically
  433. if (false !== $package && false === strpos($package, ' ')) {
  434. $validator = function ($input) {
  435. $input = trim($input);
  436. return $input ?: false;
  437. };
  438. $constraint = $io->askAndValidate(
  439. 'Enter the version constraint to require (or leave blank to use the latest version): ',
  440. $validator,
  441. 3,
  442. false
  443. );
  444. if (false === $constraint) {
  445. list($name, $constraint) = $this->findBestVersionAndNameForPackage($input, $package, $phpVersion, $preferredStability);
  446. $io->writeError(sprintf(
  447. 'Using version <info>%s</info> for <info>%s</info>',
  448. $constraint,
  449. $package
  450. ));
  451. }
  452. $package .= ' '.$constraint;
  453. }
  454. if (false !== $package) {
  455. $requires[] = $package;
  456. }
  457. }
  458. }
  459. return $requires;
  460. }
  461. protected function formatAuthors($author)
  462. {
  463. return array($this->parseAuthorString($author));
  464. }
  465. protected function formatRequirements(array $requirements)
  466. {
  467. $requires = array();
  468. $requirements = $this->normalizeRequirements($requirements);
  469. foreach ($requirements as $requirement) {
  470. $requires[$requirement['name']] = $requirement['version'];
  471. }
  472. return $requires;
  473. }
  474. protected function getGitConfig()
  475. {
  476. if (null !== $this->gitConfig) {
  477. return $this->gitConfig;
  478. }
  479. $finder = new ExecutableFinder();
  480. $gitBin = $finder->find('git');
  481. // TODO in v3 always call with an array
  482. if (method_exists('Symfony\Component\Process\Process', 'fromShellCommandline')) {
  483. $cmd = new Process(array($gitBin, 'config', '-l'));
  484. } else {
  485. $cmd = new Process(sprintf('%s config -l', ProcessExecutor::escape($gitBin)));
  486. }
  487. $cmd->run();
  488. if ($cmd->isSuccessful()) {
  489. $this->gitConfig = array();
  490. preg_match_all('{^([^=]+)=(.*)$}m', $cmd->getOutput(), $matches, PREG_SET_ORDER);
  491. foreach ($matches as $match) {
  492. $this->gitConfig[$match[1]] = $match[2];
  493. }
  494. return $this->gitConfig;
  495. }
  496. return $this->gitConfig = array();
  497. }
  498. /**
  499. * Checks the local .gitignore file for the Composer vendor directory.
  500. *
  501. * Tested patterns include:
  502. * "/$vendor"
  503. * "$vendor"
  504. * "$vendor/"
  505. * "/$vendor/"
  506. * "/$vendor/*"
  507. * "$vendor/*"
  508. *
  509. * @param string $ignoreFile
  510. * @param string $vendor
  511. *
  512. * @return bool
  513. */
  514. protected function hasVendorIgnore($ignoreFile, $vendor = 'vendor')
  515. {
  516. if (!file_exists($ignoreFile)) {
  517. return false;
  518. }
  519. $pattern = sprintf('{^/?%s(/\*?)?$}', preg_quote($vendor));
  520. $lines = file($ignoreFile, FILE_IGNORE_NEW_LINES);
  521. foreach ($lines as $line) {
  522. if (preg_match($pattern, $line)) {
  523. return true;
  524. }
  525. }
  526. return false;
  527. }
  528. protected function normalizeRequirements(array $requirements)
  529. {
  530. $parser = new VersionParser();
  531. return $parser->parseNameVersionPairs($requirements);
  532. }
  533. protected function addVendorIgnore($ignoreFile, $vendor = '/vendor/')
  534. {
  535. $contents = "";
  536. if (file_exists($ignoreFile)) {
  537. $contents = file_get_contents($ignoreFile);
  538. if ("\n" !== substr($contents, 0, -1)) {
  539. $contents .= "\n";
  540. }
  541. }
  542. file_put_contents($ignoreFile, $contents . $vendor. "\n");
  543. }
  544. protected function isValidEmail($email)
  545. {
  546. // assume it's valid if we can't validate it
  547. if (!function_exists('filter_var')) {
  548. return true;
  549. }
  550. // php <5.3.3 has a very broken email validator, so bypass checks
  551. if (PHP_VERSION_ID < 50303) {
  552. return true;
  553. }
  554. return false !== filter_var($email, FILTER_VALIDATE_EMAIL);
  555. }
  556. private function getPool(InputInterface $input, $minimumStability = null)
  557. {
  558. $key = $minimumStability ?: 'default';
  559. if (!isset($this->pools[$key])) {
  560. $this->pools[$key] = $pool = new Pool($minimumStability ?: $this->getMinimumStability($input));
  561. $pool->addRepository($this->getRepos());
  562. }
  563. return $this->pools[$key];
  564. }
  565. private function getMinimumStability(InputInterface $input)
  566. {
  567. if ($input->hasOption('stability')) {
  568. return $input->getOption('stability') ?: 'stable';
  569. }
  570. $file = Factory::getComposerFile();
  571. if (is_file($file) && is_readable($file) && is_array($composer = json_decode(file_get_contents($file), true))) {
  572. if (!empty($composer['minimum-stability'])) {
  573. return $composer['minimum-stability'];
  574. }
  575. }
  576. return 'stable';
  577. }
  578. /**
  579. * Given a package name, this determines the best version to use in the require key.
  580. *
  581. * This returns a version with the ~ operator prefixed when possible.
  582. *
  583. * @param InputInterface $input
  584. * @param string $name
  585. * @param string|null $phpVersion
  586. * @param string $preferredStability
  587. * @param string|null $requiredVersion
  588. * @param string $minimumStability
  589. * @param bool $fixed
  590. * @throws \InvalidArgumentException
  591. * @return array name version
  592. */
  593. private function findBestVersionAndNameForPackage(InputInterface $input, $name, $phpVersion, $preferredStability = 'stable', $requiredVersion = null, $minimumStability = null, $fixed = null)
  594. {
  595. // find the latest version allowed in this pool
  596. $versionSelector = new VersionSelector($this->getPool($input, $minimumStability));
  597. $ignorePlatformReqs = $input->hasOption('ignore-platform-reqs') && $input->getOption('ignore-platform-reqs');
  598. // ignore phpVersion if platform requirements are ignored
  599. if ($ignorePlatformReqs) {
  600. $phpVersion = null;
  601. }
  602. $package = $versionSelector->findBestCandidate($name, $requiredVersion, $phpVersion, $preferredStability);
  603. if (!$package) {
  604. // platform packages can not be found in the pool in versions other than the local platform's has
  605. // so if platform reqs are ignored we just take the user's word for it
  606. if ($ignorePlatformReqs && preg_match(PlatformRepository::PLATFORM_PACKAGE_REGEX, $name)) {
  607. return array($name, $requiredVersion ?: '*');
  608. }
  609. // Check whether the PHP version was the problem
  610. if ($phpVersion && $versionSelector->findBestCandidate($name, $requiredVersion, null, $preferredStability)) {
  611. throw new \InvalidArgumentException(sprintf(
  612. 'Package %s at version %s has a PHP requirement incompatible with your PHP version (%s)',
  613. $name,
  614. $requiredVersion,
  615. $phpVersion
  616. ));
  617. }
  618. // Check whether the required version was the problem
  619. if ($requiredVersion && $versionSelector->findBestCandidate($name, null, $phpVersion, $preferredStability)) {
  620. throw new \InvalidArgumentException(sprintf(
  621. 'Could not find package %s in a version matching %s',
  622. $name,
  623. $requiredVersion
  624. ));
  625. }
  626. // Check whether the PHP version was the problem
  627. if ($phpVersion && $versionSelector->findBestCandidate($name)) {
  628. throw new \InvalidArgumentException(sprintf(
  629. 'Could not find package %s in any version matching your PHP version (%s)',
  630. $name,
  631. $phpVersion
  632. ));
  633. }
  634. // Check for similar names/typos
  635. $similar = $this->findSimilar($name);
  636. if ($similar) {
  637. // Check whether the minimum stability was the problem but the package exists
  638. if ($requiredVersion === null && in_array($name, $similar, true)) {
  639. throw new \InvalidArgumentException(sprintf(
  640. 'Could not find a version of package %s matching your minimum-stability (%s). Require it with an explicit version constraint allowing its desired stability.',
  641. $name,
  642. $this->getMinimumStability($input)
  643. ));
  644. }
  645. throw new \InvalidArgumentException(sprintf(
  646. "Could not find package %s.\n\nDid you mean " . (count($similar) > 1 ? 'one of these' : 'this') . "?\n %s",
  647. $name,
  648. implode("\n ", $similar)
  649. ));
  650. }
  651. throw new \InvalidArgumentException(sprintf(
  652. 'Could not find a matching version of package %s. Check the package spelling, your version constraint and that the package is available in a stability which matches your minimum-stability (%s).',
  653. $name,
  654. $this->getMinimumStability($input)
  655. ));
  656. }
  657. return array(
  658. $package->getPrettyName(),
  659. $fixed ? $package->getPrettyVersion() : $versionSelector->findRecommendedRequireVersion($package),
  660. );
  661. }
  662. private function findSimilar($package)
  663. {
  664. try {
  665. $results = $this->repos->search($package);
  666. } catch (\Exception $e) {
  667. // ignore search errors
  668. return array();
  669. }
  670. $similarPackages = array();
  671. $installedRepo = $this->getComposer()->getRepositoryManager()->getLocalRepository();
  672. foreach ($results as $result) {
  673. if ($installedRepo->hasPackageName($result['name'])) {
  674. // Ignore installed package
  675. continue;
  676. }
  677. $similarPackages[$result['name']] = levenshtein($package, $result['name']);
  678. }
  679. asort($similarPackages);
  680. return array_keys(array_slice($similarPackages, 0, 5));
  681. }
  682. private function installDependencies($output)
  683. {
  684. try {
  685. $installCommand = $this->getApplication()->find('install');
  686. $installCommand->run(new ArrayInput(array()), $output);
  687. } catch (\Exception $e) {
  688. $this->getIO()->writeError('Could not install dependencies. Run `composer install` to see more information.');
  689. }
  690. }
  691. private function hasDependencies($options)
  692. {
  693. $requires = (array) $options['require'];
  694. $devRequires = isset($options['require-dev']) ? (array) $options['require-dev'] : array();
  695. return !empty($requires) || !empty($devRequires);
  696. }
  697. }