Skip to content

Commit 45892c1

Browse files
authored
Test stringable classes for create (#12)
* Test stringable classes for create
1 parent d8ba09c commit 45892c1

File tree

2 files changed

+38
-0
lines changed

2 files changed

+38
-0
lines changed

src/Decimal.php

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -94,6 +94,10 @@ protected function parseValue(object|string|float|int $value): string
9494
throw new InvalidArgumentException('Invalid value');
9595
}
9696

97+
if ($value instanceof Stringable) {
98+
$value = (string)$value;
99+
}
100+
97101
if (is_string($value) && !is_numeric(trim($value))) {
98102
throw new InvalidArgumentException('Invalid non numeric value');
99103
}

tests/DecimalTest.php

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@
1313
use InvalidArgumentException;
1414
use PhpCollective\DecimalObject\Decimal;
1515
use PHPUnit\Framework\TestCase;
16+
use Stringable;
1617
use TypeError;
1718

1819
class DecimalTest extends TestCase
@@ -58,6 +59,27 @@ public function testCreate(mixed $value, string $expected): void
5859
$this->assertSame($expected, (string)$decimal);
5960
}
6061

62+
/**
63+
* @return void
64+
*/
65+
public function testCreateInvalidObject(): void
66+
{
67+
$objectStringable = new class implements Stringable
68+
{
69+
/**
70+
* @return string
71+
*/
72+
public function __toString(): string
73+
{
74+
return 'foo';
75+
}
76+
};
77+
78+
$this->expectException(InvalidArgumentException::class);
79+
80+
Decimal::create($objectStringable);
81+
}
82+
6183
/**
6284
* @return array
6385
*/
@@ -74,6 +96,17 @@ public function __toString(): string
7496
}
7597
};
7698

99+
$objectStringable = new class implements Stringable
100+
{
101+
/**
102+
* @return string
103+
*/
104+
public function __toString(): string
105+
{
106+
return '12.12';
107+
}
108+
};
109+
77110
return [
78111
[1.1, '1.1'],
79112
[-23, '-23'],
@@ -102,6 +135,7 @@ public function __toString(): string
102135
['622000000000000000000000', '622000000000000000000000'],
103136
['3.11e2', '311'],
104137
[$objectWithToStringMethod, '12.12'],
138+
[$objectStringable, '12.12'],
105139
];
106140
}
107141

0 commit comments

Comments
 (0)