Passed
Push — master ( f195ba...c3313b )
by Gerrit
01:29
created

NullableInDocCommentFixer::getPriority()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 2
cts 2
cp 1
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 0
crap 1
1
<?php
2
/**
3
 * Copyright (C) 2019 Gerrit Addiks.
4
 * This package (including this file) was released under the terms of the GPL-3.0.
5
 * You should have received a copy of the GNU General Public License along with this program.
6
 * If not, see <http://www.gnu.org/licenses/> or send me a mail so i can send you a copy.
7
 *
8
 * @license GPL-3.0
9
 *
10
 * @author Gerrit Addiks <[email protected]>
11
 */
12
13
namespace Addiks\MorePhpCsFixers\DocComment;
14
15
use PhpCsFixer\AbstractFixer;
16
use PhpCsFixer\FixerDefinition\FixerDefinition;
17
use PhpCsFixer\FixerDefinition\CodeSample;
18
use PhpCsFixer\Tokenizer\Tokens;
19
use PhpCsFixer\Tokenizer\Token;
20
21
final class NullableInDocCommentFixer extends AbstractFixer
22
{
23
24
    public function getName()
25
    {
26
        return 'Addiks/nullable_in_doccomment';
27
    }
28
29
    /**
30
     * {@inheritdoc}
31
     */
32 1
    public function getDefinition()
33
    {
34 1
        return new FixerDefinition(
35 1
            'Normalizes nullable-notations in doccomments.',
36
            [
37 1
                new CodeSample(
38 1
                    '<?php
39
40
/** @var string|null $foo */
41
'
42
                ),
43
            ]
44
        );
45
    }
46
47
    /**
48
     * {@inheritdoc}
49
     */
50 3
    public function isCandidate(Tokens $tokens)
51
    {
52 3
        return $tokens->isTokenKindFound(T_DOC_COMMENT);
53
    }
54
55 1
    public function getPriority()
56
    {
57 1
        return -10;
58
    }
59
60
    /**
61
     * {@inheritdoc}
62
     */
63 3
    protected function applyFix(\SplFileInfo $file, Tokens $tokens): void
64
    {
65
66
        /** @var string $pattern */
67 3
        $pattern = "/(\@var )(\?)([a-zA-Z0-9_\\\\]+)/is";
68
69 3
        $pattern = str_replace('*', '\\*', $pattern);
70 3
        $pattern = str_replace(' ', '\s+', $pattern);
71
72 3
        foreach ($tokens as $index => $token) {
73
            /** @var Token $token */
74
75 3
            if ($token->isGivenKind([T_DOC_COMMENT])) {
76
                /** @var string $content */
77 3
                $content = $token->getContent();
78
79
                $content = preg_replace_callback($pattern, function(array $matches) {
80 2
                    array_shift($matches);
81 2
                    $matches[1] = "";
82 2
                    $matches[2] .= "|null";
83 2
                    return implode('', $matches);
84 3
                }, $content);
85
86 3
                $tokens[$index] = new Token([T_DOC_COMMENT, $content]);
87
            }
88
        }
89 3
    }
90
91
}
92