Skip to content

Commit d3207b4

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

4 files changed

Lines changed: 37 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: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,10 +4,30 @@
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+
* The fixed length of random identifiers.
19+
*
20+
* (41 - 1) / 2 = 20 → random_bytes(20) → 160 bits
21+
*/
22+
public const int ID_LENGTH = 41;
23+
24+
25+
/**
26+
* This function will generate a unique ID that is valid for use
27+
* in an xs:ID attribute
28+
*/
29+
public static function generateID(?string $prefix = "_"): static
30+
{
31+
return new static($prefix . bin2hex(random_bytes((self::ID_LENGTH - 1) / 2)));
32+
}
1333
}

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)