@@ -253,12 +253,17 @@ private function buildArrayType(
253
253
$ countGroups = count ($ captureGroups );
254
254
$ i = 0 ;
255
255
foreach ($ captureGroups as $ captureGroup ) {
256
+ $ groupValueType = $ valueType ;
257
+
256
258
if (!$ wasMatched ->yes ()) {
257
259
$ optional = true ;
258
260
} else {
259
261
if ($ i < $ countGroups - $ trailingOptionals ) {
260
262
$ optional = false ;
261
- } elseif (($ flags & PREG_UNMATCHED_AS_NULL ) !== 0 && $ this ->phpVersion ->supportsPregUnmatchedAsNull ()) {
263
+ if ($ this ->containsUnmatchedAsNull ($ flags )) {
264
+ $ groupValueType = TypeCombinator::removeNull ($ groupValueType );
265
+ }
266
+ } elseif ($ this ->containsUnmatchedAsNull ($ flags )) {
262
267
$ optional = false ;
263
268
} else {
264
269
$ optional = $ captureGroup ->isOptional ();
@@ -268,14 +273,14 @@ private function buildArrayType(
268
273
if ($ captureGroup ->isNamed ()) {
269
274
$ builder ->setOffsetValueType (
270
275
$ this ->getKeyType ($ captureGroup ->getName ()),
271
- $ valueType ,
276
+ $ groupValueType ,
272
277
$ optional ,
273
278
);
274
279
}
275
280
276
281
$ builder ->setOffsetValueType (
277
282
$ this ->getKeyType ($ i + 1 ),
278
- $ valueType ,
283
+ $ groupValueType ,
279
284
$ optional ,
280
285
);
281
286
@@ -285,6 +290,11 @@ private function buildArrayType(
285
290
return $ builder ->getArray ();
286
291
}
287
292
293
+ private function containsUnmatchedAsNull (int $ flags ): bool
294
+ {
295
+ return ($ flags & PREG_UNMATCHED_AS_NULL ) !== 0 && $ this ->phpVersion ->supportsPregUnmatchedAsNull ();
296
+ }
297
+
288
298
private function getKeyType (int |string $ key ): Type
289
299
{
290
300
if (is_string ($ key )) {
@@ -298,7 +308,7 @@ private function getValueType(int $flags): Type
298
308
{
299
309
$ valueType = new StringType ();
300
310
$ offsetType = IntegerRangeType::fromInterval (0 , null );
301
- if (( $ flags & PREG_UNMATCHED_AS_NULL ) !== 0 && $ this ->phpVersion -> supportsPregUnmatchedAsNull ( )) {
311
+ if ($ this ->containsUnmatchedAsNull ( $ flags )) {
302
312
$ valueType = TypeCombinator::addNull ($ valueType );
303
313
// unmatched groups return -1 as offset
304
314
$ offsetType = IntegerRangeType::fromInterval (-1 , null );
0 commit comments