Skip to content

Commit 5b80c7a

Browse files
✨ Add check for twig empty lines
1 parent 3c1e079 commit 5b80c7a

File tree

4 files changed

+80
-0
lines changed

4 files changed

+80
-0
lines changed
Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
<?php
2+
3+
namespace TwigCS\Ruleset\Generic;
4+
5+
use \Exception;
6+
use TwigCS\Sniff\AbstractSniff;
7+
use TwigCS\Token\Token;
8+
9+
/**
10+
* Checks that there are not 2 empty lines following each other.
11+
*/
12+
class EmptyLinesSniff extends AbstractSniff
13+
{
14+
/**
15+
* @param int $tokenPosition
16+
* @param Token[] $tokens
17+
*
18+
* @return Token
19+
*
20+
* @throws Exception
21+
*/
22+
public function process(int $tokenPosition, array $tokens)
23+
{
24+
$token = $tokens[$tokenPosition];
25+
26+
if ($this->isTokenMatching($token, Token::EOL_TYPE)) {
27+
$i = 0;
28+
while (isset($tokens[$tokenPosition - ($i + 1)])
29+
&& $this->isTokenMatching($tokens[$tokenPosition - ($i + 1)], Token::EOL_TYPE)
30+
) {
31+
$i++;
32+
}
33+
34+
if (1 < $i) {
35+
$fix = $this->addFixableMessage(
36+
$this::MESSAGE_TYPE_ERROR,
37+
sprintf('More than 1 empty lines are not allowed, found %d', $i),
38+
$token
39+
);
40+
41+
if ($fix) {
42+
$this->fixer->beginChangeset();
43+
while ($i > 1) {
44+
$this->fixer->replaceToken($tokenPosition - $i, '');
45+
$i--;
46+
}
47+
$this->fixer->endChangeset();
48+
}
49+
}
50+
}
51+
52+
return $token;
53+
}
54+
}
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
<div class="error">
2+
3+
</div>
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
<div class="error">
2+
3+
4+
</div>
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
<?php
2+
3+
namespace TwigCS\Tests\Ruleset\Generic;
4+
5+
use TwigCS\Ruleset\Generic\EmptyLinesSniff;
6+
use TwigCS\Tests\AbstractSniffTest;
7+
8+
/**
9+
* Class EmptyLinesTest
10+
*/
11+
class EmptyLinesTest extends AbstractSniffTest
12+
{
13+
public function testSniff()
14+
{
15+
$this->checkGenericSniff(new EmptyLinesSniff(), [
16+
[3, 1],
17+
]);
18+
}
19+
}

0 commit comments

Comments
 (0)