-
-
Notifications
You must be signed in to change notification settings - Fork 9.6k
[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
OskarStark
wants to merge
24
commits into
symfony:7.4
Choose a base branch
from
OskarStark:feature/semver-constraint
base: 7.4
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+590
−0
Open
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 07e3d31
Add newlines at EOF and improve code formatting
OskarStark 09fd2cd
Import DataProvider attribute and use short syntax
OskarStark 61e946a
fix
OskarStark 6c9c41b
-
OskarStark 7839cfd
Fix SemVer validation pattern and tests
OskarStark 26e2501
Simplify SemVer constraint to use single 'strict' option
OskarStark 90a91d9
Update src/Symfony/Component/Validator/Constraints/SemVerValidator.php
OskarStark 53bbc78
Change default value of strict option to true
OskarStark 7830db9
Remove array-based configuration support from SemVer constraint
OskarStark 9cbff30
Remove unnecessary comment
OskarStark 642dfb1
Use x modifier for regex patterns to improve readability
OskarStark 4ce63f8
Apply stof's suggestions for better compatibility
OskarStark bf43ccc
Apply suggestions from code review
OskarStark ebdc360
Update src/Symfony/Component/Validator/Constraints/SemVer.php
OskarStark a62f9f9
Add min/max version constraints to SemVer validator
OskarStark 5dce356
Rename tooHighMessage/tooLowMessage to minMessage/maxMessage and make…
OskarStark 763920c
Update src/Symfony/Component/Validator/Tests/Constraints/SemVerValida…
OskarStark 7f52571
Move expectException calls directly before the code that triggers the…
OskarStark 1bb4b7a
Add tests for custom message, minMessage and maxMessage
OskarStark ae62ffa
Follow Symfony constraint pattern: initialize message properties with…
OskarStark b09799c
Update src/Symfony/Component/Validator/Tests/Constraints/SemVerValida…
OskarStark c6f1545
Update src/Symfony/Component/Validator/Tests/Constraints/SemVerValida…
OskarStark b7a6d49
Remove unnecessary comments as requested in code review
OskarStark File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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( | ||
OskarStark marked this conversation as resolved.
Show resolved
Hide resolved
|
||
?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
160
src/Symfony/Component/Validator/Constraints/SemVerValidator.php
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | ||
8000 | } | |
|
||
$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; | ||
} | ||
} |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.