Skip to content

Commit 572cf62

Browse files
committed
Add normalization for unqualified wildcard bitmasks and related tests
1 parent 5e4b12c commit 572cf62

4 files changed

Lines changed: 281 additions & 19 deletions

File tree

‎src/Internal/Docblock/DocblockNormalizer.php‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
* Normalizes PHPDoc comment strings before AST parsing.
99
* Converts class-specific shapes like stdClass{id: int} into intersection shapes (stdClass & object{id: int}).
1010
* Normalizes variadic tuple spread syntax (...Type[] and ...list<Type>) into PHPStan-compliant ...<Type> syntax.
11+
* Normalizes unqualified wildcard bitmasks (int-mask-of<E_*>) into quoted string literals.
1112
*
1213
* @internal
1314
*/
@@ -58,6 +59,10 @@ public static function normalize(string $doc): string
5859
$doc = preg_replace('/(\\\\?[a-zA-Z_\x80-\xff][\\\\a-zA-Z0-9_\x80-\xff]*::[a-zA-Z_\x80-\xff][a-zA-Z0-9_\x80-\xff]*)\s*(\??:)/', '"$1"$2', $doc) ?? $doc;
5960
}
6061

62+
if (str_contains($doc, 'int-mask-of') && str_contains($doc, '*')) {
63+
$doc = preg_replace('/int-mask-of<\s*([a-zA-Z_\x80-\xff][a-zA-Z0-9_\x80-\xff]*\*)\s*>/', 'int-mask-of<"$1">', $doc) ?? $doc;
64+
}
65+
6166
if (str_contains($doc, '...')) {
6267
$doc = preg_replace('/(\.\.\.\s*)([a-zA-Z0-9_\x80-\xff\\\\]+)\[\]/', '$1<$2>', $doc) ?? $doc;
6368
$doc = preg_replace('/(\.\.\.\s*)(?:list|array)<([^>]+)>/', '$1<$2>', $doc) ?? $doc;

‎src/Internal/Validator/GenericValidator.php‎

Lines changed: 106 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -61,6 +61,13 @@ final class GenericValidator implements TypeValidatorInterface
6161
*/
6262
private static array $enumValueCache = [];
6363

64+
/**
65+
* Cache for resolved int-mask-of masks: [$cacheKey] => array{0: int, 1: bool}.
66+
*
67+
* @var array<string, array{0: int, 1: bool}>
68+
*/
69+
private static array $maskOfCache = [];
70+
6471
/**
6572
* Validates a value against a GenericTypeNode AST.
6673
*/
@@ -280,6 +287,18 @@ private function validateIntMask(mixed $value, GenericTypeNode $node, string $co
280287
$allowedMask |= $constVal;
281288
}
282289
}
290+
} elseif ($typeNode instanceof IdentifierTypeNode) {
291+
$constName = $typeNode->name;
292+
if (str_contains($constName, '::')) {
293+
[$className, $name] = explode('::', $constName, 2);
294+
$constVal = $this->resolveConstantValue($className, $name);
295+
} else {
296+
$constVal = $this->resolveConstantValue('', $constName);
297+
}
298+
299+
if (\is_int($constVal)) {
300+
$allowedMask |= $constVal;
301+
}
283302
}
284303
}
285304

