Skip to content

Commit 98b6640

Browse files
committed
Remove old utility ID-generator and move the code to the xsd-type
1 parent 1a72fad commit 98b6640

4 files changed

Lines changed: 38 additions & 63 deletions

File tree

src/XML/Utils/Random.php

Lines changed: 0 additions & 31 deletions
This file was deleted.

src/XMLSchema/Type/IDValue.php

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,10 +4,31 @@
44

55
namespace SimpleSAML\XMLSchema\Type;
66

7+
use function bin2hex;
8+
use function random_bytes;
9+
710
/**
811
* @package simplesaml/xml-common
912
*/
1013
class IDValue extends NCNameValue
1114
{
1215
public const string SCHEMA_TYPE = 'ID';
16+
17+
18+
/**
19+
* The fixed length of random identifiers.
20+
*
21+
* (43 - 1) / 2 = 21 → random_bytes(21) → 168 bits
22+
*/
23+
public const int ID_LENGTH = 43;
24+
25+
26+
/**
27+
* This function will generate a unique ID that is valid for use
28+
* in an xs:ID attribute
29+
*/
30+
public static function generateID(?string $prefix = "_"): static
31+
{
32+
return new static($prefix . bin2hex(random_bytes((self::ID_LENGTH - 1) / 2)));
33+
}
1334
}

tests/XML/Utils/RandomTest.php

Lines changed: 0 additions & 32 deletions
This file was deleted.

tests/XMLSchema/Type/IDValueTest.php

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,23 @@ public function testID(bool $shouldPass, string $id): void
4040
}
4141

4242

43+
/**
44+
* Test for IDValue::generateID().
45+
*/
46+
public function testGenerateID(): void
47+
{
48+
// check that it always starts with an underscore if no prefix is set
49+
$this->assertStringStartsWith('_', IDValue::generateID()->getValue());
50+
// check the length
51+
$this->assertEquals(IDValue::ID_LENGTH, strlen(IDValue::generateID()->getValue()));
52+
53+
// check that it always starts with the prefix if set
54+
$this->assertStringStartsWith('abc', IDValue::generateID('abc')->getValue());
55+
// check the length
56+
$this->assertEquals((IDValue::ID_LENGTH - 1) + strlen('abc'), strlen(IDValue::generateID('abc')->getValue()));
57+
}
58+
59+
4360
/**
4461
* @return array<string, array{0: true, 1: string}>
4562
*/

0 commit comments

Comments
 (0)