@@ -297,7 +297,8 @@ private function buildArrayType(
297297 $ i = 0 ;
298298 foreach ($ captureGroups as $ captureGroup ) {
299299 $ isTrailingOptional = $ i >= $ countGroups - $ trailingOptionals ;
300- $ groupValueType = $ this ->createGroupValueType ($ captureGroup , $ wasMatched , $ flags , $ isTrailingOptional , $ matchesAll );
300+ $ isLastGroup = $ i === $ countGroups - 1 ;
301+ $ groupValueType = $ this ->createGroupValueType ($ captureGroup , $ wasMatched , $ flags , $ isTrailingOptional , $ isLastGroup , $ matchesAll );
301302 $ optional = $ this ->isGroupOptional ($ captureGroup , $ wasMatched , $ flags , $ isTrailingOptional , $ matchesAll );
302303
303304 if ($ captureGroup ->isNamed ()) {
@@ -390,11 +391,11 @@ private function isGroupOptional(RegexCapturingGroup $captureGroup, TrinaryLogic
390391 return $ optional ;
391392 }
392393
393- private function createGroupValueType (RegexCapturingGroup $ captureGroup , TrinaryLogic $ wasMatched , int $ flags , bool $ isTrailingOptional , bool $ matchesAll ): Type
394+ private function createGroupValueType (RegexCapturingGroup $ captureGroup , TrinaryLogic $ wasMatched , int $ flags , bool $ isTrailingOptional , bool $ isLastGroup , bool $ matchesAll ): Type
394395 {
395- $ groupValueType = $ this ->getValueType ($ captureGroup ->getType (), $ flags , $ matchesAll );
396-
397396 if ($ matchesAll ) {
397+ $ groupValueType = $ this ->getValueType ($ captureGroup ->getType (), $ flags , $ matchesAll );
398+
398399 if (!$ isTrailingOptional && $ this ->containsUnmatchedAsNull ($ flags , $ matchesAll ) && !$ captureGroup ->isOptional ()) {
399400 $ groupValueType = TypeCombinator::removeNull ($ groupValueType );
400401 }
@@ -411,16 +412,22 @@ private function createGroupValueType(RegexCapturingGroup $captureGroup, Trinary
411412 return $ groupValueType ;
412413 }
413414
415+ if (!$ isLastGroup && !$ this ->containsUnmatchedAsNull ($ flags , $ matchesAll ) && $ captureGroup ->isOptional ()) {
416+ $ groupValueType = $ this ->getValueType (
417+ TypeCombinator::union ($ captureGroup ->getType (), new ConstantStringType ('' )),
418+ $ flags ,
419+ $ matchesAll ,
420+ );
421+ } else {
422+ $ groupValueType = $ this ->getValueType ($ captureGroup ->getType (), $ flags , $ matchesAll );
423+ }
424+
414425 if ($ wasMatched ->yes ()) {
415426 if (!$ isTrailingOptional && $ this ->containsUnmatchedAsNull ($ flags , $ matchesAll ) && !$ captureGroup ->isOptional ()) {
416427 $ groupValueType = TypeCombinator::removeNull ($ groupValueType );
417428 }
418429 }
419430
420- if (!$ isTrailingOptional && !$ this ->containsUnmatchedAsNull ($ flags , $ matchesAll ) && $ captureGroup ->isOptional ()) {
421- $ groupValueType = TypeCombinator::union ($ groupValueType , new ConstantStringType ('' ));
422- }
423-
424431 return $ groupValueType ;
425432 }
426433
0 commit comments