8000 [Validator] Add `SemVer` constraint for semantic versioning validation by OskarStark · Pull Request #60995 · symfony/symfony · GitHub
[go: up one dir, main page]

Skip to content

[Validator] Add SemVer constraint for semantic versioning validation #60995

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 24 commits into
base: 7.4
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
24 commits
Select commit Hold shift + click to select a range
65c0b3a
[Validator] Add SemVer constraint for semantic versioning validation
OskarStark Jun 30, 2025
07e3d31
Add newlines at EOF and improve code formatting
OskarStark Jun 30, 2025
09fd2cd
Import DataProvider attribute and use short syntax
OskarStark Jun 30, 2025
61e946a
fix
OskarStark Jun 30, 2025
6c9c41b
-
OskarStark Jun 30, 2025
7839cfd
Fix SemVer validation pattern and tests
OskarStark Jun 30, 2025
26e2501
Simplify SemVer constraint to use single 'strict' option
OskarStark Jul 1, 2025
90a91d9
Update src/Symfony/Component/Validator/Constraints/SemVerValidator.php
OskarStark Jul 1, 2025
53bbc78
Change default value of strict option to true
OskarStark Jul 1, 2025
7830db9
Remove array-based configuration support from SemVer constraint
OskarStark Jul 1, 2025
9cbff30
Remove unnecessary comment
OskarStark Jul 1, 2025
642dfb1
Use x modifier for regex patterns to improve readability
OskarStark Jul 1, 2025
4ce63f8
Apply stof's suggestions for better compatibility
OskarStark Jul 1, 2025
bf43ccc
Apply suggestions from code review
OskarStark Jul 1, 2025
ebdc360
Update src/Symfony/Component/Validator/Constraints/SemVer.php
OskarStark Jul 2, 2025
a62f9f9
Add min/max version constraints to SemVer validator
OskarStark Jul 2, 2025
5dce356
Rename tooHighMessage/tooLowMessage to minMessage/maxMessage and make…
OskarStark Jul 2, 2025
763920c
Update src/Symfony/Component/Validator/Tests/Constraints/SemVerValida…
OskarStark Jul 2, 2025
7f52571
Move expectException calls directly before the code that triggers the…
OskarStark Jul 2, 2025
1bb4b7a
Add tests for custom message, minMessage and maxMessage
OskarStark Jul 2, 2025
ae62ffa
Follow Symfony constraint pattern: initialize message properties with…
OskarStark Jul 2, 2025
b09799c
Update src/Symfony/Component/Validator/Tests/Constraints/SemVerValida…
OskarStark Jul 3, 2025
c6f1545
Update src/Symfony/Component/Validator/Tests/Constraints/SemVerValida…
OskarStark Jul 3, 2025
b7a6d49
Remove unnecessary comments as requested in code review
OskarStark Jul 3, 2025
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
67 changes: 67 additions & 0 deletions src/Symfony/Component/Validator/Constraints/SemVer.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\Component\Validator\Constraints;

use Symfony\Component\Validator\Attribute\HasNamedArguments;
use Symfony\Component\Validator\Constraint;

/**
* Validates that a value is a valid semantic version.
*
* @see https://semver.org
*
* @author Oskar Stark <oskarstark@googlemail.com>
*/
#[\Attribute(\Attribute::TARGET_PROPERTY | \Attribute::TARGET_METHOD | \Attribute::IS_REPEATABLE)]
class SemVer extends Constraint
{
public const INVALID_SEMVER_ERROR = '3e7a8b8f-4d8f-4c7a-b5e9-1a2b3c4d5e6f';
public const TOO_LOW_ERROR = 'a0b1c2d3-e4f5-6789-abcd-ef0123456789';
public const TOO_HIGH_ERROR = 'b1c2d3e4-f5a6-7890-bcde-f01234567890';

protected const ERROR_NAMES = [
self::INVALID_SEMVER_ERROR => 'INVALID_SEMVER_ERROR',
self::TOO_LOW_ERROR => 'TOO_LOW_ERROR',
self::TOO_HIGH_ERROR => 'TOO_HIGH_ERROR',
];

public string $message = 'This value is not a valid semantic version.';
public string $minMessage = 'This value should be {{ min }} or more.';
public string $maxMessage = 'This value should be {{ max }} or less.';
public bool $strict = true;
public ?string $min = null;
public ?string $max = null;

/**
* @param string[]|null $groups
*/
#[HasNamedArguments]
public function __construct(
?string $message = null,
?string $minMessage = null,
?string $maxMessage = null,
?bool $strict = null,
?string $min = null,
?string $max = null,
?array $groups = null,
mixed $payload = null,
) {
parent::__construct(null, $groups, $payload);

$this->message = $message ?? $this->message;
$this->minMessage = $minMessage ?? $this->minMessage;
$this->maxMessage = $maxMessage ?? $this->maxMessage;
$this->strict = $strict ?? $this->strict;
$this->min = $min;
$this->max = $max;
}
}
160 changes: 160 additions & 0 deletions src/Symfony/Component/Validator/Constraints/SemVerValidator.php
8000
Original file line number Diff line number Diff line change
@@ -0,0 +1,160 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\Component\Validator\Constraints;

