1: <?php declare(strict_types = 1);
2:
3: namespace PHPStan\Rules;
4:
5: use PhpParser\Node;
6: use PhpParser\NodeVisitor;
7: use PHPStan\Analyser\Error;
8: use PHPStan\ShouldNotHappenException;
9: use PHPStan\Turbo\ReferencedByTurboExtension;
10: use function array_map;
11: use function class_exists;
12: use function count;
13: use function implode;
14: use function is_file;
15: use function sprintf;
16:
17: /**
18: * @api
19: * @template-covariant T of RuleError
20: */
21: #[ReferencedByTurboExtension(key: 'ruleErrorBuilder')]
22: final class RuleErrorBuilder
23: {
24:
25: private const TYPE_MESSAGE = 1;
26: private const TYPE_LINE = 2;
27: private const TYPE_FILE = 4;
28: private const TYPE_TIP = 8;
29: private const TYPE_IDENTIFIER = 16;
30: private const TYPE_METADATA = 32;
31: private const TYPE_NON_IGNORABLE = 64;
32: private const TYPE_FIXABLE_NODE = 128;
33: private const TYPE_FILE_DEPENDENCIES = 256;
34:
35: private int $type;
36:
37: /** @var mixed[] */
38: private array $properties;
39:
40: /** @var list<string> */
41: private array $tips = [];
42:
43: private function __construct(string $message)
44: {
45: $this->properties['message'] = $message;
46: $this->type = self::TYPE_MESSAGE;
47: }
48:
49: /**
50: * @return array<int, array{string, array<array{string, string|null, string}>}>
51: */
52: public static function getRuleErrorTypes(): array
53: {
54: return [
55: self::TYPE_MESSAGE => [
56: RuleError::class,
57: [
58: [
59: 'message', // property name
60: 'string', // native type
61: 'string', // PHPDoc type
62: ],
63: ],
64: ],
65: self::TYPE_LINE => [
66: LineRuleError::class,
67: [
68: [
69: 'line',
70: 'int',
71: 'int',
72: ],
73: ],
74: ],
75: self::TYPE_FILE => [
76: FileRuleError::class,
77: [
78: [
79: 'file',
80: 'string',
81: 'string',
82: ],
83: [
84: 'fileDescription',
85: 'string',
86: 'string',
87: ],
88: ],
89: ],
90: self::TYPE_TIP => [
91: TipRuleError::class,
92: [
93: [
94: 'tip',
95: 'string',
96: 'string',
97: ],
98: ],
99: ],
100: self::TYPE_IDENTIFIER => [
101: IdentifierRuleError::class,
102: [
103: [
104: 'identifier',
105: 'string',
106: 'string',
107: ],
108: ],
109: ],
110: self::TYPE_METADATA => [
111: MetadataRuleError::class,
112: [
113: [
114: 'metadata',
115: 'array',
116: 'mixed[]',
117: ],
118: ],
119: ],
120: self::TYPE_NON_IGNORABLE => [
121: NonIgnorableRuleError::class,
122: [],
123: ],
124: self::TYPE_FIXABLE_NODE => [
125: FixableNodeRuleError::class,
126: [
127: [
128: 'nodeFixes',
129: 'array',
130: 'non-empty-list<\PHPStan\Rules\NodeFix>',
131: ],
132: ],
133: ],
134: self::TYPE_FILE_DEPENDENCIES => [
135: FileDependenciesRuleError::class,
136: [
137: [
138: 'fileDependencies',
139: 'array',
140: 'list<string>',
141: ],
142: ],
143: ],
144: ];
145: }
146:
147: /**
148: * @return self<RuleError>
149: */
150: public static function message(string $message): self
151: {
152: return new self($message);
153: }
154:
155: /**
156: * @phpstan-this-out self<T&LineRuleError>
157: * @return self<T&LineRuleError>
158: */
159: public function line(int $line): self
160: {
161: $this->properties['line'] = $line;
162: $this->type |= self::TYPE_LINE;
163:
164: return $this;
165: }
166:
167: /**
168: * @phpstan-this-out self<T&FileRuleError>
169: * @return self<T&FileRuleError>
170: */
171: public function file(string $file, ?string $fileDescription = null): self
172: {
173: if (!is_file($file)) {
174: throw new ShouldNotHappenException(sprintf('File %s does not exist.', $file));
175: }
176: $this->properties['file'] = $file;
177: $this->properties['fileDescription'] = $fileDescription ?? $file;
178: $this->type |= self::TYPE_FILE;
179:
180: return $this;
181: }
182:
183: /**
184: * Declares that this error depends on the contents of another file, so that the result cache
185: * re-analyses the file the error is reported in when that file appears, changes or is deleted.
186: * The path must be absolute; it does not have to exist.
187: *
188: * @deprecated Call trackFileDependency() on the Scope instead (Scope&DependencyTracker) - it declares
189: * the dependency whether the rule reports an error or not.
190: * @api
191: * @phpstan-this-out self<T&FileDependenciesRuleError>
192: * @return self<T&FileDependenciesRuleError>
193: */
194: public function fileDependency(string $file): self
195: {
196: /** @var list<string> $fileDependencies */
197: $fileDependencies = $this->properties['fileDependencies'] ?? [];
198: $fileDependencies[] = $file;
199: $this->properties['fileDependencies'] = $fileDependencies;
200: $this->type |= self::TYPE_FILE_DEPENDENCIES;
201:
202: return $this;
203: }
204:
205: /**
206: * @phpstan-this-out self<T&TipRuleError>
207: * @return self<T&TipRuleError>
208: */
209: public function tip(string $tip): self
210: {
211: $this->tips = [$tip];
212: $this->type |= self::TYPE_TIP;
213:
214: return $this;
215: }
216:
217: /**
218: * @phpstan-this-out self<T&TipRuleError>
219: * @return self<T&TipRuleError>
220: */
221: public function addTip(string $tip): self
222: {
223: $this->tips[] = $tip;
224: $this->type |= self::TYPE_TIP;
225:
226: return $this;
227: }
228:
229: /**
230: * @phpstan-this-out self<T&TipRuleError>
231: * @return self<T&TipRuleError>
232: */
233: public function discoveringSymbolsTip(): self
234: {
235: return $this->tip('Learn more at https://phpstan.org/user-guide/discovering-symbols');
236: }
237:
238: /**
239: * @param list<string> $reasons
240: * @phpstan-this-out self<T&TipRuleError>
241: * @return self<T&TipRuleError>
242: */
243: public function acceptsReasonsTip(array $reasons): self
244: {
245: foreach ($reasons as $reason) {
246: $this->addTip($reason);
247: }
248:
249: return $this;
250: }
251:
252: /**
253: * @phpstan-this-out self<T&TipRuleError>
254: * @return self<T&TipRuleError>
255: */
256: public function treatPhpDocTypesAsCertainTip(): self
257: {
258: return $this->tip('Because the type is coming from a PHPDoc, you can turn off this check by setting <fg=cyan>treatPhpDocTypesAsCertain: false</> in your <fg=cyan>%configurationFile%</>.');
259: }
260:
261: /**
262: * @param list<string> $callDescriptions
263: * @phpstan-this-out self<T&TipRuleError>
264: * @return self<T&TipRuleError>
265: */
266: public function possiblyImpureTip(array $callDescriptions): self
267: {
268: foreach ($callDescriptions as $callDescription) {
269: $this->addTip(sprintf('If %s is impure, add <fg=cyan>@phpstan-impure</> PHPDoc tag above its declaration. Learn more: <fg=cyan>https://phpstan.org/blog/remembering-and-forgetting-returned-values</>', $callDescription));
270: }
271:
272: return $this;
273: }
274:
275: /**
276: * Sets an error identifier.
277: *
278: * List of all current error identifiers in PHPStan: https://phpstan.org/error-identifiers
279: *
280: * @phpstan-this-out self<T&IdentifierRuleError>
281: * @return self<T&IdentifierRuleError>
282: */
283: public function identifier(string $identifier): self
284: {
285: if (!Error::validateIdentifier($identifier)) {
286: throw new ShouldNotHappenException(sprintf('Invalid identifier: %s, error identifiers must match /%s/', $identifier, Error::PATTERN_IDENTIFIER));
287: }
288:
289: $this->properties['identifier'] = $identifier;
290: $this->type |= self::TYPE_IDENTIFIER;
291:
292: return $this;
293: }
294:
295: /**
296: * @param mixed[] $metadata
297: * @phpstan-this-out self<T&MetadataRuleError>
298: * @return self<T&MetadataRuleError>
299: */
300: public function metadata(array $metadata): self
301: {
302: $this->properties['metadata'] = $metadata;
303: $this->type |= self::TYPE_METADATA;
304:
305: return $this;
306: }
307:
308: /**
309: * @phpstan-this-out self<T&NonIgnorableRuleError>
310: * @return self<T&NonIgnorableRuleError>
311: */
312: public function nonIgnorable(): self
313: {
314: $this->type |= self::TYPE_NON_IGNORABLE;
315:
316: return $this;
317: }
318:
319: /**
320: * Every call adds a change to the fix of the error. The changes are applied together or not at all.
321: * Several changes of the same node are applied in the order they were added.
322: *
323: * @template TNode of Node
324: * @param TNode $node
325: * @param callable(TNode): (Node|NodeVisitor::REMOVE_NODE) $cb returning NodeVisitor::REMOVE_NODE works like removeNode()
326: * @param string|null $file the file of the node when it is not the file of the error
327: * @phpstan-this-out self<T&FixableNodeRuleError>
328: * @return self<T&FixableNodeRuleError>
329: */
330: public function fixNode(Node $node, callable $cb, ?string $file = null): self
331: {
332: // ReplacingNodeVisitor passes the callback only a clone of $node
333: /** @var callable(Node): (Node|NodeVisitor::REMOVE_NODE) $cb */
334: $this->properties['nodeFixes'][] = new NodeFix($node, $cb, $file);
335: $this->type |= self::TYPE_FIXABLE_NODE;
336:
337: return $this;
338: }
339:
340: /**
341: * Adds removing the node to the fix of the error, see fixNode(). Only a node in an array,
342: * like a statement, an argument, or an array item, can be removed. Otherwise the error is not fixable.
343: *
344: * @param string|null $file the file of the node when it is not the file of the error
345: * @phpstan-this-out self<T&FixableNodeRuleError>
346: * @return self<T&FixableNodeRuleError>
347: */
348: public function removeNode(Node $node, ?string $file = null): self
349: {
350: return $this->fixNode($node, static fn (): int => NodeVisitor::REMOVE_NODE, $file);
351: }
352:
353: /**
354: * @return T
355: */
356: public function build(): RuleError
357: {
358: /** @var class-string<T> $className */
359: $className = sprintf('PHPStan\\Rules\\RuleErrors\\RuleError%d', $this->type);
360: if (!class_exists($className)) {
361: throw new ShouldNotHappenException(sprintf('Class %s does not exist.', $className));
362: }
363:
364: $ruleError = new $className();
365: foreach ($this->properties as $propertyName => $value) {
366: $ruleError->{$propertyName} = $value;
367: }
368:
369: if (count($this->tips) > 0) {
370: if (count($this->tips) === 1) {
371: $ruleError->tip = $this->tips[0];
372: } else {
373: $ruleError->tip = implode("\n", array_map(static fn (string $tip) => sprintf('• %s', $tip), $this->tips));
374: }
375: }
376:
377: return $ruleError;
378: }
379:
380: }
381: