/**
     * @dataProvider getRecommendedRequireVersionPackages
     */
    public function testFindRecommendedRequireVersion($prettyVersion, $isDev, $stability, $expectedVersion, $branchAlias = null)
    {
        $pool = $this->createMockPool();
        $versionSelector = new VersionSelector($pool);
        $versionParser = new VersionParser();

        $package = $this->getMock('\Composer\Package\PackageInterface');
        $package->expects($this->any())
            ->method('getPrettyVersion')
            ->will($this->returnValue($prettyVersion));
        $package->expects($this->any())
            ->method('getVersion')
            ->will($this->returnValue($versionParser->normalize($prettyVersion)));
        $package->expects($this->any())
            ->method('isDev')
            ->will($this->returnValue($isDev));
        $package->expects($this->any())
            ->method('getStability')
            ->will($this->returnValue($stability));

        $branchAlias = $branchAlias === null ? array() : array('branch-alias' => array($prettyVersion => $branchAlias));
        $package->expects($this->any())
            ->method('getExtra')
            ->will($this->returnValue($branchAlias));

        $recommended = $versionSelector->findRecommendedRequireVersion($package);

        // assert that the recommended version is what we expect
        $this->assertEquals($expectedVersion, $recommended);
    }
Example #2
0
 /**
  * Given a package name, this determines the best version to use in the require key.
  *
  * This returns a version with the ~ operator prefixed when possible.
  *
  * @param string $name
  *
  * @throws \InvalidArgumentException
  *
  * @return string
  */
 protected function findBestVersionForPackage($name)
 {
     $package = $this->versionSelector->findBestCandidate($name);
     if (!$package) {
         throw new \InvalidArgumentException(sprintf('Could not find package %s at any version for your minimum-stability (%s). Check the package spelling or your minimum-stability', $name, $this->getMinimumStability()));
     }
     return $this->versionSelector->findRecommendedRequireVersion($package);
 }
 /**
  * @return PackageInterface[]
  */
 public function getInstalled()
 {
     $composer = Factory::create(new NullIO(), $this->config);
     $localRepo = $composer->getRepositoryManager()->getLocalRepository();
     $repos = new CompositeRepository(array_merge(array($localRepo), $composer->getRepositoryManager()->getRepositories()));
     $pool = new Pool();
     $pool->addRepository($repos);
     $vs = new VersionSelector($pool);
     $packages = [];
     foreach ($localRepo->getPackages() as $package) {
         if (!isset($packages[$package->getName()]) || !is_object($packages[$package->getName()]) || version_compare($packages[$package->getName()]->getVersion(), $package->getVersion(), '<')) {
             if ($package instanceof CompletePackageInterface) {
                 $latestPackage = $vs->findBestCandidate($package->getName());
                 $package = new InstalledPackage($package, $latestPackage);
             }
             $packages[$package->getName()] = $package;
         }
     }
     return $packages;
 }
Example #4
0
 /**
  * Given a package name, this determines the best version to use in the require key.
  *
  * This returns a version with the ~ operator prefixed when possible.
  *
  * @param  InputInterface            $input
  * @param  string                    $name
  * @param  string                    $phpVersion
  * @throws \InvalidArgumentException
  * @return string
  */
 private function findBestVersionForPackage(InputInterface $input, $name, $phpVersion)
 {
     // find the latest version allowed in this pool
     $versionSelector = new VersionSelector($this->getPool($input));
     $package = $versionSelector->findBestCandidate($name, null, $phpVersion);
     if (!$package) {
         throw new \InvalidArgumentException(sprintf('Could not find package %s at any version for your minimum-stability (%s). Check the package spelling or your minimum-stability', $name, $this->getMinimumStability($input)));
     }
     return $versionSelector->findRecommendedRequireVersion($package);
 }
