Skip to content

Commit 0f85efc

Browse files
committed
Enhance DocblockNormalizer to normalize variadic tuple spread syntax and add tests for new functionality
1 parent 07869d3 commit 0f85efc

4 files changed

Lines changed: 260 additions & 3 deletions

File tree

‎src/Internal/Docblock/DocblockNormalizer.php‎

Lines changed: 19 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
/**
88
* Normalizes PHPDoc comment strings before AST parsing.
99
* Converts class-specific shapes like stdClass{id: int} into intersection shapes (stdClass & object{id: int}).
10+
* Normalizes variadic tuple spread syntax (...Type[] and ...list<Type>) into PHPStan-compliant ...<Type> syntax.
1011
*
1112
* @internal
1213
*/
@@ -45,19 +46,34 @@ public static function normalize(string $doc): string
4546
$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;
4647
}
4748

49+
if (str_contains($doc, '...')) {
50+
$doc = preg_replace('/(\.\.\.\s*)([a-zA-Z0-9_\x80-\xff\\\\]+)\[\]/', '$1<$2>', $doc) ?? $doc;
51+
$doc = preg_replace('/(\.\.\.\s*)(?:list|array)<([^>]+)>/', '$1<$2>', $doc) ?? $doc;
52+
}
53+
4854
if (! str_contains($doc, '{')) {
4955
return $doc;
5056
}
5157

58+
return self::normalizeShapes($doc);
59+
}
60+
61+
/**
62+
* Normalizes custom class shapes supporting arbitrary nested balanced braces via PCRE recursion.
63+
*/
64+
private static function normalizeShapes(string $doc): string
65+
{
66+
$pattern = '/(\\\\?[a-zA-Z_\x80-\xff][\\\\a-zA-Z0-9_\x80-\xff]*)\s*\{((?:[^{}]+|\{(?2)\})*)\}/s';
67+
5268
return preg_replace_callback(
53-
'/(\\\\?[a-zA-Z_\x80-\xff][\\\\a-zA-Z0-9_\x80-\xff]*)\s*\{([^}]+)\}/s',
69+
$pattern,
5470
function (array $matches): string {
5571
$className = $matches[1];
56-
$shapeBody = $matches[2];
72+
$shapeBody = self::normalizeShapes($matches[2]);
5773

5874
$lower = strtolower(ltrim($className, '\\'));
5975
if (\in_array($lower, self::BUILTIN_SHAPE_KEYWORDS, strict: true)) {
60-
return $matches[0];
76+
return $className . '{' . $shapeBody . '}';
6177
}
6278

6379
return '(' . $className . '&object{' . $shapeBody . '})';

‎src/Internal/Validator/ArrayShapeValidator.php‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,11 @@ public function validate(mixed $value, TypeNode $node, string $context, TypeVali
2626

2727
/** @var ArrayShapeNode $shapeNode */
2828
$shapeNode = $node;
29+
30+
if ($shapeNode->kind === ArrayShapeNode::KIND_LIST && \count($value) > 0 && ! array_is_list($value)) {
31+
return ErrorFactory::createError($context . ' must be a list, ' . TypeFormatter::formatGivenValue($value) . ' given');
32+
}
33+
2934
$knownKeys = [];
3035
$nextAutoIndex = 0;
3136
$matchedKeysCount = 0;

‎tests/Internal/Docblock/DocblockNormalizerTest.php‎

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -78,6 +78,63 @@
7878
});
7979
});
8080

