PageRenderTime 26ms CodeModel.GetById 22ms RepoModel.GetById 0ms app.codeStats 0ms

/src/composer-master/src/Composer/Command/RequireCommand.php

https://bitbucket.org/columbkh/project
PHP | 221 lines | 168 code | 37 blank | 16 comment | 19 complexity | fffba1561b63b2e3c5b3b21ce26f69f4 MD5 | raw file
  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 Symfony\Component\Console\Input\InputInterface;
  13. use Symfony\Component\Console\Input\InputArgument;
  14. use Symfony\Component\Console\Input\InputOption;
  15. use Symfony\Component\Console\Output\OutputInterface;
  16. use Composer\Factory;
  17. use Composer\Installer;
  18. use Composer\Json\JsonFile;
  19. use Composer\Json\JsonManipulator;
  20. use Composer\Package\Version\VersionParser;
  21. use Composer\Plugin\CommandEvent;
  22. use Composer\Plugin\PluginEvents;
  23. use Composer\Repository\CompositeRepository;
  24. use Composer\Repository\PlatformRepository;
  25. /**
  26. * @author Jérémy Romey <jeremy@free-agent.fr>
  27. * @author Jordi Boggiano <j.boggiano@seld.be>
  28. */
  29. class RequireCommand extends InitCommand
  30. {
  31. protected function configure()
  32. {
  33. $this
  34. ->setName('require')
  35. ->setDescription('Adds required packages to your composer.json and installs them.')
  36. ->setDefinition(array(
  37. new InputArgument('packages', InputArgument::IS_ARRAY | InputArgument::OPTIONAL, 'Optional package name can also include a version constraint, e.g. foo/bar or foo/bar:1.0.0 or foo/bar=1.0.0 or "foo/bar 1.0.0"'),
  38. new InputOption('dev', null, InputOption::VALUE_NONE, 'Add requirement to require-dev.'),
  39. new InputOption('prefer-source', null, InputOption::VALUE_NONE, 'Forces installation from package sources when possible, including VCS information.'),
  40. new InputOption('prefer-dist', null, InputOption::VALUE_NONE, 'Forces installation from package dist even for dev versions.'),
  41. new InputOption('no-progress', null, InputOption::VALUE_NONE, 'Do not output download progress.'),
  42. new InputOption('no-suggest', null, InputOption::VALUE_NONE, 'Do not show package suggestions.'),
  43. new InputOption('no-update', null, InputOption::VALUE_NONE, 'Disables the automatic update of the dependencies.'),
  44. new InputOption('no-scripts', null, InputOption::VALUE_NONE, 'Skips the execution of all scripts defined in composer.json file.'),
  45. new InputOption('update-no-dev', null, InputOption::VALUE_NONE, 'Run the dependency update with the --no-dev option.'),
  46. new InputOption('update-with-dependencies', null, InputOption::VALUE_NONE, 'Allows inherited dependencies to be updated, except those that are root requirements.'),
  47. new InputOption('update-with-all-dependencies', null, InputOption::VALUE_NONE, 'Allows all inherited dependencies to be updated, including those that are root requirements.'),
  48. new InputOption('ignore-platform-reqs', null, InputOption::VALUE_NONE, 'Ignore platform requirements (php & ext- packages).'),
  49. new InputOption('prefer-stable', null, InputOption::VALUE_NONE, 'Prefer stable versions of dependencies.'),
  50. new InputOption('prefer-lowest', null, InputOption::VALUE_NONE, 'Prefer lowest versions of dependencies.'),
  51. new InputOption('sort-packages', null, InputOption::VALUE_NONE, 'Sorts packages when adding/updating a new dependency'),
  52. new InputOption('optimize-autoloader', 'o', InputOption::VALUE_NONE, 'Optimize autoloader during autoloader dump'),
  53. new InputOption('classmap-authoritative', 'a', InputOption::VALUE_NONE, 'Autoload classes from the classmap only. Implicitly enables `--optimize-autoloader`.'),
  54. new InputOption('apcu-autoloader', null, InputOption::VALUE_NONE, 'Use APCu to cache found/not-found classes.'),
  55. ))
  56. ->setHelp(<<<EOT
  57. The require command adds required packages to your composer.json and installs them.
  58. If you do not specify a package, composer will prompt you to search for a package, and given results, provide a list of
  59. matches to require.
  60. If you do not specify a version constraint, composer will choose a suitable one based on the available package versions.
  61. If you do not want to install the new dependencies immediately you can call it with --no-update
  62. EOT
  63. )
  64. ;
  65. }
  66. protected function execute(InputInterface $input, OutputInterface $output)
  67. {
  68. $file = Factory::getComposerFile();
  69. $io = $this->getIO();
  70. $newlyCreated = !file_exists($file);
  71. if ($newlyCreated && !file_put_contents($file, "{\n}\n")) {
  72. $io->writeError('<error>'.$file.' could not be created.</error>');
  73. return 1;
  74. }
  75. if (!is_readable($file)) {
  76. $io->writeError('<error>'.$file.' is not readable.</error>');
  77. return 1;
  78. }
  79. if (!is_writable($file)) {
  80. $io->writeError('<error>'.$file.' is not writable.</error>');
  81. return 1;
  82. }
  83. if (filesize($file) === 0) {
  84. file_put_contents($file, "{\n}\n");
  85. }
  86. $json = new JsonFile($file);
  87. $composerBackup = file_get_contents($json->getPath());
  88. $composer = $this->getComposer(true, $input->getOption('no-plugins'));
  89. $repos = $composer->getRepositoryManager()->getRepositories();
  90. $platformOverrides = $composer->getConfig()->get('platform') ?: array();
  91. // initialize $this->repos as it is used by the parent InitCommand
  92. $this->repos = new CompositeRepository(array_merge(
  93. array(new PlatformRepository(array(), $platformOverrides)),
  94. $repos
  95. ));
  96. if ($composer->getPackage()->getPreferStable()) {
  97. $preferredStability = 'stable';
  98. } else {
  99. $preferredStability = $composer->getPackage()->getMinimumStability();
  100. }
  101. $phpVersion = $this->repos->findPackage('php', '*')->getPrettyVersion();
  102. $requirements = $this->determineRequirements($input, $output, $input->getArgument('packages'), $phpVersion, $preferredStability);
  103. $requireKey = $input->getOption('dev') ? 'require-dev' : 'require';
  104. $removeKey = $input->getOption('dev') ? 'require' : 'require-dev';
  105. $requirements = $this->formatRequirements($requirements);
  106. // validate requirements format
  107. $versionParser = new VersionParser();
  108. foreach ($requirements as $constraint) {
  109. $versionParser->parseConstraints($constraint);
  110. }
  111. $sortPackages = $input->getOption('sort-packages') || $composer->getConfig()->get('sort-packages');
  112. if (!$this->updateFileCleanly($json, $requirements, $requireKey, $removeKey, $sortPackages)) {
  113. $composerDefinition = $json->read();
  114. foreach ($requirements as $package => $version) {
  115. $composerDefinition[$requireKey][$package] = $version;
  116. unset($composerDefinition[$removeKey][$package]);
  117. }
  118. $json->write($composerDefinition);
  119. }
  120. $io->writeError('<info>'.$file.' has been '.($newlyCreated ? 'created' : 'updated').'</info>');
  121. if ($input->getOption('no-update')) {
  122. return 0;
  123. }
  124. $updateDevMode = !$input->getOption('update-no-dev');
  125. $optimize = $input->getOption('optimize-autoloader') || $composer->getConfig()->get('optimize-autoloader');
  126. $authoritative = $input->getOption('classmap-authoritative') || $composer->getConfig()->get('classmap-authoritative');
  127. $apcu = $input->getOption('apcu-autoloader') || $composer->getConfig()->get('apcu-autoloader');
  128. // Update packages
  129. $this->resetComposer();
  130. $composer = $this->getComposer(true, $input->getOption('no-plugins'));
  131. $composer->getDownloadManager()->setOutputProgress(!$input->getOption('no-progress'));
  132. $commandEvent = new CommandEvent(PluginEvents::COMMAND, 'require', $input, $output);
  133. $composer->getEventDispatcher()->dispatch($commandEvent->getName(), $commandEvent);
  134. $install = Installer::create($io, $composer);
  135. $install
  136. ->setVerbose($input->getOption('verbose'))
  137. ->setPreferSource($input->getOption('prefer-source'))
  138. ->setPreferDist($input->getOption('prefer-dist'))
  139. ->setDevMode($updateDevMode)
  140. ->setRunScripts(!$input->getOption('no-scripts'))
  141. ->setSkipSuggest($input->getOption('no-suggest'))
  142. ->setOptimizeAutoloader($optimize)
  143. ->setClassMapAuthoritative($authoritative)
  144. ->setApcuAutoloader($apcu)
  145. ->setUpdate(true)
  146. ->setUpdateWhitelist(array_keys($requirements))
  147. ->setWhitelistTransitiveDependencies($input->getOption('update-with-dependencies'))
  148. ->setWhitelistAllDependencies($input->getOption('update-with-all-dependencies'))
  149. ->setIgnorePlatformRequirements($input->getOption('ignore-platform-reqs'))
  150. ->setPreferStable($input->getOption('prefer-stable'))
  151. ->setPreferLowest($input->getOption('prefer-lowest'))
  152. ;
  153. $status = $install->run();
  154. if ($status !== 0) {
  155. if ($newlyCreated) {
  156. $io->writeError("\n".'<error>Installation failed, deleting '.$file.'.</error>');
  157. unlink($json->getPath());
  158. } else {
  159. $io->writeError("\n".'<error>Installation failed, reverting '.$file.' to its original content.</error>');
  160. file_put_contents($json->getPath(), $composerBackup);
  161. }
  162. }
  163. return $status;
  164. }
  165. private function updateFileCleanly($json, array $new, $requireKey, $removeKey, $sortPackages)
  166. {
  167. $contents = file_get_contents($json->getPath());
  168. $manipulator = new JsonManipulator($contents);
  169. foreach ($new as $package => $constraint) {
  170. if (!$manipulator->addLink($requireKey, $package, $constraint, $sortPackages)) {
  171. return false;
  172. }
  173. if (!$manipulator->removeSubNode($removeKey, $package)) {
  174. return false;
  175. }
  176. }
  177. file_put_contents($json->getPath(), $manipulator->getContents());
  178. return true;
  179. }
  180. protected function interact(InputInterface $input, OutputInterface $output)
  181. {
  182. return;
  183. }
  184. }