Skip to content

[Uid] Rework internal format conversion #58089

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

Merged
merged 1 commit into from
Aug 27, 2024
Merged
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
16 changes: 12 additions & 4 deletions src/Symfony/Component/Uid/Uuid.php
Original file line number Diff line number Diff line change
Expand Up @@ -124,15 +124,17 @@ final public static function v8(string $uuid): UuidV8
/**
* @param int-mask-of<Uuid::FORMAT_*> $format
*/
public static function isValid(string $uuid /*, int $format = self::FORMAT_RFC_4122 */): bool
public static function isValid(string $uuid /* , int $format = self::FORMAT_RFC_4122 */): bool
{
$format = 1 < \func_num_args() ? func_get_arg(1) : self::FORMAT_RFC_4122;

if (36 === \strlen($uuid) && !($format & self::FORMAT_RFC_4122)) {
return false;
}

$uuid = self::transformToRfc4122($uuid, $format);
if (false === $uuid = self::transformToRfc4122($uuid, $format)) {
return false;
}

if (self::NIL === $uuid && \in_array(static::class, [__CLASS__, NilUuid::class], true)) {
return true;
Expand Down Expand Up @@ -190,10 +192,11 @@ private static function format(string $uuid, string $version): string
*
* @param int-mask-of<Uuid::FORMAT_*> $format
*
* @return non-empty-string
* @return string|false The RFC4122 string or false if the format doesn't match the input
*/
private static function transformToRfc4122(string $uuid, int $format): string
private static function transformToRfc4122(string $uuid, int $format): string|false
{
$inputUuid = $uuid;
$fromBase58 = false;
if (22 === \strlen($uuid) && 22 === strspn($uuid, BinaryUtil::BASE58['']) && $format & self::FORMAT_BASE_58) {
$uuid = str_pad(BinaryUtil::fromBase($uuid, BinaryUtil::BASE58), 16, "\0", \STR_PAD_LEFT);
Expand All @@ -214,6 +217,11 @@ private static function transformToRfc4122(string $uuid, int $format): string
$uuid = $ulid->toRfc4122();
}

if ($inputUuid === $uuid && !($format & self::FORMAT_RFC_4122)) {
// input format doesn't match the input string
return false;
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why not throw here ?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I didn't want to trigger the heavy exception mechanism (even more for an exception we don't rethrow to the user) for something that we want to be very fast, like validating an UUID

}

return $uuid;
}
}