Skip to content

Commit e71df20

Browse files
committed
Create assertion and type-class for xs:ID
1 parent 39c318d commit e71df20

File tree

3 files changed

+95
-0
lines changed

3 files changed

+95
-0
lines changed

src/Assert/IDTrait.php

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
namespace SimpleSAML\XML\Assert;
6+
7+
use InvalidArgumentException;
8+
9+
/**
10+
* @package simplesamlphp/xml-common
11+
*/
12+
trait IDTrait
13+
{
14+
/**
15+
* @param string $value
16+
* @param string $message
17+
*/
18+
protected static function validID(string $value, string $message = ''): void
19+
{
20+
Assert::validNCName(
21+
$value,
22+
$message ?: '%s is not a valid xs:ID',
23+
InvalidArgumentException::class,
24+
);
25+
}
26+
}

src/Type/IDValue.php

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
namespace SimpleSAML\XML\Type;
6+
7+
/**
8+
* @package simplesaml/xml-common
9+
*/
10+
class IDValue extends NCNameValue
11+
{
12+
}

tests/Type/IDValueTest.php

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
namespace SimpleSAML\Test\XML\Type;
6+
7+
use PHPUnit\Framework\Attributes\CoversClass;
8+
use PHPUnit\Framework\Attributes\DataProvider;
9+
use PHPUnit\Framework\TestCase;
10+
use SimpleSAML\XML\Exception\SchemaViolationException;
11+
use SimpleSAML\XML\Type\IDValue;
12+
13+
/**
14+
* Class \SimpleSAML\Test\Type\IDValueTest
15+
*
16+
* @package simplesamlphp/xml-common
17+
*/
18+
#[CoversClass(IDValue::class)]
19+
final class IDValueTest extends TestCase
20+
{
21+
/**
22+
* @param boolean $shouldPass
23+
* @param string $id
24+
*/
25+
#[DataProvider('provideID')]
26+
public function testID(bool $shouldPass, string $id): void
27+
{
28+
try {
29+
IDValue::fromString($id);
30+
$this->assertTrue($shouldPass);
31+
} catch (SchemaViolationException $e) {
32+
$this->assertFalse($shouldPass);
33+
}
34+
}
35+
36+
37+
/**
38+
* @return array<string, array{0: bool, 1: string}>
39+
*/
40+
public static function provideID(): array
41+
{
42+
return [
43+
'valid' => [true, 'Test'],
44+
'valid starts with underscore' => [true, '_Test'],
45+
'valid contains dashes' => [true, '_1950-10-04_10-00'],
46+
'valid contains dots' => [true, 'Te.st'],
47+
'valid contains diacriticals' => [true, 'fööbár'],
48+
'valid prefixed v4 UUID' => [true, '_5425e58e-e799-4884-92cc-ca64ecede32f'],
49+
'invalid empty string' => [false, ''],
50+
'invalid contains wildcard' => [false, 'Te*st'],
51+
'invalid starts with digit' => [false, '1Test'],
52+
'invalid contains colon' => [false, 'Te:st'],
53+
'whitespace collapse' => [true, "foobar\n"],
54+
'normalization' => [true, ' foobar '],
55+
];
56+
}
57+
}

0 commit comments

Comments
 (0)