Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
107 changes: 88 additions & 19 deletions src/Version.php
Original file line number Diff line number Diff line change
Expand Up @@ -26,12 +26,22 @@ final class Version implements \Stringable, \JsonSerializable
*/
public const string VERSION_REGEX = '(?P<major>\d++)\.(?P<minor>\d++)(?:\.(?P<patch>\d++))?(?:\.(?P<build>\d++))?([-.]?(?P<stability>beta|RC|alpha|stable)(?:[.-]?(?P<pre_release>\d+))?)?';

/**
* Match relative version formats.
*
* * Major version requires a fixed number.
* * Patch and build identifiers are optional.
* * Only `x`, `X` and `*` are allowed as placeholders.
*/
public const string RELATIVE_VERSION_REGEX = '(?P<major>\d++)(?:\.(?P<minor>[xX*]|\d++))(?:\.(?P<patch>[xX*]|\d++))?(?:\.(?P<build>[xX*]|\d++))?';

// fromString() options (bitmask)
public const int INPUT_IGNORE_BUILD = 1;
public const int INPUT_IGNORE_PATCH = (self::INPUT_IGNORE_BUILD | 2);
public const int INPUT_IGNORE_PRE_RELEASE = 16;
public const int INPUT_FILL_PATCH = 4;
public const int INPUT_FILL_BUILD = (self::INPUT_FILL_PATCH | 8);
public const int INPUT_ALLOW_RELATIVE = 32;

