composer/semver
Composer Semver is a PHP library for parsing and validating version constraints, normalizing versions, and comparing releases. Extracted from Composer, it supports semver-style rules where possible while staying compatible with PHP’s version_compare.
Start by installing the package with composer require composer/semver. Once installed, the core entry points are VersionParser, Comparator, Semver, and Intervals — all in the Composer\Semver namespace. The most common first use case is validating and normalizing version strings (e.g., cleaning "1.2" → "1.2.0.0"), or parsing version constraints like "^1.2 || ~2.0" for downstream matching.
use Composer\Semver\VersionParser;
$parser = new VersionParser();
$normalized = $parser->normalize('1.2'); // '1.2.0.0'
$constraint = $parser->parseConstraints('^1.2 || ~2.0');
Check validity first using isValid() and Constraint::matches() to avoid subtle bugs from malformed version strings. Use Semver::satisfies() for checking if a version meets a constraint, and Semver::sort()/rsort() to order arrays of version strings intelligently.
VersionParser::parseConstraints() to convert user- or config-provided strings (e.g., from composer.json or CLI flags) into ConstraintInterface objects. Then validate or optimize with Intervals::compactConstraint() for performance in high-volume scenarios.Semver::satisfies() and Semver::satisfiedBy() with normalized versions. Use Comparator for low-level binary comparisons (e.g., sorting UI displays).Intervals::get() to decompose constraints into numeric intervals. Combine with Intervals::isSubsetOf() to check coverage (e.g., “does constraint A fully cover B?”), useful for security scanning or update feasibility checks."dev-main" using VersionParser::normalizeBranch(). It handles aliases (e.g., foobar-dev → dev-foobar) and preserves -dev stability markers for downstream logic.normalizeStability() expects valid stabilities (dev, alpha, beta, rc, stable). Passing invalid values silently returns ''; validate first with parseStability() if user input is involved.^ constraints, * no longer matches dev-* versions (since v3.0.0); only * matches stable *, while * + dev-* must be explicit. This avoids unintended pre-release installation."1.0" or "1.0.0.0" behave differently in version_compare; always normalize via VersionParser::normalize() before using Comparator or Semver.CompilingMatcher (introduced in v3.0) and call CompilingMatcher::clear() after processing batches to reset memoization.ConstraintInterface yourself — it’s marked internal as of v3.0. Use MultiConstraint::create() to generate optimized multi-constraints from arrays of strings instead.~ constraints support date-style versions (e.g., ~201903.0), but they’re fuzzy — always test edge cases if relying on them, and avoid mixing with standard semver unless intentional.How can I help you explore Laravel packages today?