Created
August 5, 2026 07:19
-
-
Save staabm/2c874fa44bc4d86d9ad2d25a64ca6019 to your computer and use it in GitHub Desktop.
Cache PHPParser in ExprCacheHelper
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php | |
| declare(strict_types=1); | |
| namespace PHPStan\BetterReflection\Reflection; | |
| use PhpParser\Node\Expr; | |
| use PHPStan\BetterReflection\BetterReflection; | |
| final class ExprCacheHelper | |
| { | |
| private static ?BetterReflection $br = null; | |
| /** | |
| * @return array<string, mixed | |
| */ | |
| public static function export(Expr $expr): array | |
| { | |
| $br = self::$br ??= new BetterReflection(); | |
| $attributes = []; | |
| foreach (['startLine', 'endLine', 'startTokenPos', 'startFilePos', 'endTokenPos', 'endFilePos'] as $key) { | |
| $attributes[$key] = $expr->getAttribute($key); | |
| } | |
| return [ | |
| 'code' => $br->printer()->prettyPrintExpr($expr), | |
| 'attributes' => $attributes, | |
| ]; | |
| } | |
| public static function import(array $data): Expr | |
| { | |
| $code = $data['code']; | |
| $attributes = $data['attributes']; | |
| $br = self::$br ??= new BetterReflection(); | |
| $expr = $br->originalPhpParser()->parse('<?php ' . $code . ';')[0]->expr; | |
| foreach ($attributes as $key => $value) { | |
| $expr->setAttribute($key, $value); | |
| } | |
| return $expr; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment