InitCommand.php 29 KB

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