Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

TypeAlternationTransformer - fix for "array" type in type alternation #5660

Merged
merged 1 commit into from Apr 28, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
7 changes: 4 additions & 3 deletions src/Tokenizer/Transformer/TypeAlternationTransformer.php
Expand Up @@ -18,7 +18,8 @@
use PhpCsFixer\Tokenizer\Tokens;

/**
* Transform `|` operator into CT::T_TYPE_ALTERNATION in `} catch (ExceptionType1 | ExceptionType2 $e) {`.
* Transform `|` operator into CT::T_TYPE_ALTERNATION in `function foo(Type1 | Type2 $x) {`
* or `} catch (ExceptionType1 | ExceptionType2 $e) {`.
*
* @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
*
Expand All @@ -31,7 +32,7 @@ final class TypeAlternationTransformer extends AbstractTransformer
*/
public function getPriority()
{
// needs to run after TypeColonTransformer
// needs to run after ArrayTypehintTransformer and TypeColonTransformer
return -15;
}

Expand All @@ -54,7 +55,7 @@ public function process(Tokens $tokens, Token $token, $index)

$prevIndex = $tokens->getPrevMeaningfulToken($index);

if (!$tokens[$prevIndex]->isGivenKind(T_STRING)) {
if (!$tokens[$prevIndex]->isGivenKind([T_STRING, CT::T_ARRAY_TYPEHINT])) {
return;
}

Expand Down
13 changes: 13 additions & 0 deletions tests/Fixer/ClassNotation/VisibilityRequiredFixerTest.php
Expand Up @@ -849,5 +849,18 @@ public function provideFix80Cases()
yield [
'<?php class Foo { private int | /* or empty */ null $foo; }',
];

yield [
'<?php class Foo { private array|null $foo; }',
];

yield [
'<?php class Foo { private null|array $foo; }',
];
kubawerlos marked this conversation as resolved.
Show resolved Hide resolved

yield [
'<?php class Foo { public static null|array $foo; }',
'<?php class Foo { static null|array $foo; }',
];
}
}
24 changes: 24 additions & 0 deletions tests/Tokenizer/Transformer/TypeAlternationTransformerTest.php
Expand Up @@ -226,5 +226,29 @@ class Foo {
35 => CT::T_TYPE_ALTERNATION,
],
];

yield 'array as first element of types' => [
'<?php function foo(array|bool|null $foo) {}',
[
6 => CT::T_TYPE_ALTERNATION,
8 => CT::T_TYPE_ALTERNATION,
],
];

yield 'array as middle element of types' => [
'<?php function foo(null|array|bool $foo) {}',
[
6 => CT::T_TYPE_ALTERNATION,
8 => CT::T_TYPE_ALTERNATION,
],
];

yield 'array as last element of types' => [
'<?php function foo(null|bool|array $foo) {}',
[
6 => CT::T_TYPE_ALTERNATION,
8 => CT::T_TYPE_ALTERNATION,
],
];
}
}