1: <?php declare(strict_types = 1);
2:
3: namespace PHPStan\Node\Printer;
4:
5: use PhpParser\Node\Expr;
6: use PHPStan\DependencyInjection\AutowiredService;
7: use PHPStan\Turbo\ShadowedByTurboExtension;
8:
9: /**
10: * @api
11: */
12: #[AutowiredService]
13: #[ShadowedByTurboExtension(implementation: __DIR__ . '/../../../turbo-ext/src/ExprPrinter.cpp')]
14: final class ExprPrinter
15: {
16:
17: public const ATTRIBUTE_CACHE_KEY = 'phpstan_cache_printer';
18:
19: public function __construct(private Printer $printer)
20: {
21: }
22:
23: public function printExpr(Expr $expr): string
24: {
25: // perf optimize for the most common path
26: if ($expr instanceof Expr\Variable && !$expr->name instanceof Expr) {
27: return '$' . $expr->name;
28: }
29:
30: /** @var string|null $exprString */
31: $exprString = $expr->getAttribute(self::ATTRIBUTE_CACHE_KEY);
32: if ($exprString === null) {
33: $exprString = $this->printer->prettyPrintExpr($expr);
34: $expr->setAttribute(self::ATTRIBUTE_CACHE_KEY, $exprString);
35: }
36:
37: return $exprString;
38: }
39:
40: }
41: