Skip to content

Commit

Permalink
TypeAlternationTransformer - fix for "array" type in type alternation
Browse files Browse the repository at this point in the history
  • Loading branch information
kubawerlos authored and keradus committed Apr 28, 2021
1 parent c2f6aa3 commit e362435
Show file tree
Hide file tree
Showing 3 changed files with 41 additions and 3 deletions.
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; }',
];

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,
],
];
}
}

0 comments on commit e362435

Please sign in to comment.