Skip to content

Commit

Permalink
Merge pull request #106 from fabiang/fix-numberparse-deprecation
Browse files Browse the repository at this point in the history
Fixed: handling non-scalars in NumberParse filter
  • Loading branch information
gsteel committed Oct 9, 2023
2 parents a402f1b + 68d7b15 commit 970a277
Show file tree
Hide file tree
Showing 3 changed files with 40 additions and 3 deletions.
4 changes: 1 addition & 3 deletions psalm-baseline.xml
Original file line number Diff line number Diff line change
Expand Up @@ -55,9 +55,6 @@
</MoreSpecificImplementedParamType>
</file>
<file src="src/Filter/NumberParse.php">
<MixedArgument>
<code>$value</code>
</MixedArgument>
<RedundantCastGivenDocblockType>
<code>(int) $style</code>
<code>(int) $type</code>
Expand Down Expand Up @@ -773,6 +770,7 @@
<file src="test/Filter/NumberParseTest.php">
<PossiblyUnusedMethod>
<code>formattedToNumberProvider</code>
<code>formatNonNumberProvider</code>
</PossiblyUnusedMethod>
</file>
<file src="test/TestAsset/ModuleEventInterface.php">
Expand Down
6 changes: 6 additions & 0 deletions src/Filter/NumberParse.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,10 @@

use function intl_get_error_message;
use function is_array;
use function is_bool;
use function is_float;
use function is_int;
use function is_scalar;
use function iterator_to_array;

/**
Expand Down Expand Up @@ -149,6 +151,10 @@ public function getFormatter()
*/
public function filter($value)
{
if (! is_scalar($value) || is_bool($value)) {
return $value;
}

if (
! is_int($value)
&& ! is_float($value)
Expand Down
33 changes: 33 additions & 0 deletions test/Filter/NumberParseTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
use LaminasTest\I18n\TestCase;
use NumberFormatter;
use PHPUnit\Framework\Attributes\DataProvider;
use stdClass;

class NumberParseTest extends TestCase
{
Expand Down Expand Up @@ -68,6 +69,38 @@ public static function formattedToNumberProvider(): array
];
}

#[DataProvider('formatNonNumberProvider')]
public function testFormattedWithNonNumbers(
mixed $value,
mixed $expected
): void {
$filter = new NumberParseFilter('en_US', NumberFormatter::DEFAULT_STYLE, NumberFormatter::TYPE_DOUBLE);
self::assertEquals($expected, $filter->filter($value));
}

/** @return array<array-key, array{0: mixed, 1: mixed}> */
public static function formatNonNumberProvider(): array
{
return [
[
null,
null,
],
[
[],
[],
],
[
new stdClass(),
new stdClass(),
],
[
false,
false,
],
];
}

public function testTheNumberFormatterCanBeManuallyInjected(): void
{
$formatter = new NumberFormatter('en_US', NumberFormatter::DEFAULT_STYLE);
Expand Down

0 comments on commit 970a277

Please sign in to comment.