Example #5
0
 /**
  * Given a package, this finds the latest package matching it
  *
  * @param  PackageInterface $package
  * @param  Composer         $composer
  * @param  string           $phpVersion
  * @param  bool             $minorOnly
  *
  * @return PackageInterface|null
  */
 private function find_latest_package(PackageInterface $package, Composer $composer, $phpVersion, $minorOnly = false)
 {
     // find the latest version allowed in this pool
     $name = $package->getName();
     $versionSelector = new VersionSelector($this->get_pool($composer));
     $stability = $composer->getPackage()->getMinimumStability();
     $flags = $composer->getPackage()->getStabilityFlags();
     if (isset($flags[$name])) {
         $stability = array_search($flags[$name], BasePackage::$stabilities, true);
     }
     $bestStability = $stability;
     if ($composer->getPackage()->getPreferStable()) {
         $bestStability = $package->getStability();
     }
     $targetVersion = null;
     if (0 === strpos($package->getVersion(), 'dev-')) {
         $targetVersion = $package->getVersion();
     }
     if ($targetVersion === null && $minorOnly) {
         $targetVersion = '^' . $package->getVersion();
     }
     return $versionSelector->findBestCandidate($name, $targetVersion, $phpVersion, $bestStability);
 }
 protected function installRootPackage(IOInterface $io, Config $config, $packageName, $directory = null, $packageVersion = null, $stability = 'stable', $preferSource = false, $preferDist = false, $installDevPackages = false, $repositoryUrl = null, $disablePlugins = false, $noScripts = false, $keepVcs = false, $noProgress = false)
 {
     if (null === $repositoryUrl) {
         $sourceRepo = new CompositeRepository(Factory::createDefaultRepositories($io, $config));
     } elseif ("json" === pathinfo($repositoryUrl, PATHINFO_EXTENSION) && file_exists($repositoryUrl)) {
         $json = new JsonFile($repositoryUrl, new RemoteFilesystem($io, $config));
         $data = $json->read();
         if (!empty($data['packages']) || !empty($data['includes']) || !empty($data['provider-includes'])) {
             $sourceRepo = new ComposerRepository(array('url' => 'file://' . strtr(realpath($repositoryUrl), '\\', '/')), $io, $config);
         } else {
             $sourceRepo = new FilesystemRepository($json);
         }
     } elseif (0 === strpos($repositoryUrl, 'http')) {
         $sourceRepo = new ComposerRepository(array('url' => $repositoryUrl), $io, $config);
     } else {
         throw new \InvalidArgumentException("Invalid repository url given. Has to be a .json file or an http url.");
     }
     $parser = new VersionParser();
     $requirements = $parser->parseNameVersionPairs(array($packageName));
     $name = strtolower($requirements[0]['name']);
     if (!$packageVersion && isset($requirements[0]['version'])) {
         $packageVersion = $requirements[0]['version'];
     }
     if (null === $stability) {
         if (preg_match('{^[^,\\s]*?@(' . implode('|', array_keys(BasePackage::$stabilities)) . ')$}i', $packageVersion, $match)) {
             $stability = $match[1];
         } else {
             $stability = VersionParser::parseStability($packageVersion);
         }
     }
     $stability = VersionParser::normalizeStability($stability);
     if (!isset(BasePackage::$stabilities[$stability])) {
         throw new \InvalidArgumentException('Invalid stability provided (' . $stability . '), must be one of: ' . implode(', ', array_keys(BasePackage::$stabilities)));
     }
     $pool = new Pool($stability);
     $pool->addRepository($sourceRepo);
     // find the latest version if there are multiple
     $versionSelector = new VersionSelector($pool);
     $package = $versionSelector->findBestCandidate($name, $packageVersion);
     if (!$package) {
         throw new \InvalidArgumentException("Could not find package {$name}" . ($packageVersion ? " with version {$packageVersion}." : " with stability {$stability}."));
     }
     if (null === $directory) {
         $parts = explode("/", $name, 2);
         $directory = getcwd() . DIRECTORY_SEPARATOR . array_pop($parts);
     }
     // handler Ctrl+C for unix-like systems
     if (function_exists('pcntl_signal')) {
         declare (ticks=100);
         pcntl_signal(SIGINT, function () use($directory) {
             $fs = new Filesystem();
             $fs->removeDirectory($directory);
             exit(130);
         });
     }
     $io->writeError('<info>Installing ' . $package->getName() . ' (' . VersionParser::formatVersion($package, false) . ')</info>');
     if ($disablePlugins) {
         $io->writeError('<info>Plugins have been disabled.</info>');
     }
     if (0 === strpos($package->getPrettyVersion(), 'dev-') && in_array($package->getSourceType(), array('git', 'hg'))) {
         $package->setSourceReference(substr($package->getPrettyVersion(), 4));
     }
     $dm = $this->createDownloadManager($io, $config);
     $dm->setPreferSource($preferSource)->setPreferDist($preferDist)->setOutputProgress(!$noProgress);
     $projectInstaller = new ProjectInstaller($directory, $dm);
     $im = $this->createInstallationManager();
     $im->addInstaller($projectInstaller);
     $im->install(new InstalledFilesystemRepository(new JsonFile('php://memory')), new InstallOperation($package));
     $im->notifyInstalls();
     $installedFromVcs = 'source' === $package->getInstallationSource();
     $io->writeError('<info>Created project in ' . $directory . '</info>');
     chdir($directory);
     $_SERVER['COMPOSER_ROOT_VERSION'] = $package->getPrettyVersion();
     putenv('COMPOSER_ROOT_VERSION=' . $_SERVER['COMPOSER_ROOT_VERSION']);
     return $installedFromVcs;
 }
 protected function installRootPackage(IOInterface $io, Config $config, $packageName, $directory = null, $packageVersion = null, $stability = 'stable', $preferSource = false, $preferDist = false, $installDevPackages = false, $repository = null, $disablePlugins = false, $noScripts = false, $keepVcs = false, $noProgress = false, $ignorePlatformReqs = false, $secureHttp = true)
 {
     if (!$secureHttp) {
         $config->merge(array('config' => array('secure-http' => false)));
     }
     if (null === $repository) {
         $sourceRepo = new CompositeRepository(RepositoryFactory::defaultRepos($io, $config));
     } else {
         $sourceRepo = RepositoryFactory::fromString($io, $config, $repository, true);
     }
     $parser = new VersionParser();
     $requirements = $parser->parseNameVersionPairs(array($packageName));
     $name = strtolower($requirements[0]['name']);
     if (!$packageVersion && isset($requirements[0]['version'])) {
         $packageVersion = $requirements[0]['version'];
     }
     if (null === $stability) {
         if (preg_match('{^[^,\\s]*?@(' . implode('|', array_keys(BasePackage::$stabilities)) . ')$}i', $packageVersion, $match)) {
             $stability = $match[1];
         } else {
             $stability = VersionParser::parseStability($packageVersion);
         }
     }
     $stability = VersionParser::normalizeStability($stability);
     if (!isset(BasePackage::$stabilities[$stability])) {
         throw new \InvalidArgumentException('Invalid stability provided (' . $stability . '), must be one of: ' . implode(', ', array_keys(BasePackage::$stabilities)));
     }
     $pool = new Pool($stability);
     $pool->addRepository($sourceRepo);
     $phpVersion = null;
     $prettyPhpVersion = null;
     if (!$ignorePlatformReqs) {
         $platformOverrides = $config->get('platform') ?: array();
         // initialize $this->repos as it is used by the parent InitCommand
         $platform = new PlatformRepository(array(), $platformOverrides);
         $phpPackage = $platform->findPackage('php', '*');
         $phpVersion = $phpPackage->getVersion();
         $prettyPhpVersion = $phpPackage->getPrettyVersion();
     }
     // find the latest version if there are multiple
     $versionSelector = new VersionSelector($pool);
     $package = $versionSelector->findBestCandidate($name, $packageVersion, $phpVersion, $stability);
     if (!$package) {
         $errorMessage = "Could not find package {$name} with " . ($packageVersion ? "version {$packageVersion}" : "stability {$stability}");
         if ($phpVersion && $versionSelector->findBestCandidate($name, $packageVersion, null, $stability)) {
             throw new \InvalidArgumentException($errorMessage . ' in a version installable using your PHP version ' . $prettyPhpVersion . '.');
         }
         throw new \InvalidArgumentException($errorMessage . '.');
     }
     if (null === $directory) {
         $parts = explode("/", $name, 2);
         $directory = getcwd() . DIRECTORY_SEPARATOR . array_pop($parts);
     }
     // handler Ctrl+C for unix-like systems
     if (function_exists('pcntl_signal')) {
         declare (ticks=100);
         pcntl_signal(SIGINT, function () use($directory) {
             $fs = new Filesystem();
             $fs->removeDirectory($directory);
             exit(130);
         });
     }
     $io->writeError('<info>Installing ' . $package->getName() . ' (' . $package->getFullPrettyVersion(false) . ')</info>');
     if ($disablePlugins) {
         $io->writeError('<info>Plugins have been disabled.</info>');
     }
     if (0 === strpos($package->getPrettyVersion(), 'dev-') && in_array($package->getSourceType(), array('git', 'hg'))) {
         $package->setSourceReference(substr($package->getPrettyVersion(), 4));
     }
     $dm = $this->createDownloadManager($io, $config);
     $dm->setPreferSource($preferSource)->setPreferDist($preferDist)->setOutputProgress(!$noProgress);
     $projectInstaller = new ProjectInstaller($directory, $dm);
     $im = $this->createInstallationManager();
     $im->addInstaller($projectInstaller);
     $im->install(new InstalledFilesystemRepository(new JsonFile('php://memory')), new InstallOperation($package));
     $im->notifyInstalls($io);
     // collect suggestions
     $this->suggestedPackagesReporter->addSuggestionsFromPackage($package);
     $installedFromVcs = 'source' === $package->getInstallationSource();
     $io->writeError('<info>Created project in ' . $directory . '</info>');
     chdir($directory);
     $_SERVER['COMPOSER_ROOT_VERSION'] = $package->getPrettyVersion();
     putenv('COMPOSER_ROOT_VERSION=' . $_SERVER['COMPOSER_ROOT_VERSION']);
     return $installedFromVcs;
 }
