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