Skip to content

Commit

Permalink
Improve parenthesization for union types
Browse files Browse the repository at this point in the history
  • Loading branch information
rvanvelzen committed Jun 17, 2022
1 parent 85ab8cf commit c6924aa
Show file tree
Hide file tree
Showing 4 changed files with 41 additions and 1 deletion.
4 changes: 3 additions & 1 deletion src/Type/UnionType.php
Expand Up @@ -203,9 +203,11 @@ public function describe(VerbosityLevel $level): string
{
$joinTypes = static function (array $types) use ($level): string {
$typeNames = [];
foreach ($types as $type) {
foreach ($types as $i => $type) {
if ($type instanceof ClosureType || $type instanceof CallableType || $type instanceof TemplateUnionType) {
$typeNames[] = sprintf('(%s)', $type->describe($level));
} elseif ($type instanceof TemplateType && $i < (count($types) - 1) && ($level->isTypeOnly() || $level->isValue())) {
$typeNames[] = sprintf('(%s)', $type->describe($level));
} elseif ($type instanceof IntersectionType) {
$intersectionDescription = $type->describe($level);
if (strpos($intersectionDescription, '&') !== false) {
Expand Down
5 changes: 5 additions & 0 deletions src/Type/VerbosityLevel.php
Expand Up @@ -60,6 +60,11 @@ public function isTypeOnly(): bool
return $this->value === self::TYPE_ONLY;
}

public function isValue(): bool
{
return $this->value === self::VALUE;
}

/** @api */
public static function getRecommendedLevelByType(Type $acceptingType, ?Type $acceptedType = null): self
{
Expand Down
10 changes: 10 additions & 0 deletions tests/PHPStan/Rules/Generators/YieldTypeRuleTest.php
Expand Up @@ -59,4 +59,14 @@ public function testRule(): void
]);
}

public function testBug7484(): void
{
$this->analyse([__DIR__ . '/data/bug-7484.php'], [
[
'Generator expects key type K of int|string, (K of int)|string given.',
21,
],
]);
}

}
23 changes: 23 additions & 0 deletions tests/PHPStan/Rules/Generators/data/bug-7484.php
@@ -0,0 +1,23 @@
<?php

namespace Bug7484;

/**
* @template K of int|string
* @template V
* @param iterable<K, V> $iterable
* @return iterable<K, V>
*/
function changeKeyCase(
iterable $iterable,
int $case = CASE_LOWER,
): iterable {
$callable = $case === CASE_LOWER ? 'strtolower' : 'strtoupper';
foreach ($iterable as $key => $value) {
if (is_string($key)) {
$key = $callable($key);
}

yield $key => $value;
}
}

0 comments on commit c6924aa

Please sign in to comment.