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