Skip to content

Commit 00fb9ff

Browse files
authored
Allow array like types in StringOrArrayDynamicFunctionReturnTypeExtension (#96)
1 parent 0276800 commit 00fb9ff

File tree

3 files changed

+28
-4
lines changed

3 files changed

+28
-4
lines changed

src/StringOrArrayDynamicFunctionReturnTypeExtension.php

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414
use PHPStan\Reflection\ParametersAcceptorSelector;
1515
use PHPStan\Type\StringType;
1616
use PHPStan\Type\ArrayType;
17+
use PHPStan\Type\IntegerType;
1718
use PHPStan\Type\Type;
1819

1920
class StringOrArrayDynamicFunctionReturnTypeExtension implements \PHPStan\Type\DynamicFunctionReturnTypeExtension
@@ -34,13 +35,14 @@ public function getTypeFromFunctionCall(FunctionReflection $functionReflection,
3435
$functionReflection->getVariants()
3536
)->getReturnType();
3637
}
37-
3838
$dataArg = $args[0]->value;
3939
$dataArgType = $scope->getType($dataArg);
40-
if ($dataArgType instanceof ArrayType) {
40+
if ($dataArgType->isArray()->yes()) {
4141
$keyType = $dataArgType->getIterableKeyType();
42-
$itemType = $dataArgType->getIterableValueType();
43-
return new ArrayType($keyType, $itemType);
42+
if ($keyType instanceof StringType) {
43+
return new ArrayType(new StringType(), new StringType());
44+
}
45+
return new ArrayType(new IntegerType(), new StringType());
4446
}
4547
return new StringType();
4648
}

tests/DynamicReturnTypeExtensionTest.php

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ public function dataFileAsserts(): iterable
1616
yield from $this->gatherAssertTypes(__DIR__ . '/data/apply_filters.php');
1717
yield from $this->gatherAssertTypes(__DIR__ . '/data/current_time.php');
1818
yield from $this->gatherAssertTypes(__DIR__ . '/data/echo_parameter.php');
19+
yield from $this->gatherAssertTypes(__DIR__ . '/data/esc_sql.php');
1920
yield from $this->gatherAssertTypes(__DIR__ . '/data/get_comment.php');
2021
yield from $this->gatherAssertTypes(__DIR__ . '/data/get_object_taxonomies.php');
2122
yield from $this->gatherAssertTypes(__DIR__ . '/data/get_post.php');

tests/data/esc_sql.php

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
namespace SzepeViktor\PHPStan\WordPress\Tests;
6+
7+
use stdClass;
8+
9+
use function PHPStan\Testing\assertType;
10+
11+
// Indexed array as parameter
12+
assertType('array<int, string>', esc_sql(['someValue', 'toEscape']));
13+
14+
// Associative array as parameter
15+
assertType('array<string, string>', esc_sql(['someValue' => 'toEscape']));
16+
17+
// String as parameter
18+
assertType('string', esc_sql('someValueToEscape'));
19+
20+
// Wrong type provided (esc_sql() returns an empty string in that case)
21+
assertType('string', esc_sql(new \stdClass()));

0 commit comments

Comments
 (0)