InitCommand.php 26 KB

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