Passed
Push — master ( 4ebeec...f195ba )
by Gerrit
02:48
created

CorrectOrderInVarDocCommentFixer::applyFix()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 26

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 13
CRAP Score 3

Importance

Changes 0
Metric Value
dl 0
loc 26
ccs 13
cts 13
cp 1
rs 9.504
c 0
b 0
f 0
cc 3
nc 3
nop 2
crap 3
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 CorrectOrderInVarDocCommentFixer extends AbstractFixer
22
{
23
24
    public function getName()
25
    {
26
        return 'Addiks/correct_order_in_var_doccomment';
27
    }
28
29
    /**
30
     * {@inheritdoc}
31
     */
32 1
    public function getDefinition()
33
    {
34 1
        return new FixerDefinition(
35 1
            'Corrects the order of variable and typedeclaration in a @var doccomment.',
36
            [
37 1
                new CodeSample(
38 1
                    '<?php
39
40
/** @var string $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
    /**
56
     * {@inheritdoc}
57
     */
58 3
    protected function applyFix(\SplFileInfo $file, Tokens $tokens): void
59
    {
60
61
        /** @var string $pattern */
62 3
        $pattern = "/(\@var )(\\$[a-zA-Z0-9_]+)( )([a-zA-Z0-9_\\\\]+)/is";
63
64 3
        $pattern = str_replace('*', '\\*', $pattern);
65 3
        $pattern = str_replace(' ', '\s+', $pattern);
66
67 3
        foreach ($tokens as $index => $token) {
68
            /** @var Token $token */
69
70 3
            if ($token->isGivenKind([T_DOC_COMMENT])) {
71
                /** @var string $content */
72 3
                $content = $token->getContent();
73
74
                $content = preg_replace_callback($pattern, function(array $matches) {
75 2
                    array_shift($matches);
76 2
                    [$matches[1], $matches[3]] = [$matches[3], $matches[1]];
77 2
                    return implode('', $matches);
78 3
                }, $content);
79
80 3
                $tokens[$index] = new Token([T_DOC_COMMENT, $content]);
81
            }
82
        }
83 3
    }
84
85
}
86