Skip to content

Commit fefd8ef

Browse files
committed
Add equals-method to compare value types
1 parent 3e0c48b commit fefd8ef

File tree

2 files changed

+35
-1
lines changed

2 files changed

+35
-1
lines changed

src/Type/AbstractValueType.php

+18
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,9 @@
44

55
namespace SimpleSAML\XML\Type;
66

7+
use function is_string;
78
use function preg_replace;
9+
use function strcmp;
810
use function trim;
911

1012
/**
@@ -132,4 +134,20 @@ public function __toString(): string
132134
{
133135
return $this->getValue();
134136
}
137+
138+
139+
/**
140+
* Compare the value to another one
141+
*
142+
* @param \SimpleSAML\Type\ValueTypeInterface|string
143+
* @return bool
144+
*/
145+
public function equals(ValueTypeInterface|string $other): bool
146+
{
147+
if (is_string($other)) {
148+
$other = static::fromString($other);
149+
}
150+
151+
return strcmp($this->getValue(), $other->getValue()) === 0;
152+
}
135153
}

tests/Type/AnyURIValueTest.php

+17-1
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@
88
use PHPUnit\Framework\TestCase;
99
use SimpleSAML\Test\XML\Assert\AnyURITest;
1010
use SimpleSAML\XML\Exception\SchemaViolationException;
11-
use SimpleSAML\XML\Type\AnyURIValue;
11+
use SimpleSAML\XML\Type\{AnyURIValue, StringValue};
1212

1313
/**
1414
* Class \SimpleSAML\Test\XML\Type\AnyURIValueTest
@@ -36,6 +36,22 @@ public function testAnyURI(bool $shouldPass, string $uri): void
3636
}
3737

3838

39+
/**
40+
*/
41+
public function testEquals(): void
42+
{
43+
// Assert that two identical values are equal
44+
$this->assertTrue(AnyURIValue::fromString('hello')->equals(AnyURIValue::fromString('hello')));
45+
$this->assertTrue(AnyURIValue::fromString('hello')->equals(StringValue::fromString('hello')));
46+
$this->assertTrue(AnyURIValue::fromString('hello')->equals('hello'));
47+
48+
// Assert that two different values are not equal
49+
$this->assertFalse(AnyURIValue::fromString('hello')->equals(AnyURIValue::fromString('world')));
50+
$this->assertFalse(AnyURIValue::fromString('hello')->equals(StringValue::fromString('world')));
51+
$this->assertFalse(AnyURIValue::fromString('hello')->equals('world'));
52+
}
53+
54+
3955
/**
4056
* @return array<string, array{0: true, 1: string}>
4157
*/

0 commit comments

Comments
 (0)