Skip to content

Instantly share code, notes, and snippets.

@staabm
Created August 5, 2026 07:19
Show Gist options
  • Select an option

  • Save staabm/2c874fa44bc4d86d9ad2d25a64ca6019 to your computer and use it in GitHub Desktop.

Select an option

Save staabm/2c874fa44bc4d86d9ad2d25a64ca6019 to your computer and use it in GitHub Desktop.
Cache PHPParser in ExprCacheHelper
<?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