| 1: | <?php |
| 2: | |
| 3: | declare(strict_types=1); |
| 4: | |
| 5: | namespace PHPStan\BetterReflection\Reflection; |
| 6: | |
| 7: | use PhpParser\Node\Expr; |
| 8: | use PHPStan\BetterReflection\BetterReflection; |
| 9: | |
| 10: | final class ExprCacheHelper |
| 11: | { |
| 12: | |
| 13: | |
| 14: | |
| 15: | |
| 16: | |
| 17: | |
| 18: | |
| 19: | private static $betterReflection = null; |
| 20: | |
| 21: | private static function betterReflection(): BetterReflection |
| 22: | { |
| 23: | return self::$betterReflection ??= new BetterReflection(); |
| 24: | } |
| 25: | |
| 26: | |
| 27: | |
| 28: | |
| 29: | public static function export(Expr $expr): array |
| 30: | { |
| 31: | $br = self::betterReflection(); |
| 32: | |
| 33: | $attributes = []; |
| 34: | foreach (['startLine', 'endLine', 'startTokenPos', 'startFilePos', 'endTokenPos', 'endFilePos'] as $key) { |
| 35: | $attributes[$key] = $expr->getAttribute($key); |
| 36: | } |
| 37: | |
| 38: | return [ |
| 39: | 'code' => $br->printer()->prettyPrintExpr($expr), |
| 40: | 'attributes' => $attributes, |
| 41: | ]; |
| 42: | } |
| 43: | |
| 44: | public static function import(array $data): Expr |
| 45: | { |
| 46: | $code = $data['code']; |
| 47: | $attributes = $data['attributes']; |
| 48: | |
| 49: | $expr = self::betterReflection()->originalPhpParser()->parse('<?php ' . $code . ';')[0]->expr; |
| 50: | foreach ($attributes as $key => $value) { |
| 51: | $expr->setAttribute($key, $value); |
| 52: | } |
| 53: | |
| 54: | return $expr; |
| 55: | } |
| 56: | |
| 57: | } |
| 58: | |