-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathNonExistingBladeTemplateSniff.php
More file actions
212 lines (174 loc) · 7.57 KB
/
NonExistingBladeTemplateSniff.php
File metadata and controls
212 lines (174 loc) · 7.57 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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
<?php declare(strict_types=1);
namespace IxDFCodingStandard\Sniffs\Laravel;
use PHP_CodeSniffer\Files\File;
use PHP_CodeSniffer\Sniffs\Sniff;
final class NonExistingBladeTemplateSniff implements Sniff
{
public const CODE_TEMPLATE_NOT_FOUND = 'TemplateNotFound';
public const CODE_UNKNOWN_VIEW_NAMESPACE = 'UnknownViewNamespace';
/** @var list<non-empty-string> The same as for config('view.paths') */
public array $viewPaths = [
'resources/views',
];
/** @var array<non-empty-string, non-empty-string> Example: <element key="googletagmanager" value="resources/views/vendor/googletagmanager"/> */
public array $viewNamespaces = [];
/** @var non-empty-string|null Custom base directory, defaults to auto-detection */
public ?string $baseDir = null;
/** @var array<string, bool> */
private array $checkedFiles = [];
/** @var array<string, bool> Cache for template existence checks */
private array $templateExistsCache = [];
/** @var string|null Cached base directory */
private ?string $resolvedBaseDir = null;
private BladeTemplateExtractor $bladeExtractor;
private PhpViewExtractor $phpExtractor;
public function __construct()
{
$this->bladeExtractor = new BladeTemplateExtractor();
$this->phpExtractor = new PhpViewExtractor();
}
/** @inheritDoc */
public function register(): array
{
return [\T_OPEN_TAG, \T_INLINE_HTML, \T_STRING];
}
/** @inheritDoc */
public function process(File $phpcsFile, $stackPtr): int // phpcs:ignore SlevomatCodingStandard.Complexity.Cognitive.ComplexityTooHigh
{
$filename = $phpcsFile->getFilename();
$hash = md5($filename);
if (($this->checkedFiles[$hash] ?? false) || $filename === 'STDIN' || \str_contains($filename, '.stub')) {
return 0;
}
// Early exit: Skip processing for non-Blade and non-PHP files
if (!str_ends_with($filename, '.php')) {
return 0;
}
$this->checkedFiles[$hash] = true;
$tokens = $phpcsFile->getTokens();
foreach ($tokens as $position => $token) {
$tokenContent = $token['content'];
// Handle Blade directives (found in T_INLINE_HTML tokens)
if ($this->bladeExtractor->isBladeIncludeDirective($tokenContent)) {
$this->validateTemplateName($this->bladeExtractor->getBladeTemplateName($tokenContent), $phpcsFile, $position);
} elseif ($this->bladeExtractor->isConditionalBladeIncludeDirective($tokenContent)) {
$this->validateTemplateName($this->bladeExtractor->getConditionalBladeTemplateName($tokenContent), $phpcsFile, $position);
} elseif ($this->bladeExtractor->isEachBladeDirective($tokenContent)) {
$this->validateTemplateName($this->bladeExtractor->getEachBladeTemplateName($tokenContent), $phpcsFile, $position);
} elseif ($this->bladeExtractor->isFirstBladeDirective($tokenContent)) {
$this->validateTemplateName($this->bladeExtractor->getFirstBladeTemplateName($tokenContent), $phpcsFile, $position);
} elseif ($token['type'] === 'T_STRING') { // Handle PHP code (found in T_STRING tokens)
if ($this->phpExtractor->isViewFunction($tokens, $position)) {
$this->validateTemplateName($this->phpExtractor->getViewFunctionTemplateName($tokens, $position), $phpcsFile, $position);
}
}
}
return 0;
}
/**
* @param string $templateName In dot notation
* @throws \OutOfBoundsException
*/
private function templateIsMissing(string $templateName): bool
{
if (isset($this->templateExistsCache[$templateName])) {
return !$this->templateExistsCache[$templateName];
}
foreach ($this->getTemplatePathCandidates($templateName) as $candidateFilePath) {
if (\file_exists($candidateFilePath)) {
$this->templateExistsCache[$templateName] = true;
return false;
}
}
$this->templateExistsCache[$templateName] = false;
return true;
}
private function resolveLaravelBaseDir(): string
{
if ($this->resolvedBaseDir === null) {
$this->resolvedBaseDir = $this->baseDir ?? dirname(__DIR__, 6); // assume this file in the classic vendor dir for phpcs installed as a dependency
}
return $this->resolvedBaseDir;
}
/**
* @param string $templatePath In dot notation
* @return list<non-empty-string>
* @throws \OutOfBoundsException
*/
private function getTemplatePathCandidates(string $templatePath): array
{
/**
* Here, we have 2 cases:
* 1. No custom namespace, e.g. 'dashboard.index' -> resources/views/dashboard/index.blade.php
* 2. Custom namespace, e.g. 'googletagmanager::head' -> resources/views/vendor/googletagmanager ({@see \Illuminate\Support\ServiceProvider::loadViewsFrom})
*/
$hasCustomNamespace = preg_match('/^(\w++)::\w+/', $templatePath, $matches);
// 2. Custom namespace
if ($hasCustomNamespace) {
$namespace = (string) $matches[1];
if (!isset($this->viewNamespaces[$namespace])) {
throw new \OutOfBoundsException("Unable to find view namespace “{$namespace}” in viewNamespaces property.");
}
$namespacePath = $this->viewNamespaces[$namespace];
$templateNameWithoutNamespace = str_replace("{$namespace}::", '', $templatePath);
return [
sprintf(
'%s/%s/%s.blade.php',
$this->resolveLaravelBaseDir(),
$namespacePath,
str_replace('.', '/', $templateNameWithoutNamespace)
),
];
}
// 1. No custom namespace
$candidates = [];
foreach ($this->viewPaths as $viewPath) {
$candidates[] = sprintf(
'%s/%s/%s.blade.php',
$this->resolveLaravelBaseDir(),
$viewPath,
str_replace('.', '/', $templatePath)
);
}
return $candidates;
}
private function reportTemplateNotFound(File $phpcsFile, int $stackPtr, string $templateName): void
{
$phpcsFile->addError(
'Blade template "%s" not found. Expected location(s): "%s"',
$stackPtr,
self::CODE_TEMPLATE_NOT_FOUND,
[
$templateName,
implode(', ', $this->getTemplatePathCandidates($templateName)),
]
);
}
private function reportUnknownViewNamespace(File $phpcsFile, int $stackPtr, string $templateName): void
{
$phpcsFile->addWarning(
'Blade template namespace for the "%s" is not registered via "viewNamespaces" property.',
$stackPtr,
self::CODE_UNKNOWN_VIEW_NAMESPACE,
[
$templateName,
]
);
}
private function validateTemplateName(string $templateName, File $phpcsFile, int $stackPtr): void
{
if (mb_rtrim($templateName, '-_.') !== $templateName) {
return;
}
if (str_contains($templateName, '$')) {
return;
}
try {
if ($this->templateIsMissing($templateName)) {
$this->reportTemplateNotFound($phpcsFile, $stackPtr, $templateName);
}
} catch (\OutOfBoundsException) {
$this->reportUnknownViewNamespace($phpcsFile, $stackPtr, $templateName);
}
}
}