@@ -300,36 +319,104 @@ private function validateIntMaskOf(mixed $value, GenericTypeNode $node, string $
300319
$allowedMask = 0;
301320
$foundFlags = false;
302321

322+
$className = '';
323+
$pattern = '';
324+
303325
if ($targetType instanceof ConstTypeNode && $targetType->constExpr instanceof ConstFetchNode) {
304-
$constExpr = $targetType->constExpr;
305-
$fqcn = $constExpr->className;
306-
$pattern = $constExpr->name;
326+
$className = $targetType->constExpr->className;
327+
$pattern = $targetType->constExpr->name;
328+
} elseif ($targetType instanceof ConstTypeNode && $targetType->constExpr instanceof ConstExprStringNode) {
329+
$className = '';
330+
$pattern = $targetType->constExpr->value;
331+
} elseif ($targetType instanceof IdentifierTypeNode) {
332+
if (str_contains($targetType->name, '::')) {
333+
[$className, $pattern] = explode('::', $targetType->name, 2);
334+
} else {
335+
$className = '';
336+
$pattern = $targetType->name;
337+
}
338+
} elseif ($targetType instanceof UnionTypeNode) {
339+
foreach ($targetType->types as $unionMember) {
340+
if ($unionMember instanceof ConstTypeNode) {
341+
$expr = $unionMember->constExpr;
342+
if ($expr instanceof ConstExprIntegerNode) {
343+
$allowedMask |= (int) $expr->value;
344+
$foundFlags = true;
345+
} elseif ($expr instanceof ConstFetchNode) {
346+
$val = $this->resolveConstantValue($expr->className, $expr->name);
347+
if (\is_int($val)) {
348+
$allowedMask |= $val;
349+
$foundFlags = true;
350+
}
351+
}
352+
} elseif ($unionMember instanceof IdentifierTypeNode) {
353+
$name = $unionMember->name;
354+
if (str_contains($name, '::')) {
355+
[$cls, $cName] = explode('::', $name, 2);
356+
$val = $this->resolveConstantValue($cls, $cName);
357+
} else {
358+
$val = $this->resolveConstantValue('', $name);
359+
}
360+
if (\is_int($val)) {
361+
$allowedMask |= $val;
362+
$foundFlags = true;
363+
}
364+
}
365+
}
366+
}
307367

308-
if ($fqcn !== '' && (class_exists($fqcn) || interface_exists($fqcn))) {
309-
$refClass = new \ReflectionClass($fqcn);
368+
if ($pattern !== '') {
369+
$cacheKey = $className !== '' ? "$className::$pattern" : $pattern;
310370

311-
if (str_contains($pattern, '*')) {
312-
$regex = '/^' . str_replace('\*', '.*', preg_quote($pattern, '/')) . '$/i';
313-
foreach ($refClass->getConstants() as $cName => $cValue) {
314-
if (\is_int($cValue) && preg_match($regex, $cName) === 1) {
315-
$allowedMask |= $cValue;
316-
$foundFlags = true;
371+
if (isset(self::$maskOfCache[$cacheKey])) {
372+
[$allowedMask, $foundFlags] = self::$maskOfCache[$cacheKey];
373+
} else {
374+
if ($className !== '') {
375+
if (class_exists($className) || interface_exists($className)) {
376+
$refClass = new \ReflectionClass($className);
377+
378+
if (str_contains($pattern, '*')) {
379+
$regex = '/^' . str_replace('\*', '.*', preg_quote($pattern, '/')) . '$/i';
380+
foreach ($refClass->getConstants() as $cName => $cValue) {
381+
if (\is_int($cValue) && preg_match($regex, $cName) === 1) {
382+
$allowedMask |= $cValue;
383+
$foundFlags = true;
384+
}
385+
}
386+
} else {
387+
$cValue = $this->resolveConstantValue($className, $pattern);
388+
if (\is_int($cValue)) {
389+
$allowedMask |= $cValue;
390+
$foundFlags = true;
391+
} elseif (\is_array($cValue)) {
392+
foreach ($cValue as $item) {
393+
if (\is_int($item)) {
394+
$allowedMask |= $item;
395+
$foundFlags = true;
396+
}
397+
}
398+
}
317399
}
318400
}
319401
} else {
320-
$cValue = $this->resolveConstantValue($fqcn, $pattern);
321-
if (\is_int($cValue)) {
322-
$allowedMask |= $cValue;
323-
$foundFlags = true;
324-
} elseif (\is_array($cValue)) {
325-
foreach ($cValue as $item) {
326-
if (\is_int($item)) {
327-
$allowedMask |= $item;
402+
if (str_contains($pattern, '*')) {
403+
$regex = '/^' . str_replace('\*', '.*', preg_quote($pattern, '/')) . '$/i';
404+
foreach (get_defined_constants() as $cName => $cValue) {
405+
if (\is_int($cValue) && preg_match($regex, $cName) === 1) {
406+
$allowedMask |= $cValue;
328407
$foundFlags = true;
329408
}
330409
}
410+
} else {
411+
$cValue = $this->resolveConstantValue('', $pattern);
412+
if (\is_int($cValue)) {
413+
$allowedMask |= $cValue;
414+
$foundFlags = true;
415+
}
331416
}
332417
}
418+
419+
self::$maskOfCache[$cacheKey] = [$allowedMask, $foundFlags];
333420
}
334421
}
335422

‎tests/Internal/Docblock/DocblockNormalizerTest.php‎

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -164,6 +164,31 @@
164164
});
165165
});
166166

167+
describe('Unqualified int-mask-of Wildcard Normalization', function () {
168+
test('quotes unqualified wildcard constant patterns in int-mask-of', function () {
169+
$doc1 = '/** @param int-mask-of<E_*> $flags */';
170+
$expected1 = '/** @param int-mask-of<"E_*"> $flags */';
171+
expect(DocblockNormalizer::normalize($doc1))->toBe($expected1);
172+
173+
$doc2 = '/** @param int-mask-of<JSON_*> $flags */';
174+
$expected2 = '/** @param int-mask-of<"JSON_*"> $flags */';
175+
expect(DocblockNormalizer::normalize($doc2))->toBe($expected2);
176+
});
177+
178+
test('preserves class-scoped int-mask-of wildcards without quoting', function () {
179+
$doc1 = '/** @param int-mask-of<Permissions::*> $mask */';
180+
expect(DocblockNormalizer::normalize($doc1))->toBe($doc1);
181+
182+
$doc2 = '/** @param int-mask-of<HttpOptions::FLAG_*> $flags */';
183+
expect(DocblockNormalizer::normalize($doc2))->toBe($doc2);
184+
});
185+
186+
test('does not double-quote already quoted int-mask-of wildcards', function () {
187+
$doc = '/** @param int-mask-of<"E_*"> $flags */';
188+
expect(DocblockNormalizer::normalize($doc))->toBe($doc);
189+
});
190+
});
191+
167192
describe('Variadic Tuple and Spread Syntax Normalization', function () {
168193
test('normalizes trailing ...Type[] spread syntax to ...<Type>', function () {
169194
$doc = '/** @param array{string, int, ...float[]} $tuple */';
Lines changed: 145 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,145 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
use TypePHP\Exception\TypeError;
6+
7+
/**
8+
* 1. Single composite global constant
9+
*
10+
* @param int-mask<E_ALL> $levels
11+
*/
12+
function testGlobalErrorLevelsMask(int $levels): int
13+
{
14+
return $levels;
15+
}
16+
17+
/**
18+
* 2. Specific individual global constants
19+
*
20+
* @param int-mask<E_ERROR, E_WARNING> $levels
21+
*/
22+
function testSpecificGlobalFlagsMask(int $levels): int
23+
{
24+
return $levels;
25+
}
26+
27+
/**
28+
* 3. Wildcard pattern of global constants
29+
*
30+
* @param int-mask-of<E_*> $levels
31+
*/
32+
function testGlobalWildcardErrorMask(int $levels): int
33+
{
34+
return $levels;
35+
}
36+
37+
/**
38+
* 4. Other extension global constants (JSON)
39+
*
40+
* @param int-mask<JSON_PRETTY_PRINT, JSON_UNESCAPED_SLASHES> $flags
41+
*/
42+
function testJsonFlagsMask(int $flags): int
43+
{
44+
return $flags;
45+
}
46+
47+
/**
48+
* 5. Return type contract with global constant int-mask
49+
*
50+
* @return int-mask<E_ALL>
51+
*/
52+
function returnGlobalErrorMask(int $levels): int
53+
{
54+
return $levels;
55+
}
56+
57+
describe('Global Constant Bitmasks (int-mask<E_ALL> and int-mask-of<E_*>)', function () {
58+
describe('Single Global Composite Constant (int-mask<E_ALL>)', function () {
59+
test('accepts E_ALL constant itself', function () {
60+
expect(testGlobalErrorLevelsMask(E_ALL))->toBe(E_ALL);
61+
});
62+
63+
test('accepts single error bit included in E_ALL', function () {
64+
expect(testGlobalErrorLevelsMask(E_ERROR))->toBe(E_ERROR);
65+
expect(testGlobalErrorLevelsMask(E_WARNING))->toBe(E_WARNING);
66+
});
67+
68+
test('accepts combination of error bits included in E_ALL', function () {
69+
$mask = E_ERROR | E_WARNING | E_PARSE;
70+
expect(testGlobalErrorLevelsMask($mask))->toBe($mask);
71+
});
72+
73+
test('accepts 0 as valid empty bitmask', function () {
74+
expect(testGlobalErrorLevelsMask(0))->toBe(0);
75+
});
76+
77+
test('rejects bit outside of E_ALL', function () {
78+
expect(fn () => testGlobalErrorLevelsMask(1 << 30))
79+
->toThrow(TypeError::class, 'must be a valid bitmask combination of the allowed flags')
80+
;
81+
});
82+
});
83+
84+
describe('Multiple Global Constants (int-mask<E_ERROR, E_WARNING>)', function () {
85+
test('accepts allowed flags and combination', function () {
86+
expect(testSpecificGlobalFlagsMask(E_ERROR))->toBe(E_ERROR);
87+
expect(testSpecificGlobalFlagsMask(E_WARNING))->toBe(E_WARNING);
88+
expect(testSpecificGlobalFlagsMask(E_ERROR | E_WARNING))->toBe(E_ERROR | E_WARNING);
89+
expect(testSpecificGlobalFlagsMask(0))->toBe(0);
90+
});
91+
92+
test('rejects unlisted global constant flag (E_NOTICE)', function () {
93+
expect(fn () => testSpecificGlobalFlagsMask(E_NOTICE))
94+
->toThrow(TypeError::class, 'must be a valid bitmask combination of the allowed flags')
95+
;
96+
});
97+
});
98+
99+
describe('Global Wildcard Constants (int-mask-of<E_*>)', function () {
100+
test('accepts any combination of E_* constants', function () {
101+
expect(testGlobalWildcardErrorMask(E_ERROR | E_WARNING))->toBe(E_ERROR | E_WARNING);
102+
expect(testGlobalWildcardErrorMask(E_ALL))->toBe(E_ALL);
103+
});
104+
105+
test('rejects undeclared bits for global wildcard', function () {
106+
expect(fn () => testGlobalWildcardErrorMask(1 << 30))
107+
->toThrow(TypeError::class, 'must be a valid bitmask combination of the allowed flags')
108+
;
109+
});
110+
});
111+
112+
describe('JSON Global Constants (int-mask<JSON_PRETTY_PRINT, JSON_UNESCAPED_SLASHES>)', function () {
113+
test('accepts valid JSON constants and combinations', function () {
114+
expect(testJsonFlagsMask(JSON_PRETTY_PRINT))->toBe(JSON_PRETTY_PRINT);
115+
expect(testJsonFlagsMask(JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES))->toBe(JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);
116+
});
117+
118+
test('rejects unlisted JSON constant (JSON_FORCE_OBJECT)', function () {
119+
expect(fn () => testJsonFlagsMask(JSON_FORCE_OBJECT))
120+
->toThrow(TypeError::class, 'must be a valid bitmask combination of the allowed flags')
121+
;
122+
});
123+
});
124+
125+
describe('Return Types and Inline @var with Global Constants', function () {
126+
test('validates return type with global constant int-mask', function () {
127+
expect(returnGlobalErrorMask(E_ALL))->toBe(E_ALL);
128+
129+
expect(fn () => returnGlobalErrorMask(1 << 30))
130+
->toThrow(TypeError::class, 'Return value must be a valid bitmask combination of the allowed flags')
131+
;
132+
});
133+
134+
test('validates inline @var with global constant int-mask', function () {
135+
/** @var int-mask<E_ALL> $mask */
136+
$mask = E_ALL;
137+
expect($mask)->toBe(E_ALL);
138+
139+
expect(function () {
140+
/** @var int-mask<E_ALL> $badMask */
141+
$badMask = 1 << 30;
142+
})->toThrow(TypeError::class, 'Variable $badMask must be a valid bitmask combination of the allowed flags');
143+
});
144+
});
145+
});

0 commit comments

Comments
 (0)