-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathEmptyLinesRule.php
More file actions
73 lines (57 loc) · 2.04 KB
/
EmptyLinesRule.php
File metadata and controls
73 lines (57 loc) · 2.04 KB
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
<?php
/*
* This file has been created by developers from BitBag.
* Feel free to contact us once you face any issues or want to start
* You can find more information about us on https://bitbag.io and write us
* an email on hello@bitbag.io.
*/
declare(strict_types=1);
namespace BitBag\CodingStandard\Twigcs\Rule;
use BitBag\CodingStandard\Twigcs\Ruleset\Ruleset;
use BitBag\CodingStandard\Twigcs\Util\HtmlUtil;
use FriendsOfTwig\Twigcs\Rule\AbstractRule;
use FriendsOfTwig\Twigcs\Rule\RuleInterface;
use FriendsOfTwig\Twigcs\TwigPort\TokenStream;
use FriendsOfTwig\Twigcs\Validator\Violation;
final class EmptyLinesRule extends AbstractRule implements RuleInterface
{
/** @var string */
private $pattern = '#(?<offset>\n{3,})#s';
/** @var HtmlUtil */
private $htmlUtil;
/** @var int */
private $lineNumberOffset = 2;
public function __construct(int $severity, HtmlUtil $htmlUtil)
{
parent::__construct($severity);
$this->htmlUtil = $htmlUtil;
}
/**
* @return Violation[]
*/
public function check(TokenStream $tokens): array
{
$violations = [];
$content = str_replace("\r", '', $tokens->getSourceContext()->getCode());
$this->htmlUtil->stripUnnecessaryTagsAndSavePositions($content);
foreach ($this->getMultiLines($content) as $multiline) {
if ($this->htmlUtil->isInsideUnnecessaryTag($multiline['offset'][1])) {
continue;
}
$offset = $this->htmlUtil->getTwigcsOffset($content, $multiline['offset'][1] + $this->lineNumberOffset);
$violations[] = $this->createViolation(
$tokens->getSourceContext()->getPath(),
$offset->getLine(),
0,
Ruleset::ERROR_MULTIPLE_EMPTY_LINES
);
}
return $violations;
}
private function getMultiLines(string $content): array
{
return preg_match_all($this->pattern, $content, $multilines, HtmlUtil::REGEX_FLAGS)
? $multilines
: [];
}
}