本文整理汇总了PHP中Composer\Package\Version\VersionParser类的典型用法代码示例。如果您正苦于以下问题:PHP VersionParser类的具体用法?PHP VersionParser怎么用?PHP VersionParser使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了VersionParser类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: selectPackage
protected function selectPackage(IOInterface $io, $packageName, $version = null)
{
$io->writeError('<info>Searching for the specified package.</info>');
if ($composer = $this->getComposer(false)) {
$localRepo = $composer->getRepositoryManager()->getLocalRepository();
$repos = new CompositeRepository(array_merge(array($localRepo), $composer->getRepositoryManager()->getRepositories()));
} else {
$defaultRepos = Factory::createDefaultRepositories($this->getIO());
$io->writeError('No composer.json found in the current directory, searching packages from ' . implode(', ', array_keys($defaultRepos)));
$repos = new CompositeRepository($defaultRepos);
}
$pool = new Pool();
$pool->addRepository($repos);
$parser = new VersionParser();
$constraint = $version ? $parser->parseConstraints($version) : null;
$packages = $pool->whatProvides($packageName, $constraint, true);
if (count($packages) > 1) {
$package = reset($packages);
$io->writeError('<info>Found multiple matches, selected ' . $package->getPrettyString() . '.</info>');
$io->writeError('Alternatives were ' . implode(', ', array_map(function ($p) {
return $p->getPrettyString();
}, $packages)) . '.');
$io->writeError('<comment>Please use a more specific constraint to pick a different package.</comment>');
} elseif ($packages) {
$package = reset($packages);
$io->writeError('<info>Found an exact match ' . $package->getPrettyString() . '.</info>');
} else {
$io->writeError('<error>Could not find a package matching ' . $packageName . '.</error>');
return false;
}
return $package;
}
示例2: prepare
protected function prepare()
{
if (Type::determinePickle($this->path, $matches) < 1) {
throw new \Exception('Not a pickle git URI');
}
$this->name = $matches['package'];
$extension = $this->fetchPackageJson();
$versionParser = new VersionParser();
if ($matches['version'] == '') {
$versions = array_keys($extension['packages'][$this->name]);
if (count($versions) > 1) {
$versionToUse = $versions[1];
} else {
$versionToUse = $versions[0];
}
} else {
$versionConstraints = $versionParser->parseConstraints($matches['version']);
/* versions are sorted decreasing */
foreach ($extension['packages'][$this->name] as $version => $release) {
$constraint = new VersionConstraint('=', $versionParser->normalize($version));
if ($versionConstraints->matches($constraint)) {
$versionToUse = $version;
break;
}
}
}
$package = $extension['packages'][$this->name][$versionToUse];
$this->version = $versionToUse;
$this->normalizedVersion = $versionParser->normalize($versionToUse);
$this->name = $matches['package'];
$this->prettyVersion = $this->version;
$this->url = $package['source']['url'];
$this->reference = $package['source']['reference'];
$this->type = $package['source']['type'];
}
示例3: has
/**
* Search for a given package version.
*
* Usage examples : Composition::has('php', '5.3.*') // PHP version
* Composition::has('ext-memcache') // PHP extension
* Composition::has('vendor/package', '>2.1') // Package version
*
* @param type $packageName The package name
* @param type $prettyString An optional version constraint
*
* @return boolean Wether or not the package has been found.
*/
public static function has($packageName, $prettyString = '*')
{
if (null === self::$pool) {
if (null === self::$rootDir) {
self::$rootDir = getcwd();
if (!file_exists(self::$rootDir . '/composer.json')) {
throw new \RuntimeException('Unable to guess the project root dir, please specify it manually using the Composition::setRootDir method.');
}
}
$minimumStability = 'dev';
$config = new Config();
$file = new JsonFile(self::$rootDir . '/composer.json');
if ($file->exists()) {
$projectConfig = $file->read();
$config->merge($projectConfig);
if (isset($projectConfig['minimum-stability'])) {
$minimumStability = $projectConfig['minimum-stability'];
}
}
$vendorDir = self::$rootDir . '/' . $config->get('vendor-dir');
$pool = new Pool($minimumStability);
$pool->addRepository(new PlatformRepository());
$pool->addRepository(new InstalledFilesystemRepository(new JsonFile($vendorDir . '/composer/installed.json')));
$pool->addRepository(new InstalledFilesystemRepository(new JsonFile($vendorDir . '/composer/installed_dev.json')));
self::$pool = $pool;
}
$parser = new VersionParser();
$constraint = $parser->parseConstraints($prettyString);
$packages = self::$pool->whatProvides($packageName, $constraint);
return empty($packages) ? false : true;
}
示例4: testMemoryPackageHasExpectedMarshallingSemantics
/**
* Tests memory package marshalling/serialization semantics
* @dataProvider providerVersioningSchemes
*/
public function testMemoryPackageHasExpectedMarshallingSemantics($name, $version)
{
$versionParser = new VersionParser();
$normVersion = $versionParser->normalize($version);
$package = new MemoryPackage($name, $normVersion, $version);
$this->assertEquals(strtolower($name) . '-' . $normVersion, (string) $package);
}
示例5: validatePackage
/**
* @param PackageInterface $package
* @param bool $allowDevMaster
*
* @return \string[]
*/
public function validatePackage(PackageInterface $package, $allowDevMaster = false)
{
$errors = [];
$versionParser = new VersionParser();
/** @noinspection ExceptionsAnnotatingAndHandlingInspection */
$devMaster = new Constraint('==', $versionParser->normalize('dev-master'));
foreach ($package->getRequires() as $link) {
$linkConstraint = $link->getConstraint();
if (preg_match(PlatformRepository::PLATFORM_PACKAGE_REGEX, $link->getTarget())) {
continue;
}
if ($linkConstraint->matches($devMaster)) {
if ($allowDevMaster) {
continue;
}
$errors[] = sprintf('Package "%s" is required with branch constraint %s', $link->getTarget(), $linkConstraint->getPrettyString());
}
$constraints = [$linkConstraint];
if ($linkConstraint instanceof MultiConstraint) {
$constraints = (new ConstraintAccessor($linkConstraint))->getConstraints();
}
foreach ($constraints as $constraint) {
if ('dev-' === substr($constraint->getPrettyString(), 0, 4)) {
$errors[] = sprintf('Package "%s" is required with branch constraint %s', $link->getTarget(), $linkConstraint->getPrettyString());
}
}
}
return $errors;
}
示例6: getMinimalPackages
/**
* {@inheritDoc}
*/
public function getMinimalPackages()
{
if (isset($this->minimalPackages)) {
return $this->minimalPackages;
}
if (null === $this->rawData) {
$this->rawData = $this->loadDataFromServer();
}
$this->minimalPackages = array();
$versionParser = new VersionParser();
foreach ($this->rawData as $package) {
$version = !empty($package['version_normalized']) ? $package['version_normalized'] : $versionParser->normalize($package['version']);
$data = array('name' => strtolower($package['name']), 'repo' => $this, 'version' => $version, 'raw' => $package);
if (!empty($package['replace'])) {
$data['replace'] = $package['replace'];
}
if (!empty($package['provide'])) {
$data['provide'] = $package['provide'];
}
// add branch aliases
if ($aliasNormalized = $this->loader->getBranchAlias($package)) {
$data['alias'] = preg_replace('{(\\.9{7})+}', '.x', $aliasNormalized);
$data['alias_normalized'] = $aliasNormalized;
}
$this->minimalPackages[] = $data;
}
return $this->minimalPackages;
}
示例7: initialize
protected function initialize()
{
parent::initialize();
$versionParser = new VersionParser();
try {
$prettyVersion = PHP_VERSION;
$version = $versionParser->normalize($prettyVersion);
} catch (\UnexpectedValueException $e) {
$prettyVersion = preg_replace('#^(.+?)(-.+)?$#', '$1', PHP_VERSION);
$version = $versionParser->normalize($prettyVersion);
}
$php = new MemoryPackage('php', $version, $prettyVersion);
$php->setDescription('The PHP interpreter');
parent::addPackage($php);
foreach (get_loaded_extensions() as $name) {
if (in_array($name, array('standard', 'Core'))) {
continue;
}
$reflExt = new \ReflectionExtension($name);
try {
$prettyVersion = $reflExt->getVersion();
$version = $versionParser->normalize($prettyVersion);
} catch (\UnexpectedValueException $e) {
$prettyVersion = '0';
$version = $versionParser->normalize($prettyVersion);
}
$ext = new MemoryPackage('ext-' . $name, $version, $prettyVersion);
$ext->setDescription('The ' . $name . ' PHP extension');
parent::addPackage($ext);
}
}
示例8: execute
/**
* {@inheritdoc}
*/
protected function execute(InputInterface $input, OutputInterface $output)
{
if (!$this->deploymentConfig->isAvailable()) {
$output->writeln("<info>No information is available: the Magento application is not installed.</info>");
return;
}
/** @var DbVersionInfo $dbVersionInfo */
$dbVersionInfo = $this->objectManagerProvider->get()->get('Magento\\Framework\\Module\\DbVersionInfo');
$outdated = $dbVersionInfo->getDbVersionErrors();
if (!empty($outdated)) {
$output->writeln("<info>The module code base doesn't match the DB schema and data.</info>");
$versionParser = new VersionParser();
$codebaseUpdateNeeded = false;
foreach ($outdated as $row) {
if (!$codebaseUpdateNeeded && $row[DbVersionInfo::KEY_CURRENT] !== 'none') {
// check if module code base update is needed
$currentVersion = $versionParser->parseConstraints($row[DbVersionInfo::KEY_CURRENT]);
$requiredVersion = $versionParser->parseConstraints('>' . $row[DbVersionInfo::KEY_REQUIRED]);
if ($requiredVersion->matches($currentVersion)) {
$codebaseUpdateNeeded = true;
}
}
$output->writeln(sprintf("<info>%20s %10s: %11s -> %-11s</info>", $row[DbVersionInfo::KEY_MODULE], $row[DbVersionInfo::KEY_TYPE], $row[DbVersionInfo::KEY_CURRENT], $row[DbVersionInfo::KEY_REQUIRED]));
}
if ($codebaseUpdateNeeded) {
$output->writeln('<info>Some modules use code versions newer or older than the database. ' . "First update the module code, then run 'setup:upgrade'.</info>");
// we must have an exit code higher than zero to indicate something was wrong
return \Magento\Framework\Console\Cli::RETURN_FAILURE;
} else {
$output->writeln("<info>Run 'setup:upgrade' to update your DB schema and data.</info>");
}
} else {
$output->writeln('<info>All modules are up to date.</info>');
}
}
示例9: updateVersion
public function updateVersion()
{
/* Be sure package root is set before! */
$version = new Header\Version($this);
$parser = new VersionParser();
$this->version = $parser->normalize($version);
$this->prettyVersion = (string) $version;
}
示例10: isVersionMatching
/**
* Return true if $version matches $constraint (expressed as a Composer constraint string)
*
* @param string $version
* @param string $constraint
* @return bool
*/
public function isVersionMatching($version, $constraint)
{
$versionParser = new VersionParser();
$normalizedVersion = $versionParser->normalize($version);
$versionAsContraint = $versionParser->parseConstraints($normalizedVersion);
$linkConstraint = $versionParser->parseConstraints($constraint);
return $linkConstraint->matches($versionAsContraint);
}
示例11: execute
protected function execute(InputInterface $input, OutputInterface $output)
{
$file = Factory::getComposerFile();
if (!file_exists($file) && !file_put_contents($file, "{\n}\n")) {
$output->writeln('<error>' . $file . ' could not be created.</error>');
return 1;
}
if (!is_readable($file)) {
$output->writeln('<error>' . $file . ' is not readable.</error>');
return 1;
}
if (!is_writable($file)) {
$output->writeln('<error>' . $file . ' is not writable.</error>');
return 1;
}
$json = new JsonFile($file);
$composer = $json->read();
$composerBackup = file_get_contents($json->getPath());
$requirements = $this->determineRequirements($input, $output, $input->getArgument('packages'));
$requireKey = $input->getOption('dev') ? 'require-dev' : 'require';
$removeKey = $input->getOption('dev') ? 'require' : 'require-dev';
$baseRequirements = array_key_exists($requireKey, $composer) ? $composer[$requireKey] : array();
$requirements = $this->formatRequirements($requirements);
// validate requirements format
$versionParser = new VersionParser();
foreach ($requirements as $constraint) {
$versionParser->parseConstraints($constraint);
}
if (!$this->updateFileCleanly($json, $baseRequirements, $requirements, $requireKey, $removeKey)) {
foreach ($requirements as $package => $version) {
$baseRequirements[$package] = $version;
if (isset($composer[$removeKey][$package])) {
unset($composer[$removeKey][$package]);
}
}
$composer[$requireKey] = $baseRequirements;
$json->write($composer);
}
$output->writeln('<info>' . $file . ' has been updated</info>');
if ($input->getOption('no-update')) {
return 0;
}
$updateDevMode = !$input->getOption('update-no-dev');
// Update packages
$composer = $this->getComposer();
$composer->getDownloadManager()->setOutputProgress(!$input->getOption('no-progress'));
$io = $this->getIO();
$commandEvent = new CommandEvent(PluginEvents::COMMAND, 'require', $input, $output);
$composer->getEventDispatcher()->dispatch($commandEvent->getName(), $commandEvent);
$install = Installer::create($io, $composer);
$install->setVerbose($input->getOption('verbose'))->setPreferSource($input->getOption('prefer-source'))->setPreferDist($input->getOption('prefer-dist'))->setDevMode($updateDevMode)->setUpdate(true)->setUpdateWhitelist(array_keys($requirements))->setWhitelistDependencies($input->getOption('update-with-dependencies'));
$status = $install->run();
if ($status !== 0) {
$output->writeln("\n" . '<error>Installation failed, reverting ' . $file . ' to its original content.</error>');
file_put_contents($json->getPath(), $composerBackup);
}
return $status;
}
示例12: determinePickle
public static function determinePickle($arg, &$matches)
{
$versionParser = new VersionParser();
$res = $versionParser->parseNameVersionPairs([$arg]);
$argPrefix = substr($arg, 0, 1);
if ($argPrefix == '/' || $argPrefix == '.') {
return 0;
}
$matches = ['package' => $res[0]['name'], 'version' => isset($res[0]['version']) ? $res[0]['version'] : ''];
return 1;
}
示例13: findPackage
/**
* {@inheritDoc}
*/
public function findPackage($name, $version)
{
// normalize version & name
$versionParser = new VersionParser();
$version = $versionParser->normalize($version);
$name = strtolower($name);
foreach ($this->getPackages() as $package) {
if ($name === $package->getName() && $version === $package->getVersion()) {
return $package;
}
}
}
示例14: execute
/**
* Require (install) a package.
*
* @param array $package Package names and version to require
* - Format: ['name' => '', 'version' => '']
*
* @throws \Bolt\Exception\PackageManagerException
*
* @return int 0 on success or a positive error code on failure
*/
public function execute(array $package)
{
$this->getComposer();
$io = $this->getIO();
/** @var \Bolt\Filesystem\Handler\JsonFile $jsonFile */
$jsonFile = $this->getOptions()->composerJson();
$newlyCreated = !$jsonFile->exists();
if ($newlyCreated) {
$this->app['extend.manager.json']->update();
}
// Format the package array
$package = $this->formatRequirements($package);
// Validate requirements format
$versionParser = new VersionParser();
foreach ($package as $constraint) {
$versionParser->parseConstraints($constraint);
}
// Get a back up of the file contents
$composerBackup = $jsonFile->parse();
// Update our JSON file now with a specific version.
// This is what Composer will read, and use, internally during the process.
// After that is complete, we'll re-save with a constraint
$this->updateComposerJson($jsonFile, $package, false);
// JSON file has been created/updated, if we're not installing, exit
if ($this->getOptions()->noUpdate()) {
return 0;
}
// Reload Composer config
$composer = $this->resetComposer();
/** @var $install \Composer\Installer */
$install = Installer::create($io, $composer)->setVerbose($this->getOptions()->verbose())->setPreferSource($this->getOptions()->preferSource())->setPreferDist($this->getOptions()->preferDist())->setDevMode(!$this->getOptions()->updateNoDev())->setOptimizeAutoloader($this->getOptions()->optimizeAutoloader())->setClassMapAuthoritative($this->getOptions()->classmapAuthoritative())->setUpdate($this->getOptions()->update())->setUpdateWhitelist(array_keys($package))->setWhitelistDependencies($this->getOptions()->updateWithDependencies())->setIgnorePlatformRequirements($this->getOptions()->ignorePlatformReqs())->setRunScripts(!$this->getOptions()->noScripts());
try {
$status = $install->run();
if ($status !== 0) {
if ($newlyCreated) {
// Installation failed, deleting JSON
$jsonFile->delete();
} else {
// Installation failed, reverting JSON to its original content
$jsonFile->dump($composerBackup);
}
}
// Update our JSON file now with a constraint
$this->updateComposerJson($jsonFile, $package, true);
return $status;
} catch (\Exception $e) {
// Installation failed, reverting JSON to its original content
$jsonFile->dump($composerBackup);
$msg = sprintf('%s recieved an error from Composer: %s in %s::%s', __METHOD__, $e->getMessage(), $e->getFile(), $e->getLine());
$this->app['logger.system']->critical($msg, ['event' => 'exception', 'exception' => $e]);
throw new PackageManagerException($e->getMessage(), $e->getCode(), $e);
}
}
示例15: doExecute
/**
* Execute the command.
*
* @param InputInterface $input
* @param OutputInterface $output
* @param bool $inverted Whether to invert matching process (why-not vs why behaviour)
* @return int|null Exit code of the operation.
*/
protected function doExecute(InputInterface $input, OutputInterface $output, $inverted = false)
{
// Emit command event on startup
$composer = $this->getComposer();
$commandEvent = new CommandEvent(PluginEvents::COMMAND, $this->getName(), $input, $output);
$composer->getEventDispatcher()->dispatch($commandEvent->getName(), $commandEvent);
// Prepare repositories and set up a pool
$platformOverrides = $composer->getConfig()->get('platform') ?: array();
$repository = new CompositeRepository(array(new ArrayRepository(array($composer->getPackage())), $composer->getRepositoryManager()->getLocalRepository(), new PlatformRepository(array(), $platformOverrides)));
$pool = new Pool();
$pool->addRepository($repository);
// Parse package name and constraint
list($needle, $textConstraint) = array_pad(explode(':', $input->getArgument(self::ARGUMENT_PACKAGE)), 2, $input->getArgument(self::ARGUMENT_CONSTRAINT));
// Find packages that are or provide the requested package first
$packages = $pool->whatProvides($needle);
if (empty($packages)) {
throw new \InvalidArgumentException(sprintf('Could not find package "%s" in your project', $needle));
}
// Include replaced packages for inverted lookups as they are then the actual starting point to consider
$needles = array($needle);
if ($inverted) {
foreach ($packages as $package) {
$needles = array_merge($needles, array_map(function (Link $link) {
return $link->getTarget();
}, $package->getReplaces()));
}
}
// Parse constraint if one was supplied
if ('*' !== $textConstraint) {
$versionParser = new VersionParser();
$constraint = $versionParser->parseConstraints($textConstraint);
} else {
$constraint = null;
}
// Parse rendering options
$renderTree = $input->getOption(self::OPTION_TREE);
$recursive = $renderTree || $input->getOption(self::OPTION_RECURSIVE);
// Resolve dependencies
$results = $repository->getDependents($needles, $constraint, $inverted, $recursive);
if (empty($results)) {
$extra = null !== $constraint ? sprintf(' in versions %smatching %s', $inverted ? 'not ' : '', $textConstraint) : '';
$this->getIO()->writeError(sprintf('<info>There is no installed package depending on "%s"%s</info>', $needle, $extra));
} elseif ($renderTree) {
$this->initStyles($output);
$root = $packages[0];
$this->getIO()->write(sprintf('<info>%s</info> %s %s', $root->getPrettyName(), $root->getPrettyVersion(), $root->getDescription()));
$this->printTree($results);
} else {
$this->printTable($output, $results);
}
return 0;
}