-
Notifications
You must be signed in to change notification settings - Fork 158
/
Copy pathPhtmlTemplateSniff.php
92 lines (83 loc) · 2.72 KB
/
PhtmlTemplateSniff.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
82
83
84
85
86
87
88
89
90
91
92
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types = 1);
namespace Magento2\Sniffs\Legacy;
use PHP_CodeSniffer\Files\File;
use PHP_CodeSniffer\Sniffs\Sniff;
class PhtmlTemplateSniff implements Sniff
{
private const WARNING_CODE_TEXT_JAVASCRIPT = 'TextJavascriptTypeFound';
private const WARNING_CODE_PROTECTED_PRIVATE_BLOCK_ACCESS = 'ProtectedPrivateBlockAccess';
/**
* @inheritdoc
*/
public function register(): array
{
return [
T_OBJECT_OPERATOR,
T_INLINE_HTML,
T_HEREDOC
];
}
/**
* @inheritdoc
*/
public function process(File $phpcsFile, $stackPtr)
{
$tokens = $phpcsFile->getTokens();
if ($tokens[$stackPtr]['code'] === T_OBJECT_OPERATOR) {
$this->checkBlockVariable($phpcsFile, $stackPtr, $tokens);
}
if ($tokens[$stackPtr]['code'] === T_INLINE_HTML || $tokens[$stackPtr]['code'] === T_HEREDOC) {
$this->checkHtml($phpcsFile, $stackPtr);
}
}
/**
* Check access to protected and private members of Block
*
* @param File $phpcsFile
* @param int $stackPtr
* @param array $tokens
*/
private function checkBlockVariable(File $phpcsFile, int $stackPtr, array $tokens): void
{
$varPos = $phpcsFile->findPrevious(T_VARIABLE, $stackPtr - 1);
if ($tokens[$varPos]['content'] !== '$block') {
return;
}
$stringPos = $phpcsFile->findNext(T_STRING, $stackPtr + 1);
if (strpos($tokens[$stringPos]['content'], '_') === 0) {
$phpcsFile->addWarning(
'Access to protected and private members of Block class is ' .
'obsolete in phtml templates. Use only public members.',
$stringPos,
self::WARNING_CODE_PROTECTED_PRIVATE_BLOCK_ACCESS
);
}
}
/**
* Check use of "text/javascript" type
*
* @param File $phpcsFile
* @param int $stackPtr
*/
private function checkHtml(File $phpcsFile, int $stackPtr): void
{
$content = $phpcsFile->getTokensAsString($stackPtr, 1);
$pattern = '_(<script[^>]*?)\s+type=(["\'])text/javascript\2_i';
if (preg_match($pattern, $content, $matches)) {
$fix = $phpcsFile->addFixableWarning(
'Please do not use "text/javascript" type attribute.',
$stackPtr,
self::WARNING_CODE_TEXT_JAVASCRIPT
);
if ($fix) {
$content = preg_replace($pattern, $matches[1], $content);
$phpcsFile->fixer->replaceToken($stackPtr, $content);
}
}
}
}