81+
describe('Variadic Tuple and Spread Syntax Normalization', function () {
82+
test('normalizes trailing ...Type[] spread syntax to ...<Type>', function () {
83+
$doc = '/** @param array{string, int, ...float[]} $tuple */';
84+
$expected = '/** @param array{string, int, ...<float>} $tuple */';
85+
86+
expect(DocblockNormalizer::normalize($doc))->toBe($expected);
87+
});
88+
89+
test('normalizes trailing ...list<Type> spread syntax to ...<Type>', function () {
90+
$doc = '/** @param array{string, ...list<positive-int>} $data */';
91+
$expected = '/** @param array{string, ...<positive-int>} $data */';
92+
93+
expect(DocblockNormalizer::normalize($doc))->toBe($expected);
94+
});
95+
96+
test('normalizes trailing ...array<Type> spread syntax to ...<Type>', function () {
97+
$doc = '/** @param array{id: int, ...array<string>} $payload */';
98+
$expected = '/** @param array{id: int, ...<string>} $payload */';
99+
100+
expect(DocblockNormalizer::normalize($doc))->toBe($expected);
101+
});
102+
103+
test('preserves already-compliant ...<Type> and ...<Key, Value> syntax', function () {
104+
$doc1 = '/** @param array{string, int, ...<float>} $tuple */';
105+
expect(DocblockNormalizer::normalize($doc1))->toBe($doc1);
106+
107+
$doc2 = '/** @param array{id: int, ...<string, string>} $options */';
108+
expect(DocblockNormalizer::normalize($doc2))->toBe($doc2);
109+
110+
$doc3 = '/** @param array{string, int, ...} $bareTuple */';
111+
expect(DocblockNormalizer::normalize($doc3))->toBe($doc3);
112+
});
113+
});
114+
115+
describe('Nested Braces in Custom Class Shapes', function () {
116+
test('normalizes custom class shape containing nested array shape', function () {
117+
$doc = '/** @param stdClass{id: int, config: array{debug: bool}} $data */';
118+
$expected = '/** @param (stdClass&object{id: int, config: array{debug: bool}}) $data */';
119+
120+
expect(DocblockNormalizer::normalize($doc))->toBe($expected);
121+
});
122+
123+
test('normalizes custom class shape containing multi-level nested array shapes', function () {
124+
$doc = '/** @param stdClass{id: int, a: array{b: array{c: string}}} $data */';
125+
$expected = '/** @param (stdClass&object{id: int, a: array{b: array{c: string}}}) $data */';
126+
127+
expect(DocblockNormalizer::normalize($doc))->toBe($expected);
128+
});
129+
130+
test('normalizes nested custom class shapes within custom class shapes', function () {
131+
$doc = '/** @param stdClass{id: int, author: User{name: string}} $data */';
132+
$expected = '/** @param (stdClass&object{id: int, author: (User&object{name: string})}) $data */';
133+
134+
expect(DocblockNormalizer::normalize($doc))->toBe($expected);
135+
});
136+
});
137+
81138
describe('Custom Class Shapes to Intersection Shapes', function () {
82139
test('converts stdClass shapes into intersection shapes', function () {
83140
$doc = '/** @param stdClass{id: int, name: string} $data */';
Lines changed: 179 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,179 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
use TypePHP\Exception\TypeError;
6+
7+
/**
8+
* 1. Open tuple with single value constraint: array{string, int, ...<float>}
9+
*
10+
* @param array{string, int, ...<float>} $tuple
11+
*/
12+
function tddOpenTupleSingleValueType(array $tuple): array
13+
{
14+
return $tuple;
15+
}
16+
17+
/**
18+
* 2. Open tuple with array spread syntax: array{string, int, ...float[]}
19+
*
20+
* @param array{string, int, ...float[]} $tuple
21+
*/
22+
function tddOpenTupleArraySpread(array $tuple): array
23+
{
24+
return $tuple;
25+
}
26+
27+
/**
28+
* 3. Open tuple with list spread syntax: array{string, ...list<positive-int>}
29+
*
30+
* @param array{string, ...list<positive-int>} $data
31+
*/
32+
function tddOpenTupleListSpread(array $data): array
33+
{
34+
return $data;
35+
}
36+
37+
/**
38+
* 4. Bare open tuple (allows any extra elements): array{string, int, ...}
39+
*
40+
* @param array{string, int, ...} $tuple
41+
*/
42+
function tddBareOpenTuple(array $tuple): array
43+
{
44+
return $tuple;
45+
}
46+
47+
/**
48+
* 5. Open associative shape with single value type: array{id: positive-int, ...<string>}
49+
*
50+
* @param array{id: positive-int, ...<string>} $payload
51+
*/
52+
function tddOpenShapeSingleValueType(array $payload): array
53+
{
54+
return $payload;
55+
}
56+
57+
/**
58+
* 6. Open sequential list tuple: list{string, int, ...<float>}
59+
*
60+
* @param list{string, int, ...<float>} $list
61+
*/
62+
function tddOpenListTuple(array $list): array
63+
{
64+
return $list;
65+
}
66+
67+
describe('Open / Variadic Tuples and Shapes (PHPStan Spec Baseline)', function () {
68+
describe('1. Single Value Constraint (...<float>)', function () {
69+
test('accepts tuple with zero extra elements', function () {
70+
expect(tddOpenTupleSingleValueType(['Alice', 10]))->toBe(['Alice', 10]);
71+
});
72+
73+
test('accepts tuple with multiple valid trailing float elements', function () {
74+
expect(tddOpenTupleSingleValueType(['Alice', 10, 1.5, 2.5, 3.5]))
75+
->toBe(['Alice', 10, 1.5, 2.5, 3.5])
76+
;
77+
});
78+
79+
test('rejects tuple when trailing element violates float constraint', function () {
80+
expect(fn () => tddOpenTupleSingleValueType(['Alice', 10, 1.5, 'not_a_float']))
81+
->toThrow(TypeError::class, "['3'] must be of type float")
82+
;
83+
});
84+
});
85+
86+
describe('2. Array Spread Syntax (...float[])', function () {
87+
test('accepts tuple with zero extra elements using array spread', function () {
88+
expect(tddOpenTupleArraySpread(['Bob', 20]))->toBe(['Bob', 20]);
89+
});
90+
91+
test('unwraps float[] so trailing elements are validated as individual floats', function () {
92+
expect(tddOpenTupleArraySpread(['Bob', 20, 1.5, 2.5]))->toBe(['Bob', 20, 1.5, 2.5]);
93+
});
94+
95+
test('rejects trailing element violating unwrapped float constraint', function () {
96+
expect(fn () => tddOpenTupleArraySpread(['Bob', 20, 1.5, 'invalid']))
97+
->toThrow(TypeError::class, "['3'] must be of type float")
98+
;
99+
});
100+
});
101+
102+
describe('3. List Spread Syntax (...list<positive-int>)', function () {
103+
test('unwraps list<positive-int> so trailing elements are validated as positive integers', function () {
104+
expect(tddOpenTupleListSpread(['tag_primary', 10, 20, 30]))
105+
->toBe(['tag_primary', 10, 20, 30])
106+
;
107+
});
108+
109+
test('rejects trailing element violating positive-int constraint', function () {
110+
expect(fn () => tddOpenTupleListSpread(['tag_primary', 10, -5, 30]))
111+
->toThrow(TypeError::class, "['2'] must be of type positive-int")
112+
;
113+
});
114+
});
115+
116+
describe('4. Bare ... Open Tuple (array{string, int, ...})', function () {
117+
test('accepts tuple with zero extra elements', function () {
118+
expect(tddBareOpenTuple(['Alice', 10]))->toBe(['Alice', 10]);
119+
});
120+
121+
test('accepts arbitrary trailing elements of any type', function () {
122+
$data = ['Alice', 10, true, 3.14, new stdClass(), ['nested']];
123+
expect(tddBareOpenTuple($data))->toBe($data);
124+
});
125+
126+
test('still strictly validates the fixed leading elements', function () {
127+
expect(fn () => tddBareOpenTuple([123, 10, 'extra']))
128+
->toThrow(TypeError::class, "['0'] must be of type string")
129+
;
130+
131+
expect(fn () => tddBareOpenTuple(['Alice', 'not_an_int', 'extra']))
132+
->toThrow(TypeError::class, "['1'] must be of type int")
133+
;
134+
});
135+
});
136+
137+
describe('5. Associative Open Shape with Single Value Type (array{id: int, ...<string>})', function () {
138+
test('accepts shape with extra string values under arbitrary keys', function () {
139+
$payload = [
140+
'id' => 1,
141+
'name' => 'Alice',
142+
'role' => 'admin',
143+
'dept' => 'engineering',
144+
];
145+
146+
expect(tddOpenShapeSingleValueType($payload))->toBe($payload);
147+
});
148+
149+
test('rejects extra element when value is not a string', function () {
150+
$badPayload = [
151+
'id' => 1,
152+
'name' => 'Alice',
153+
'count' => 50,
154+
];
155+
156+
expect(fn () => tddOpenShapeSingleValueType($badPayload))
157+
->toThrow(TypeError::class, "['count'] must be of type string")
158+
;
159+
});
160+
});
161+
162+
describe('6. Open Sequential List Tuples (list{string, int, ...<float>})', function () {
163+
test('accepts sequential list with trailing floats', function () {
164+
expect(tddOpenListTuple(['test', 1, 1.1, 2.2]))->toBe(['test', 1, 1.1, 2.2]);
165+
});
166+
167+
test('rejects open list tuple when passed non-sequential associative keys', function () {
168+
$associative = [
169+
0 => 'test',
170+
1 => 1,
171+
'non_sequential' => 1.5,
172+
];
173+
174+
expect(fn () => tddOpenListTuple($associative))
175+
->toThrow(TypeError::class, 'must be a list')
176+
;
177+
});
178+
});
179+
});

0 commit comments

Comments
 (0)