InitCommand.php 31 KB

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