Skip to content

Commit 6af159a

Browse files
committed
Enhance callable type handling by wrapping callables in array shapes and adding type alias tests
1 parent 3832b44 commit 6af159a

2 files changed

Lines changed: 156 additions & 6 deletions

File tree

‎src/Internal/Checker/InlineChecker.php‎

Lines changed: 74 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -174,12 +174,6 @@ public static function checkVariable(
174174

175175
$context = ($varName === 'return') ? 'Return value' : "Variable \$$varName";
176176

177-
if ($typeNode instanceof CallableTypeNode || ($typeNode instanceof IdentifierTypeNode && strtolower($typeNode->name) === 'callable')) {
178-
$cbPrefix = ($varName === 'return') ? 'Return value: Callback' : "Variable \$$varName: Callback";
179-
180-
return CallableWrapper::wrapTypeNode($typeNode, $value, $cbPrefix, $registry);
181-
}
182-
183177
if ($typeNode instanceof GenericTypeNode) {
184178
$baseName = strtolower($typeNode->type->name);
185179
$isCollection = isset(self::ARRAY_TYPES[$baseName]);
@@ -204,13 +198,87 @@ public static function checkVariable(
204198
if ($err !== null) {
205199
return $err;
206200
}
201+
202+
if ($typeNode instanceof CallableTypeNode || ($typeNode instanceof IdentifierTypeNode && strtolower($typeNode->name) === 'callable')) {
203+
$cbPrefix = ($varName === 'return') ? 'Return value: Callback' : "Variable \$$varName: Callback";
204+
205+
return CallableWrapper::wrapTypeNode($typeNode, $value, $cbPrefix, $registry);
206+
}
207+
208+
if ($typeNode instanceof ArrayShapeNode && \is_array($value)) {
209+
$value = self::wrapShapeCallables($typeNode, $value, $context, $registry);
210+
} elseif (\is_array($value)) {
211+
$value = self::wrapCollectionCallables($typeNode, $value, $context, $registry);
212+
}
207213
} catch (\Throwable $e) {
208214
// Silently ignore unexpected execution exceptions
209215
}
210216

211217
return $value;
212218
}
213219

220+
/**
221+
* Recursively wraps callable items nested inside array shapes.
222+
*
223+
* @param array<int|string, mixed> $value
224+
*
225+
* @return array<int|string, mixed>
226+
*/
227+
private static function wrapShapeCallables(ArrayShapeNode $shapeNode, array $value, string $context, TypeValidatorRegistry $registry): array
228+
{
229+
foreach ($shapeNode->items as $item) {
230+
$key = null;
231+
if ($item->keyName instanceof \PHPStan\PhpDocParser\Ast\ConstExpr\ConstExprStringNode) {
232+
$key = $item->keyName->value;
233+
} elseif ($item->keyName instanceof IdentifierTypeNode) {
234+
$key = $item->keyName->name;
235+
} elseif ($item->keyName instanceof \PHPStan\PhpDocParser\Ast\ConstExpr\ConstExprIntegerNode) {
236+
$key = (int) $item->keyName->value;
237+
} elseif ($item->keyName !== null) {
238+
$key = (string) $item->keyName;
239+
}
240+
241+
if ($key !== null && \array_key_exists($key, $value)) {
242+
if ($item->valueType instanceof CallableTypeNode) {
243+
$cbPrefix = $context . "['" . $key . "']: Callback";
244+
$value[$key] = CallableWrapper::wrapTypeNode($item->valueType, $value[$key], $cbPrefix, $registry);
245+
} elseif ($item->valueType instanceof ArrayShapeNode && \is_array($value[$key])) {
246+
$value[$key] = self::wrapShapeCallables($item->valueType, $value[$key], $context . "['" . $key . "']", $registry);
247+
}
248+
}
249+
}
250+
251+
return $value;
252+
}
253+
254+
/**
255+
* Wraps callable elements in generic lists or typed arrays (e.g. list<callable(int): string>).
256+
*
257+
* @param array<int|string, mixed> $value
258+
*
259+
* @return array<int|string, mixed>
260+
*/
261+
private static function wrapCollectionCallables(TypeNode $typeNode, array $value, string $context, TypeValidatorRegistry $registry): array
262+
{
263+
$innerCallable = null;
264+
if ($typeNode instanceof GenericTypeNode && \in_array(strtolower($typeNode->type->name), ['list', 'array', 'iterable'], true)) {
265+
$innerCallable = $typeNode->genericTypes[1] ?? $typeNode->genericTypes[0] ?? null;
266+
} elseif ($typeNode instanceof ArrayTypeNode) {
267+
$innerCallable = $typeNode->type;
268+
}
269+
270+
if ($innerCallable instanceof CallableTypeNode) {
271+
foreach ($value as $k => $item) {
272+
if (CallableWrapper::isCallable($item)) {
273+
$cbPrefix = $context . "[$k]: Callback";
274+
$value[$k] = CallableWrapper::wrapTypeNode($innerCallable, $item, $cbPrefix, $registry);
275+
}
276+
}
277+
}
278+
279+
return $value;
280+
}
281+
214282
/**
215283
* Checks if a TypeNode is or contains an ArrayShapeNode.
216284
*/

‎tests/TypeChecking/CallablesAndIterators/CallableEdgeCasesTest.php‎

Lines changed: 82 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -44,7 +44,89 @@ public function getBound(): Closure
4444
}
4545
}
4646

