|
| 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