Example #8
0
 /**
  * Given a package name, this determines the best version to use in the require key.
  *
  * This returns a version with the ~ operator prefixed when possible.
  *
  * @param string $name
  *
  * @throws \InvalidArgumentException
  *
  * @return array
  */
 public function findBestVersionForPackage($name)
 {
     // find the latest version allowed in this pool
     $versionSelector = new VersionSelector($this->getPool());
     $package = $versionSelector->findBestCandidate($name);
     if (!$package) {
         return null;
     }
     return array('name' => $name, 'version' => $package->getVersion(), 'prettyversion' => $package->getPrettyVersion(), 'package' => $package, 'requirever' => $versionSelector->findRecommendedRequireVersion($package));
 }
 protected function installRootPackage(IOInterface $io, Config $config, $packageName, $directory = null, $packageVersion = null, $stability = 'stable', $preferSource = false, $preferDist = false, $installDevPackages = false, $repository = null, $disablePlugins = false, $noScripts = false, $keepVcs = false, $noProgress = false)
 {
     if (null === $repository) {
         $sourceRepo = new CompositeRepository(RepositoryFactory::defaultRepos($io, $config));
     } else {
         $sourceRepo = RepositoryFactory::fromString($io, $config, $repository, true);
     }
     $parser = new VersionParser();
     $requirements = $parser->parseNameVersionPairs(array($packageName));
     $name = strtolower($requirements[0]['name']);
     if (!$packageVersion && isset($requirements[0]['version'])) {
         $packageVersion = $requirements[0]['version'];
     }
     if (null === $stability) {
         if (preg_match('{^[^,\\s]*?@(' . implode('|', array_keys(BasePackage::$stabilities)) . ')$}i', $packageVersion, $match)) {
             $stability = $match[1];
         } else {
             $stability = VersionParser::parseStability($packageVersion);
         }
     }
     $stability = VersionParser::normalizeStability($stability);
     if (!isset(BasePackage::$stabilities[$stability])) {
         throw new \InvalidArgumentException('Invalid stability provided (' . $stability . '), must be one of: ' . implode(', ', array_keys(BasePackage::$stabilities)));
     }
     $pool = new Pool($stability);
     $pool->addRepository($sourceRepo);
     // using those 3 constants to build a version without the 'extra' bit that can contain garbage
     $phpVersion = PHP_MAJOR_VERSION . '.' . PHP_MINOR_VERSION . '.' . PHP_RELEASE_VERSION;
     // find the latest version if there are multiple
     $versionSelector = new VersionSelector($pool);
     $package = $versionSelector->findBestCandidate($name, $packageVersion, $phpVersion, $stability);
     if (!$package) {
         throw new \InvalidArgumentException("Could not find package {$name}" . ($packageVersion ? " with version {$packageVersion}." : " with stability {$stability}."));
     }
     if (null === $directory) {
         $parts = explode("/", $name, 2);
         $directory = getcwd() . DIRECTORY_SEPARATOR . array_pop($parts);
     }
     // handler Ctrl+C for unix-like systems
     if (function_exists('pcntl_signal')) {
         declare (ticks=100);
         pcntl_signal(SIGINT, function () use($directory) {
             $fs = new Filesystem();
             $fs->removeDirectory($directory);
             exit(130);
         });
     }
     $io->writeError('<info>Installing ' . $package->getName() . ' (' . $package->getFullPrettyVersion(false) . ')</info>');
     if ($disablePlugins) {
         $io->writeError('<info>Plugins have been disabled.</info>');
     }
     if (0 === strpos($package->getPrettyVersion(), 'dev-') && in_array($package->getSourceType(), array('git', 'hg'))) {
         $package->setSourceReference(substr($package->getPrettyVersion(), 4));
     }
     $dm = $this->createDownloadManager($io, $config);
     $dm->setPreferSource($preferSource)->setPreferDist($preferDist)->setOutputProgress(!$noProgress);
     $projectInstaller = new ProjectInstaller($directory, $dm);
     $im = $this->createInstallationManager();
     $im->addInstaller($projectInstaller);
     $im->install(new InstalledFilesystemRepository(new JsonFile('php://memory')), new InstallOperation($package));
     $im->notifyInstalls($io);
     $installedFromVcs = 'source' === $package->getInstallationSource();
     $io->writeError('<info>Created project in ' . $directory . '</info>');
     chdir($directory);
     $_SERVER['COMPOSER_ROOT_VERSION'] = $package->getPrettyVersion();
     putenv('COMPOSER_ROOT_VERSION=' . $_SERVER['COMPOSER_ROOT_VERSION']);
     return $installedFromVcs;
 }
