Skip to content

Commit b4dff55

Browse files
authored
Assert non-empty-string when UUID is valid (#410)
* Assert, for psalm, the string is non-empty if validation passes * Adds a test for SA asserting that valid string are also non-empty * Suppress PHPStan error for unsupported conditional type assertion * Check SA tools don't complain about non-empty-string as input parameter to `Uuid::isValid()`
1 parent bc6cd7d commit b4dff55

File tree

3 files changed

+41
-0
lines changed

3 files changed

+41
-0
lines changed

phpstan-tests.neon

+4
Original file line numberDiff line numberDiff line change
@@ -26,3 +26,7 @@ parameters:
2626
- ./tests/Guid/*Test.php
2727
- ./tests/Nonstandard/*Test.php
2828
- ./tests/Rfc4122/*Test.php
29+
-
30+
message: "#^Method Ramsey\\\\Uuid\\\\.+ should return non-empty-string but returns string\\.$#"
31+
paths:
32+
- ./tests/static-analysis/ValidUuidIsNonEmpty.php

src/Uuid.php

+2
Original file line numberDiff line numberDiff line change
@@ -549,6 +549,8 @@ public static function fromInteger(string $integer): UuidInterface
549549
*
550550
* @psalm-pure note: changing the internal factory is an edge case not covered by purity invariants,
551551
* but under constant factory setups, this method operates in functionally pure manners
552+
*
553+
* @psalm-assert-if-true non-empty-string $uuid
552554
*/
553555
public static function isValid(string $uuid): bool
554556
{
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
namespace Ramsey\Uuid\StaticAnalysis;
6+
7+
use InvalidArgumentException;
8+
use Ramsey\Uuid\Uuid;
9+
10+
final class ValidUuidIsNonEmpty
11+
{
12+
/** @return non-empty-string */
13+
public function validUuidsAreNotEmpty(string $input): string
14+
{
15+
if (Uuid::isValid($input)) {
16+
return $input;
17+
}
18+
19+
throw new InvalidArgumentException('Not a UUID');
20+
}
21+
22+
/**
23+
* @param non-empty-string $input
24+
*
25+
* @return non-empty-string
26+
*/
27+
public function givenNonEmptyInputAssertionRemainsValid(string $input): string
28+
{
29+
if (Uuid::isValid($input)) {
30+
return $input;
31+
}
32+
33+
throw new InvalidArgumentException('Not a UUID');
34+
}
35+
}

0 commit comments

Comments
 (0)