1: <?php declare(strict_types = 1);
2:
3: namespace PHPStan\Analyser;
4:
5: use Exception;
6: use JsonSerializable;
7: use Nette\Utils\Strings;
8: use Override;
9: use PhpParser\Node;
10: use PHPStan\ShouldNotHappenException;
11: use ReturnTypeWillChange;
12: use Throwable;
13: use function array_key_exists;
14: use function array_map;
15: use function count;
16: use function is_bool;
17: use function sprintf;
18:
19: /**
20: * @api
21: */
22: final class Error implements JsonSerializable
23: {
24:
25: public const PATTERN_IDENTIFIER = '[a-zA-Z0-9](?:[a-zA-Z0-9\\.]*[a-zA-Z0-9])?';
26:
27: /**
28: * Error constructor.
29: *
30: * @param class-string<Node>|null $nodeType
31: * @param mixed[] $metadata
32: * @param list<FixedErrorDiff> $fixedErrorDiffs one diff per fixed file
33: * @param array<string, string> $traitContexts
34: */
35: public function __construct(
36: private string $message,
37: private string $file,
38: private ?int $line = null,
39: private bool|Throwable $canBeIgnored = true,
40: private ?string $filePath = null,
41: private ?string $traitFilePath = null,
42: private ?string $tip = null,
43: private ?int $nodeLine = null,
44: private ?string $nodeType = null,
45: private ?string $identifier = null,
46: private array $metadata = [],
47: private array $fixedErrorDiffs = [],
48: private array $traitContexts = [],
49: )
50: {
51: if ($this->identifier !== null && !self::validateIdentifier($this->identifier)) {
52: throw new ShouldNotHappenException(sprintf('Invalid identifier: %s', $this->identifier));
53: }
54: }
55:
56: public function getMessage(): string
57: {
58: return $this->message;
59: }
60:
61: public function getFile(): string
62: {
63: return $this->file;
64: }
65:
66: public function getFilePath(): string
67: {
68: if ($this->filePath === null) {
69: return $this->file;
70: }
71:
72: return $this->filePath;
73: }
74:
75: public function changeFilePath(string $newFilePath): self
76: {
77: if ($this->traitFilePath !== null) {
78: throw new ShouldNotHappenException('Errors in traits not yet supported');
79: }
80:
81: return new self(
82: $this->message,
83: $newFilePath,
84: $this->line,
85: $this->canBeIgnored,
86: $newFilePath,
87: null,
88: $this->tip,
89: $this->nodeLine,
90: $this->nodeType,
91: $this->identifier,
92: $this->metadata,
93: $this->renameFixedFile($this->getFilePath(), $newFilePath),
94: );
95: }
96:
97: public function changeTraitFilePath(string $newFilePath): self
98: {
99: return new self(
100: $this->message,
101: $this->file,
102: $this->line,
103: $this->canBeIgnored,
104: $this->filePath,
105: $newFilePath,
106: $this->tip,
107: $this->nodeLine,
108: $this->nodeType,
109: $this->identifier,
110: $this->metadata,
111: $this->traitFilePath === null ? $this->fixedErrorDiffs : $this->renameFixedFile($this->traitFilePath, $newFilePath),
112: $this->traitContexts,
113: );
114: }
115:
116: public function removeTraitContext(): self
117: {
118: if ($this->traitFilePath === null) {
119: throw new ShouldNotHappenException();
120: }
121:
122: return new self(
123: $this->message,
124: $this->traitFilePath,
125: $this->line,
126: $this->canBeIgnored,
127: $this->traitFilePath,
128: $this->traitFilePath,
129: $this->tip,
130: $this->nodeLine,
131: $this->nodeType,
132: $this->identifier,
133: $this->metadata,
134: $this->fixedErrorDiffs,
135: $this->traitContexts,
136: );
137: }
138:
139: public function getTraitFilePath(): ?string
140: {
141: return $this->traitFilePath;
142: }
143:
144: /**
145: * Using-class contexts of an error deduplicated directly into the trait
146: * (see ConstantConditionInTraitRule): the file path of each class in whose
147: * context the error was reported => the "trait.php (in context of class X)"
148: * file string it was reported with there. An ignoreErrors path pointing at
149: * one of these files accounts for that class's context only.
150: *
151: * @return array<string, string>
152: */
153: public function getTraitContexts(): array
154: {
155: return $this->traitContexts;
156: }
157:
158: /**
159: * @param array<string, string> $traitContexts
160: */
161: public function withTraitContexts(array $traitContexts): self
162: {
163: return new self(
164: $this->message,
165: $this->file,
166: $this->line,
167: $this->canBeIgnored,
168: $this->filePath,
169: $this->traitFilePath,
170: $this->tip,
171: $this->nodeLine,
172: $this->nodeType,
173: $this->identifier,
174: $this->metadata,
175: $this->fixedErrorDiffs,
176: $traitContexts,
177: );
178: }
179:
180: /**
181: * Rebuilds the per-context error this deduplicated trait error was merged
182: * from, for the given using-class file path.
183: */
184: public function asReportedInTraitContext(string $contextFilePath): self
185: {
186: if (!array_key_exists($contextFilePath, $this->traitContexts)) {
187: throw new ShouldNotHappenException(sprintf('Unknown trait context %s', $contextFilePath));
188: }
189:
190: return new self(
191: $this->message,
192: $this->traitContexts[$contextFilePath],
193: $this->line,
194: $this->canBeIgnored,
195: $contextFilePath,
196: $this->traitFilePath,
197: $this->tip,
198: $this->nodeLine,
199: $this->nodeType,
200: $this->identifier,
201: $this->metadata,
202: $this->fixedErrorDiffs,
203: );
204: }
205:
206: /**
207: * Rewrites every path this error carries, for portable storage in the result cache. The caller
208: * owns the transformation - see ResultCachePathTransformer, which passes relativizePath() when
209: * storing and absolutizePath() when loading - so both directions apply exactly the same rules
210: * to the error's paths as to the cache's file-path keys.
211: *
212: * @param callable(string): string $transformPath
213: */
214: public function transformPaths(callable $transformPath): self
215: {
216: return new self(
217: $this->message,
218: $transformPath($this->file),
219: $this->line,
220: $this->canBeIgnored,
221: $this->filePath === null ? null : $transformPath($this->filePath),
222: $this->traitFilePath === null ? null : $transformPath($this->traitFilePath),
223: $this->tip,
224: $this->nodeLine,
225: $this->nodeType,
226: $this->identifier,
227: $this->metadata,
228: array_map(static fn (FixedErrorDiff $diff): FixedErrorDiff => new FixedErrorDiff($transformPath($diff->file), $diff->originalHash, $diff->diff), $this->fixedErrorDiffs),
229: $this->transformTraitContexts($transformPath),
230: );
231: }
232:
233: public function getLine(): ?int
234: {
235: return $this->line;
236: }
237:
238: public function canBeIgnored(): bool
239: {
240: return $this->canBeIgnored === true;
241: }
242:
243: public function hasNonIgnorableException(): bool
244: {
245: return $this->canBeIgnored instanceof Throwable;
246: }
247:
248: public function getTip(): ?string
249: {
250: return $this->tip;
251: }
252:
253: public function withoutTip(): self
254: {
255: if ($this->tip === null) {
256: return $this;
257: }
258:
259: return new self(
260: $this->message,
261: $this->file,
262: $this->line,
263: $this->canBeIgnored,
264: $this->filePath,
265: $this->traitFilePath,
266: null,
267: $this->nodeLine,
268: $this->nodeType,
269: $this->identifier,
270: $this->metadata,
271: $this->fixedErrorDiffs,
272: $this->traitContexts,
273: );
274: }
275:
276: public function doNotIgnore(): self
277: {
278: if (!$this->canBeIgnored()) {
279: return $this;
280: }
281:
282: return new self(
283: $this->message,
284: $this->file,
285: $this->line,
286: false,
287: $this->filePath,
288: $this->traitFilePath,
289: $this->tip,
290: $this->nodeLine,
291: $this->nodeType,
292: $this->identifier,
293: $this->metadata,
294: $this->fixedErrorDiffs,
295: $this->traitContexts,
296: );
297: }
298:
299: public function withIdentifier(string $identifier): self
300: {
301: if ($this->identifier !== null) {
302: throw new ShouldNotHappenException(sprintf('Error already has an identifier: %s', $this->identifier));
303: }
304:
305: return new self(
306: $this->message,
307: $this->file,
308: $this->line,
309: $this->canBeIgnored,
310: $this->filePath,
311: $this->traitFilePath,
312: $this->tip,
313: $this->nodeLine,
314: $this->nodeType,
315: $identifier,
316: $this->metadata,
317: $this->fixedErrorDiffs,
318: $this->traitContexts,
319: );
320: }
321:
322: /**
323: * @param mixed[] $metadata
324: */
325: public function withMetadata(array $metadata): self
326: {
327: if ($this->metadata !== []) {
328: throw new ShouldNotHappenException('Error already has metadata');
329: }
330:
331: return new self(
332: $this->message,
333: $this->file,
334: $this->line,
335: $this->canBeIgnored,
336: $this->filePath,
337: $this->traitFilePath,
338: $this->tip,
339: $this->nodeLine,
340: $this->nodeType,
341: $this->identifier,
342: $metadata,
343: $this->fixedErrorDiffs,
344: $this->traitContexts,
345: );
346: }
347:
348: public function getNodeLine(): ?int
349: {
350: return $this->nodeLine;
351: }
352:
353: /**
354: * @return class-string<Node>|null
355: */
356: public function getNodeType(): ?string
357: {
358: return $this->nodeType;
359: }
360:
361: /**
362: * Error identifier set via `RuleErrorBuilder::identifier()`.
363: *
364: * List of all current error identifiers in PHPStan: https://phpstan.org/error-identifiers
365: */
366: public function getIdentifier(): ?string
367: {
368: return $this->identifier;
369: }
370:
371: /**
372: * @return mixed[]
373: */
374: public function getMetadata(): array
375: {
376: return $this->metadata;
377: }
378:
379: /**
380: * Whether the rule attached a fix with RuleErrorBuilder::fixNode() or removeNode(),
381: * to be applied with ErrorFixer or `phpstan analyse --fix`.
382: */
383: public function isFixable(): bool
384: {
385: return $this->fixedErrorDiffs !== [];
386: }
387:
388: /**
389: * @internal Experimental
390: * @deprecated Use getFixedErrorDiffs(), a fix can change several files.
391: */
392: public function getFixedErrorDiff(): ?FixedErrorDiff
393: {
394: // one diff of a fix of several files would apply only a part of the fix
395: return count($this->fixedErrorDiffs) === 1 ? $this->fixedErrorDiffs[0] : null;
396: }
397:
398: /**
399: * The diffs are applied together or not at all.
400: *
401: * @internal Experimental
402: * @return list<FixedErrorDiff>
403: */
404: public function getFixedErrorDiffs(): array
405: {
406: return $this->fixedErrorDiffs;
407: }
408:
409: /**
410: * @return list<FixedErrorDiff>
411: */
412: private function renameFixedFile(string $oldFile, string $newFile): array
413: {
414: return array_map(
415: static fn (FixedErrorDiff $diff): FixedErrorDiff => $diff->file === $oldFile ? new FixedErrorDiff($newFile, $diff->originalHash, $diff->diff) : $diff,
416: $this->fixedErrorDiffs,
417: );
418: }
419:
420: /**
421: * @return mixed
422: */
423: #[ReturnTypeWillChange]
424: #[Override]
425: public function jsonSerialize()
426: {
427: return [
428: 'message' => $this->message,
429: 'file' => $this->file,
430: 'line' => $this->line,
431: 'canBeIgnored' => is_bool($this->canBeIgnored) ? $this->canBeIgnored : 'exception',
432: 'filePath' => $this->filePath,
433: 'traitFilePath' => $this->traitFilePath,
434: 'tip' => $this->tip,
435: 'nodeLine' => $this->nodeLine,
436: 'nodeType' => $this->nodeType,
437: 'identifier' => $this->identifier,
438: 'metadata' => $this->metadata,
439: 'fixedErrorDiffs' => array_map(static fn (FixedErrorDiff $diff): array => [$diff->file, $diff->originalHash, $diff->diff], $this->fixedErrorDiffs),
440: 'traitContexts' => $this->traitContexts,
441: ];
442: }
443:
444: /**
445: * @param mixed[] $json
446: */
447: public static function decode(array $json): self
448: {
449: $fixedErrorDiffs = [];
450: foreach ($json['fixedErrorDiffs'] ?? [] as [$file, $hash, $diff]) {
451: $fixedErrorDiffs[] = new FixedErrorDiff($file, $hash, $diff);
452: }
453:
454: return new self(
455: $json['message'],
456: $json['file'],
457: $json['line'],
458: $json['canBeIgnored'] === 'exception' ? new Exception() : $json['canBeIgnored'],
459: $json['filePath'],
460: $json['traitFilePath'],
461: $json['tip'],
462: $json['nodeLine'] ?? null,
463: $json['nodeType'] ?? null,
464: $json['identifier'] ?? null,
465: $json['metadata'] ?? [],
466: $fixedErrorDiffs,
467: $json['traitContexts'] ?? [],
468: );
469: }
470:
471: /**
472: * @param mixed[] $properties
473: */
474: public static function __set_state(array $properties): self
475: {
476: return new self(
477: $properties['message'],
478: $properties['file'],
479: $properties['line'],
480: $properties['canBeIgnored'],
481: $properties['filePath'],
482: $properties['traitFilePath'],
483: $properties['tip'],
484: $properties['nodeLine'] ?? null,
485: $properties['nodeType'] ?? null,
486: $properties['identifier'] ?? null,
487: $properties['metadata'] ?? [],
488: $properties['fixedErrorDiffs'] ?? [],
489: $properties['traitContexts'] ?? [],
490: );
491: }
492:
493: /**
494: * @param callable(string): string $transformPath
495: * @return array<string, string>
496: */
497: private function transformTraitContexts(callable $transformPath): array
498: {
499: $result = [];
500: foreach ($this->traitContexts as $contextFilePath => $contextFile) {
501: $result[$transformPath($contextFilePath)] = $transformPath($contextFile);
502: }
503:
504: return $result;
505: }
506:
507: public static function validateIdentifier(string $identifier): bool
508: {
509: return Strings::match($identifier, '~^' . self::PATTERN_IDENTIFIER . '$~') !== null;
510: }
511:
512: }
513: