-
Notifications
You must be signed in to change notification settings - Fork 159
/
Copy pathMultipleEmptyLinesSniff.php
81 lines (72 loc) · 2.46 KB
/
MultipleEmptyLinesSniff.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento2\Sniffs\Whitespace;
use PHP_CodeSniffer\Files\File;
use PHP_CodeSniffer\Sniffs\Sniff;
/**
* Detects possible usage of multiple blank lines in a row.
*/
class MultipleEmptyLinesSniff implements Sniff
{
/**
* String representation of warning.
*
* @var string
*/
protected $warningMessage = 'Code must not contain multiple empty lines in a row; found %s empty lines.';
/**
* Warning violation code.
*
* @var string
*/
protected $warningCode = 'MultipleEmptyLines';
/**
* @inheritdoc
*/
public function register()
{
return [T_WHITESPACE];
}
/**
* @inheritdoc
*/
public function process(File $phpcsFile, $stackPtr)
{
$tokens = $phpcsFile->getTokens();
if ($phpcsFile->hasCondition($stackPtr, T_FUNCTION)
|| $phpcsFile->hasCondition($stackPtr, T_CLASS)
|| $phpcsFile->hasCondition($stackPtr, T_INTERFACE)
) {
if ($tokens[$stackPtr - 1]['line'] < $tokens[$stackPtr]['line']
&& $tokens[$stackPtr - 2]['line'] === $tokens[$stackPtr - 1]['line']
) {
// This is an empty line and the line before this one is not
// empty, so this could be the start of a multiple empty line block
$next = $phpcsFile->findNext(T_WHITESPACE, $stackPtr, null, true);
$lines = $tokens[$next]['line'] - $tokens[$stackPtr]['line'];
if ($lines > 1) {
$fix = $phpcsFile->addFixableWarning(
$this->warningMessage,
$stackPtr,
$this->warningCode,
[$lines]
);
if ($fix) {
// $stackPtr + 1 to keep one empty line.
// $next - 1 to keep the indentation
for ($i = $stackPtr + 1; $i < $next - 1; $i++) {
$phpcsFile->fixer->replaceToken($i, '');
}
// Handle case where the next line isn't indented
if ($tokens[$next - 1]['content'] === PHP_EOL) {
$phpcsFile->fixer->replaceToken($next - 1, '');
}
}
}
}
}
}
}