// getNextVersionCandidates() options (bitmask)
public const int CANDIDATE_EXCLUDE_PATCH = 1;
Expand Down Expand Up @@ -67,6 +77,7 @@ private function __construct(
int $preRelease = 0,
public readonly ?int $build = null,
?string $outputFormat = null,
public readonly ?string $relative = null,
) {
self::$formatter ??= new VersionFormatter();

Expand All @@ -78,12 +89,12 @@ private function __construct(

$this->patchEmpty = $patch === null ? null : 0;
$this->buildEmpty = $build === null ? null : 0;
$this->outputFormat = $outputFormat ?? VersionFormatter::FORMAT_DEFAULT;
$this->outputFormat = $outputFormat ?? ($relative ? VersionFormatter::FORMAT_DEFAULT_WITH_RELATIVE : VersionFormatter::FORMAT_DEFAULT);
$this->formatted = self::$formatter->format($this, $this->outputFormat);

// When an identifier is empty (patch or build) it will not be considered
// for as a candidate and so will ommited from the output when empty.
if ($patch !== null && $this->outputFormat === VersionFormatter::FORMAT_DEFAULT) {
// for a candidate and so will ommited from the output when empty.
if ($patch !== null && \in_array($this->outputFormat, [VersionFormatter::FORMAT_DEFAULT, VersionFormatter::FORMAT_DEFAULT_WITH_RELATIVE], true)) {
// Default format already contains patch identifier, and build is only used when none-null.
$this->outputFormatOfIncrement = $this->outputFormat;
} else {
Expand Down Expand Up @@ -163,27 +174,45 @@ public function __debugInfo(): array
* Note: When the patch identifier is omitted the patch property is set to null.
* Use the `$full` property to get a full version string.
*
* Relative versions:
*
* Relative versions are not allowed by default, add the {@see self::INPUT_ALLOW_RELATIVE}
* option to allow relative versions (only `x`, `X` and `*` are allowed as placeholders).
*
* A relative version cannot have a pre-release identifier or `-dev` suffix.
* Only minor, patch and build identifiers can be relative, major must be a "fixed" number.
*
* All placeholders are replaced with `9999999`, you can get the relative version
* with the {@see Version::$relative} property, `null` if the version is not relative.
*
* So: `1.x` becomes `1.9999999`, `1.5.*` becomes `1.5.9999999` (for the final version).
*
* Note that the relative version are also processed using the same options
* as the final version. Filling and ignoring of patch and/or build produces
* a relative version with these identifiers filled or omitted accordingly.
*
* 1.x with patch filling produces `1.x.0`, while `1.5.x` with ignore
* patch becomes `1.5`. Placeholders are kept as there original.
*
* @param string|null $outputFormat See {@see format()} for details defaults to {@see VersionFormatter::FORMAT_DEFAULT}
* @param int $options Bitmask options {@see Version::INPUT_*}
*/
public static function fromString(string $version, ?string $outputFormat = null, int $options = 0): self
{
// This is a special case that is never accepted anywhere.
if (str_ends_with(strtolower($version), 'stable-dev')) {
throw new \InvalidArgumentException(
\sprintf(
'Unable to parse version "%s" Expects an SemVer compatible version. ' .
'Either "1.0.0", "1.0", "1.0" or "1.0.0-beta1", "1.0.0-beta-1", "1.0.0.5", "1.0.0.0-dev"',
$version
)
);
$relative = null;

self::validateInputOptions($options);

if (str_contains($version, '*') || stripos($version, 'x') !== false) {
$version = self::getFromRelative($version, $relative, $options);
}

if (! preg_match('/^v?' . self::VERSION_REGEX . '(?:-dev)?$/i', $version, $matches)) {
if (! preg_match('/^v?' . self::VERSION_REGEX . '(?:-dev)?$/i', $version, $matches) || str_ends_with(strtolower($version), 'stable-dev')) {
throw new \InvalidArgumentException(
\sprintf(
'Unable to parse version "%s" Expects an SemVer compatible version. ' .
'Either "1.0.0", "1.0", "1.0" or "1.0.0-beta1", "1.0.0-beta-1", "1.0.0.5", "1.0.0.0-dev"',
'Either "1.0.0", "1.0", "1.0" or "1.0.0-beta1", "1.0.0-beta-1", "1.0.0.5", "1.0.0.0-dev"' .
(self::bitmaskHas($options, self::INPUT_ALLOW_RELATIVE) ? ', or relative (for minor, patch and/or build) like "1.x", "1.x.x", "10.*", "1.x.x.x".' : '.'),
$version
)
);
Expand All @@ -207,7 +236,8 @@ public static function fromString(string $version, ?string $outputFormat = null,
stability: Stability::fromString($matches['stability']),
preRelease: $matches['pre_release'],
build: $matches['build'],
outputFormat: $outputFormat
outputFormat: $outputFormat,
relative: $relative,
);
}

Expand Down Expand Up @@ -358,6 +388,9 @@ public static function createFromList(array $versions, ?\SortDirection $sortDire
* - `{major}.{minor}.{?patch}` (patch is only displayed when provided)
* - `{major}.{minor}` (minimal accepted version)
*
* Use `{relative}|{major}.{minor}` to display a relative version (when one was provided).
* Specific formatting of a relative version (omitting/filling) is not supported.
*
* Tip: If you need only one identifier use the object property instead.
*
* @param string|null $format The format to use. If null, the output format provided with
Expand Down Expand Up @@ -526,10 +559,7 @@ public function getNextIncreaseOf(VersionIdentifier $type): self
};
}

/**
* @param array<string|int, mixed> $matches
*/
private static function processInputOptions(int $options, array &$matches): void
private static function validateInputOptions(int $options): void
{
if ($options === 0) {
return;
Expand All @@ -546,6 +576,16 @@ private static function processInputOptions(int $options, array &$matches): void
if (self::bitmaskHas($options, self::INPUT_IGNORE_BUILD) && self::bitmaskHas($options, self::INPUT_FILL_BUILD)) {
throw new \InvalidArgumentException('Cannot combine options "INPUT_IGNORE_BUILD" and "INPUT_FILL_BUILD".');
}
}

/**
* @param array<string|int, mixed> $matches
*/
private static function processInputOptions(int $options, array &$matches): void
{
if ($options === 0) {
return;
}

if (self::bitmaskHas($options, self::INPUT_IGNORE_PATCH)) {
$matches['patch'] = null;
Expand All @@ -565,6 +605,35 @@ private static function processInputOptions(int $options, array &$matches): void
}
}

/**
* @param-out string $relative
*/
private static function getFromRelative(string $version, ?string &$relative, int $options): string
{
if (! self::bitmaskHas($options, self::INPUT_ALLOW_RELATIVE)) {
throw new \InvalidArgumentException(\sprintf('Unable to parse version "%s" Expects an SemVer compatible version. Relative versions are not allowed, try adding the "INPUT_ALLOW_RELATIVE" option.', $version));
}

if (! preg_match(\sprintf('{^[vV]?%s$}', self::RELATIVE_VERSION_REGEX), $version, $matches)) {
throw new \InvalidArgumentException(\sprintf('Unable to parse version "%s", unexpected relative format. Expected a SemVer compatible relative version, major must be "fixed" like "1.x" or "1.*".', $version));
}

$relative = $version = $matches['major'];

self::processInputOptions($options, $matches);

foreach (['minor', 'patch', 'build'] as $identifier) {
if (! isset($matches[$identifier])) {
continue;
}

$version .= '.' . str_ireplace(['*', 'X'], '9999999', (string) $matches[$identifier]);
$relative .= '.' . $matches[$identifier];
}

return $version;
}

/**
* @return array{withPatch: bool, withBuild: bool, withPrereleases: Stability[]}
*/
Expand Down
38 changes: 33 additions & 5 deletions src/VersionFormatter.php
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,13 @@ final class VersionFormatter
*/
public const string FORMAT_DEFAULT = '{major}.{minor}.{?patch}.{?build}-{pre-release:upper}x';

/**
* Full Output-format same as FORMAT_DEFAULT, but with a relative-version identifier.
*
* Either: "1.0-ALPHA1", "1.0.0", "1.0.0.0", "1.0.0.5-ALPHA1", or "1.x" for a relative version
*/
public const string FORMAT_DEFAULT_WITH_RELATIVE = '{relative}|{major}.{minor}.{?patch}.{?build}-{pre-release:upper}x';

/**
* Full Output-format (with `{patch}`, `{build}`, uppercase pre-release without seperator).
*
Expand All @@ -44,20 +51,27 @@ final class VersionFormatter
/** @var array{casing: string, separator: string}|null */
private ?array $preReleasePattern = null;

private ?bool $relative = null;

/**
* @throws \InvalidArgumentException when the format is invalid
*/
public function format(Version $version, string $format = self::FORMAT_DEFAULT): string
{
$this->prefix = '';
$this->preReleasePattern = ['casing' => 'upper', 'separator' => ''];
$this->relative = false;

if ($format === self::FORMAT_FULL) {
$this->patchPattern = IdentifierMarker::Always;
$this->buildPattern = IdentifierMarker::Always;
} elseif ($format === self::FORMAT_DEFAULT) {
$this->patchPattern = IdentifierMarker::WhenProvided;
$this->buildPattern = IdentifierMarker::WhenProvided;
} elseif ($format === self::FORMAT_DEFAULT_WITH_RELATIVE) {
$this->patchPattern = IdentifierMarker::WhenProvided;
$this->buildPattern = IdentifierMarker::WhenProvided;
$this->relative = true;
} elseif ($format === self::FORMAT_WITHOUT_BUILD) {
$this->patchPattern = IdentifierMarker::Always;
$this->buildPattern = IdentifierMarker::Omit;
Expand All @@ -66,6 +80,13 @@ public function format(Version $version, string $format = self::FORMAT_DEFAULT):
}

$versionString = $this->prefix;

if ($this->relative && $version->relative !== null) {
$versionString .= $version->relative;

return $versionString;
}

$versionString .= \sprintf('%d.%d', $version->major, $version->minor);

$versionString .= $this->formatVersionIdentifier($this->patchPattern, $version->patch);
Expand All @@ -89,10 +110,12 @@ public function format(Version $version, string $format = self::FORMAT_DEFAULT):
* @param 'v'|'V'|null $prefix
* @param 'upper'|'lower'|'title'|null $preReleaseCasing
* @param '-'|''|null $preReleaseSeparator
* @param bool|null $relative Add `{relative}|` to display a relative version
* when one was set
*
* @throws \InvalidArgumentException when the format is invalid or when the pre-release options are invalid
*/
public function modifyFormat(string $original, ?string $prefix = null, ?IdentifierMarker $patch = null, ?IdentifierMarker $build = null, ?bool $preRelease = null, ?string $preReleaseCasing = null, ?string $preReleaseSeparator = null): string
public function modifyFormat(string $original, ?string $prefix = null, ?IdentifierMarker $patch = null, ?IdentifierMarker $build = null, ?bool $preRelease = null, ?string $preReleaseCasing = null, ?string $preReleaseSeparator = null, ?bool $relative = null): string
{
$this->parse($original);

Expand All @@ -109,6 +132,7 @@ public function modifyFormat(string $original, ?string $prefix = null, ?Identifi
}

$this->prefix = $prefix ?? $this->prefix;
$this->relative = $relative ?? $this->relative;
$this->patchPattern = $patch ?? $this->patchPattern;
$this->buildPattern = $build ?? $this->buildPattern;

Expand All @@ -120,7 +144,10 @@ public function modifyFormat(string $original, ?string $prefix = null, ?Identifi
throw new \InvalidArgumentException('Pre-release options "$preReleaseCasing" and/or "$preReleaseSeparator" cannot be provided when pre-release is disabled, pass null to these arguments or remove them from the invocation.');
}

$format = $this->prefix . '{major}.{minor}' . $this->patchPattern->toFormat('patch') . $this->buildPattern->toFormat('build');
$format = $this->prefix;
$format .= $this->relative !== false ? '{relative}|' : '';
$format .= '{major}.{minor}';
$format .= $this->patchPattern->toFormat('patch') . $this->buildPattern->toFormat('build');

if ($preRelease ?? ($this->preReleasePattern !== null)) {
$format .= \sprintf(
Expand All @@ -141,11 +168,12 @@ private function parse(string $format): void
throw new \InvalidArgumentException(\sprintf('Invalid format "%s" provided. Expects something like: "{major}.{minor}.{patch}".', $format));
}

if (! preg_match('/^(?P<prefix>[vV])?\{major}\.\{minor}?/', $format, $matches)) {
throw new \InvalidArgumentException(\sprintf('Invalid format "%s" provided. Expects format to start with optional (v or V) followed by "{major}.{minor}"', $format));
if (! preg_match('/^(?P<prefix>[vV])?(?P<relative>\\{relative}\\|)?\{major}\.\{minor}?/', $format, $matches)) {
throw new \InvalidArgumentException(\sprintf('Invalid format "%s" provided. Expects format to start with optional (v or V) followed by "{major}.{minor}" or "{relative}|{major}.{minor}"', $format));
}

$this->prefix = $matches['prefix'] ?? '';
$this->relative = ($matches['relative'] ?? '') !== '';
$this->position = \strlen($matches[0]);

$this->preReleasePattern = null;
Expand Down Expand Up @@ -177,7 +205,7 @@ private function parse(string $format): void
$this->position += \strlen($matches[0]);

if ($length > $this->position) {
throw new \InvalidArgumentException(\sprintf('Invalid format "%s" provided at position "%s". Expected nothing more at this position. Note that any custom suffix like is not accepted.', $format, substr($format, $this->position)));
throw new \InvalidArgumentException(\sprintf('Invalid format "%s" provided at position "%s". Expected nothing more at this position. Note that any custom suffix like "-dev" is not accepted.', $format, substr($format, $this->position)));
}
}

Expand Down
Loading
Loading