Example #10
0
 /**
  * Given a concrete package, this returns a ~ constraint (in the future a ^ constraint)
  * that should be used, for example, in composer.json.
  * For example:
  *  * 1.2.1         -> ~1.2
  *  * 1.2           -> ~1.2
  *  * v3.2.1        -> ~3.2
  *  * 2.0-beta.1    -> ~2.0@beta
  *
  * @param string $vendor
  * @param string $package
  *
  * @return string
  */
 public function getDefaultConstraint($vendor, $package)
 {
     // Get versions.
     $versions = array_keys($this->getRawVersions($vendor, $package));
     // Get highest version.
     $highestVersion = reset($versions);
     $highestStability = $this->parser->parseStability($highestVersion);
     foreach ($versions as $version) {
         $nomalizedVersion = $this->parser->normalize($version);
         $nomalizedHighestVersion = $this->parser->normalize($highestVersion);
         if ($this->isMoreStable($version, $highestStability) || version_compare($nomalizedHighestVersion, $nomalizedVersion, '<')) {
             $highestVersion = $version;
             $highestStability = $this->parser->parseStability($version);
         }
     }
     // Let version selector format the constraint.
     $selector = new VersionSelector(new Pool());
     $package = new Package("{$vendor}/{$package}", $this->parser->normalize($highestVersion), $highestVersion);
     return $selector->findRecommendedRequireVersion($package);
 }
