Skip to content

Commit 99ddeaf

Browse files
rvanvelzenondrejmirtes
authored andcommitted
Improve parenthesization for union types
1 parent 85ab8cf commit 99ddeaf

File tree

4 files changed

+41
-1
lines changed

4 files changed

+41
-1
lines changed

src/Type/UnionType.php

+3-1
Original file line numberDiff line numberDiff line change
@@ -203,9 +203,11 @@ public function describe(VerbosityLevel $level): string
203203
{
204204
$joinTypes = static function (array $types) use ($level): string {
205205
$typeNames = [];
206-
foreach ($types as $type) {
206+
foreach ($types as $i => $type) {
207207
if ($type instanceof ClosureType || $type instanceof CallableType || $type instanceof TemplateUnionType) {
208208
$typeNames[] = sprintf('(%s)', $type->describe($level));
209+
} elseif ($type instanceof TemplateType && $i < (count($types) - 1) && ($level->isTypeOnly() || $level->isValue())) {
210+
$typeNames[] = sprintf('(%s)', $type->describe($level));
209211
} elseif ($type instanceof IntersectionType) {
210212
$intersectionDescription = $type->describe($level);
211213
if (strpos($intersectionDescription, '&') !== false) {

src/Type/VerbosityLevel.php

+5
Original file line numberDiff line numberDiff line change
@@ -60,6 +60,11 @@ public function isTypeOnly(): bool
6060
return $this->value === self::TYPE_ONLY;
6161
}
6262

63+
public function isValue(): bool
64+
{
65+
return $this->value === self::VALUE;
66+
}
67+
6368
/** @api */
6469
public static function getRecommendedLevelByType(Type $acceptingType, ?Type $acceptedType = null): self
6570
{

tests/PHPStan/Rules/Generators/YieldTypeRuleTest.php

+10
Original file line numberDiff line numberDiff line change
@@ -59,4 +59,14 @@ public function testRule(): void
5959
]);
6060
}
6161

62+
public function testBug7484(): void
63+
{
64+
$this->analyse([__DIR__ . '/data/bug-7484.php'], [
65+
[
66+
'Generator expects key type K of int|string, (K of int)|string given.',
67+
21,
68+
],
69+
]);
70+
}
71+
6272
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
<?php
2+
3+
namespace Bug7484;
4+
5+
/**
6+
* @template K of int|string
7+
* @template V
8+
* @param iterable<K, V> $iterable
9+
* @return iterable<K, V>
10+
*/
11+
function changeKeyCase(
12+
iterable $iterable,
13+
int $case = CASE_LOWER
14+
): iterable {
15+
$callable = $case === CASE_LOWER ? 'strtolower' : 'strtoupper';
16+
foreach ($iterable as $key => $value) {
17+
if (is_string($key)) {
18+
$key = $callable($key);
19+
}
20+
21+
yield $key => $value;
22+
}
23+
}

0 commit comments

Comments
 (0)