47+
/**
48+
* @phpstan-type LocalHandlerFn callable(int): string
49+
*/
50+
class TypeAliasHolderFixture
51+
{
52+
}
53+
54+
/**
55+
* Valid: Explicitly imports type alias per PHPStan specification
56+
*
57+
* @phpstan-import-type LocalHandlerFn from TypeAliasHolderFixture
58+
*/
59+
function testFunctionWithImportedAlias(int $x): string
60+
{
61+
/** @var LocalHandlerFn $fn */
62+
$fn = fn (int $n): string => "aliased: {$n}";
63+
64+
return $fn($x);
65+
}
66+
67+
function testFunctionWithoutImportedAlias(): void
68+
{
69+
/** @var LocalHandlerFn $fn */
70+
$fn = fn (int $n): string => "aliased: {$n}";
71+
}
72+
73+
function testFunctionWithNonExistentClass(): void
74+
{
75+
/** @var HandlerFnClassNotExist $fn */
76+
$fn = fn (int $n): string => "aliased: {$n}";
77+
}
78+
4779
describe('Callable & Closure Edge Cases', function () {
80+
describe('Inline Variable Callable Validations', function () {
81+
test('rejects non-callable string assigned to @var callable variable', function () {
82+
expect(function () {
83+
/** @var callable(int): string $fn */
84+
$fn = 'not a callable at all';
85+
})->toThrow(TypeError::class, 'must be of type callable');
86+
});
87+
88+
test('rejects integer assigned to @var callable variable', function () {
89+
expect(function () {
90+
/** @var callable(int): string $fn */
91+
$fn = 42;
92+
})->toThrow(TypeError::class, 'must be of type callable');
93+
});
94+
95+
test('rejects non-closure string assigned to @var Closure variable', function () {
96+
expect(function () {
97+
/** @var Closure(int): string $fn */
98+
$fn = 'strlen';
99+
})->toThrow(TypeError::class, 'must be of type Closure');
100+
});
101+
102+
test('wraps callable nested inside array shape and enforces return type on invocation', function () {
103+
/** @var array{handler: callable(int): string} $config */
104+
$config = ['handler' => fn (int $x) => 42];
105+
106+
expect(fn () => $config['handler'](42))
107+
->toThrow(TypeError::class, 'Callback return value must be of type string, int (42) given')
108+
;
109+
});
110+
111+
test('resolves and wraps callable type alias when explicitly imported via @phpstan-import-type', function () {
112+
$result = testFunctionWithImportedAlias(42);
113+
114+
expect($result)->toBe('aliased: 42');
115+
});
116+
117+
test('strictly rejects closure when type alias was NOT imported with @phpstan-import-type', function () {
118+
expect(fn () => testFunctionWithoutImportedAlias())
119+
->toThrow(TypeError::class, 'must be of type LocalHandlerFn, Closure given')
120+
;
121+
});
122+
123+
test('strictly rejects closure when variable is typed with a non-existent class', function () {
124+
expect(fn () => testFunctionWithNonExistentClass())
125+
->toThrow(TypeError::class, 'must be of type HandlerFnClassNotExist, Closure given')
126+
;
127+
});
128+
});
129+
48130
describe('Bug 1: Non-Callable Values and Arrays against Closure/Callable constraints', function () {
49131
test('rejects non-callable array on parameter expecting Closure', function () {
50132
expect(fn () => testRequiresClosureParam([new stdClass(), 'nonexistentMethod']))

0 commit comments

Comments
 (0)