Skip to content

Commit 5267183

Browse files
authored
Add stringable object support to NumericHelper::normalize() (#114)
* Add stringable object support to `NumericHelper::normalize()` * fix test
1 parent 0b573f3 commit 5267183

File tree

4 files changed

+26
-3
lines changed

4 files changed

+26
-3
lines changed

CHANGELOG.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22

33
## 2.2.1 under development
44

5-
- no changes in this release.
5+
- Enh #114: Add stringable object support to `NumericHelper::normalize()` (@vjik)
66

77
## 2.2.0 September 20, 2023
88

src/NumericHelper.php

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
namespace Yiisoft\Strings;
66

77
use InvalidArgumentException;
8+
use Stringable;
89

910
use function filter_var;
1011
use function fmod;
@@ -52,14 +53,14 @@ public static function toOrdinal(mixed $value): string
5253
/**
5354
* Returns string representation of a number value without thousands separators and with dot as decimal separator.
5455
*
55-
* @param bool|float|int|string $value
56+
* @param bool|float|int|string|Stringable $value
5657
*
5758
* @throws InvalidArgumentException if value is not scalar.
5859
*/
5960
public static function normalize(mixed $value): string
6061
{
6162
/** @psalm-suppress DocblockTypeContradiction */
62-
if (!is_scalar($value)) {
63+
if (!is_scalar($value) && !$value instanceof Stringable) {
6364
$type = gettype($value);
6465
throw new InvalidArgumentException("Value must be scalar. $type given.");
6566
}

tests/NumericHelperTest.php

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66

77
use PHPUnit\Framework\TestCase;
88
use Yiisoft\Strings\NumericHelper;
9+
use Yiisoft\Strings\Tests\Support\StringableObject;
910

1011
final class NumericHelperTest extends TestCase
1112
{
@@ -49,6 +50,7 @@ public function dataNormalize(): array
4950
'Int' => [10, '10'],
5051
'True' => [true, '1'],
5152
'False' => [false, '0'],
53+
'Stringable' => [new StringableObject('7 500,25'), '7500.25'],
5254
];
5355
}
5456

tests/Support/StringableObject.php

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
namespace Yiisoft\Strings\Tests\Support;
6+
7+
use Stringable;
8+
9+
final class StringableObject implements Stringable
10+
{
11+
public function __construct(
12+
private string $string
13+
) {
14+
}
15+
16+
public function __toString(): string
17+
{
18+
return $this->string;
19+
}
20+
}

0 commit comments

Comments
 (0)