use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
use Symfony\Component\Validator\Exception\UnexpectedTypeException;
use Symfony\Component\Validator\Exception\UnexpectedValueException;

/**
* @author Oskar Stark <oskarstark@googlemail.com>
*/
class SemVerValidator extends ConstraintValidator
{
/**
* Strict Semantic Versioning 2.0.0 regex pattern.
* According to https://semver.org, no "v" prefix allowed
* Supports: 1.0.0, 1.2.3, 1.2.3-alpha, 1.2.3-alpha.1, 1.2.3+20130313144700, 1.2.3-beta+exp.sha.5114f85
*/
private const STRICT_SEMVER_PATTERN = '/^
(?P<major>0|[1-9]\d*) # Major version
\.
(?P<minor>0|[1-9]\d*) # Minor version
\.
(?P<patch>0|[1-9]\d*) # Patch version
(?:
-
(?P<prerelease>
(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*) # Pre-release identifier
(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))* # Additional dot-separated identifiers
)
)?
(?:
\+
(?P<buildmetadata>[0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*) # Build metadata
)?
$/x';

/**
* Loose semantic versioning pattern that allows partial versions.
* Supports: 1, 1.2, 1.2.3, v1, v1.2, v1.2.3, plus all the variations above
*/
private const LOOSE_SEMVER_PATTERN = '/^
(?P<prefix>v)? # Optional "v" prefix
(?P<major>0|[1-9]\d*) # Major version (required)
(?:
\.
(?P<minor>0|[1-9]\d*) # Minor version (optional)
(?:
\.
(?P<patch>0|[1-9]\d*) # Patch version (optional)
(?:
-
(?P<prerelease>
(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*) # Pre-release identifier
(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))* # Additional identifiers
)
)?
(?:
\+
(?P<buildmetadata>[0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*) # Build metadata
)?
)?
)?
$/x';

public function validate(mixed $value, Constraint $constraint): void
{
if (!$constraint instanceof SemVer) {
throw new UnexpectedTypeException($constraint, SemVer::class);
}

if (null === $value || '' === $value) {
return;
}

if (!\is_string($value) && !$value instanceof \Stringable) {
throw new UnexpectedValueException($value, 'string');
}

$value = (string) $value;

$pattern = $constraint->strict ? self::STRICT_SEMVER_PATTERN : self::LOOSE_SEMVER_PATTERN;

if (!preg_match($pattern, $value)) {
$this->context->buildViolation($constraint->message)
->setParameter('{{ value }}', $this->formatValue($value))
->setCode(SemVer::INVALID_SEMVER_ERROR)
->addViolation();

return;
}

$normalizedValue = $this->normalizeVersion($value);

if (null !== $constraint->min) {
$normalizedMin = $this->normalizeVersion($constraint->min);

if (!preg_match($pattern, $constraint->min)) {
throw new \InvalidArgumentException(sprintf('The "min" option value "%s" is not a valid semantic version according to the "strict" option.', $constraint->min));
}

if (version_compare($normalizedValue, $normalizedMin, '<')) {
$this->context->buildViolation($constraint->minMessage)
->setParameter('{{ value }}', $this->formatValue($value))
->setParameter('{{ min }}', $constraint->min)
->setCode(SemVer::TOO_LOW_ERROR)
->addViolation();
}
}

if (null !== $constraint->max) {
$normalizedMax = $this->normalizeVersion($constraint->max);

if (!preg_match($pattern, $constraint->max)) {
throw new \InvalidArgumentException(sprintf('The "max" option value "%s" is not a valid semantic version according to the "strict" option.', $constraint->max));
}

if (version_compare($normalizedValue, $normalizedMax, '>')) {
$this->context->buildViolation($constraint->maxMessage)
->setParameter('{{ value }}', $this->formatValue($value))
->setParameter('{{ max }}', $constraint->max)
->setCode(SemVer::TOO_HIGH_ERROR)
->addViolation();
}
}
}

/**
* Normalizes a version string for comparison by removing the 'v' prefix and
* ensuring it has all three version components (major.minor.patch).
*/
private function normalizeVersion(string $version): string
{
$version = ltrim($version, 'v');

$parts = explode('.', explode('-', explode('+', $version)[0])[0]);

while (count($parts) < 3) {
$parts[] = '0';
}

// Get pre-release and build metadata if any
$suffix = '';
if (preg_match('/^[^-+]+(.+)$/', $version, $matches)) {
$suffix = $matches[1];
}

return implode('.', array_slice($parts, 0, 3)) . $suffix;
}
}
Loading
Loading
0