Skip to content

Commit b75fe69

Browse files
committed
Add unit tests for AbstractType::convertMixedToString method
- Added tests to validate behavior of `convertMixedToString` for scalars, null, and `Stringable` objects. - Confirmed exceptions are thrown for non-stringable objects, arrays, and resources.
1 parent 3479d01 commit b75fe69

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
use PhpTypedValues\Abstract\AbstractType;
6+
use PhpTypedValues\Exception\TypeException;
7+
8+
it('convertMixedToString casts scalars and null to string', function (): void {
9+
expect(AbstractType::convertMixedToString(123))->toBe('123')
10+
->and(AbstractType::convertMixedToString(1.5))->toBe('1.5')
11+
->and(AbstractType::convertMixedToString('foo'))->toBe('foo')
12+
->and(AbstractType::convertMixedToString(true))->toBe('1')
13+
->and(AbstractType::convertMixedToString(false))->toBe('')
14+
->and(AbstractType::convertMixedToString(null))->toBe('');
15+
});
16+
17+
it('convertMixedToString accepts Stringable objects', function (): void {
18+
$obj = new class implements Stringable {
19+
public function __toString(): string
20+
{
21+
return '3.5';
22+
}
23+
};
24+
25+
expect(AbstractType::convertMixedToString($obj))->toBe('3.5');
26+
});
27+
28+
it('convertMixedToString throws TypeException for non-stringable objects, arrays and resources', function (): void {
29+
// array
30+
expect(fn() => AbstractType::convertMixedToString(['x']))
31+
->toThrow(TypeException::class, 'Value cannot be cast to string');
32+
33+
// stdClass (non-stringable)
34+
expect(fn() => AbstractType::convertMixedToString(new stdClass()))
35+
->toThrow(TypeException::class, 'Value cannot be cast to string');
36+
37+
// resource
38+
$res = fopen('php://memory', 'r');
39+
try {
40+
expect(fn() => AbstractType::convertMixedToString($res))
41+
->toThrow(TypeException::class, 'Value cannot be cast to string');
42+
} finally {
43+
\is_resource($res) && fclose($res);
44+
}
45+
});

0 commit comments

Comments
 (0)