Example #11
0
 /**
  * Given a package name, this determines the best version to use in the require key.
  *
  * This returns a version with the ^ operator prefixed when possible.
  *
  * @param string $packageName
  * @param string $targetPackageVersion
  * @param bool   $returnArray
  *
  * @throws \InvalidArgumentException
  *
  * @return PackageInterface|array
  */
 protected function findBestVersionForPackage($packageName, $targetPackageVersion = null, $returnArray = false)
 {
     $versionSelector = new VersionSelector($this->getPool());
     $package = $versionSelector->findBestCandidate($packageName, $targetPackageVersion, strtok(PHP_VERSION, '-'), $this->getComposer()->getPackage()->getStability());
     if (!$package) {
         if ($returnArray === false) {
             throw new \InvalidArgumentException(sprintf('Could not find package %s at any version for your minimum-stability (%s). Check the package spelling or your minimum-stability', $packageName, $this->getMinimumStability()));
         }
         return null;
     }
     if ($returnArray === false) {
         return $versionSelector->findRecommendedRequireVersion($package);
     }
     return ['name' => $packageName, 'version' => $package->getVersion(), 'prettyversion' => $package->getPrettyVersion(), 'package' => $package, 'requirever' => $versionSelector->findRecommendedRequireVersion($package)];
 }