|
| 1 | +<?php declare(strict_types=1); |
| 2 | + |
| 3 | +namespace Nette\PHPStan\Database; |
| 4 | + |
| 5 | +use PHPStan\Reflection\ReflectionProvider; |
| 6 | +use PHPStan\Type\ObjectType; |
| 7 | + |
| 8 | + |
| 9 | +/** |
| 10 | + * Resolves database table names to entity row class types. |
| 11 | + * Convention: table_name -> str_replace('*', PascalCase(table), mask). |
| 12 | + * Explicit overrides in $tables take precedence over convention. |
| 13 | + */ |
| 14 | +class TableRowTypeResolver |
| 15 | +{ |
| 16 | + /** |
| 17 | + * @param string $convention mask like App\Entity\*Row, where * is replaced by PascalCase table name |
| 18 | + * @param array<string, string> $tables explicit table -> FQCN overrides |
| 19 | + */ |
| 20 | + public function __construct( |
| 21 | + private ReflectionProvider $reflectionProvider, |
| 22 | + private string $convention = '', |
| 23 | + private array $tables = [], |
| 24 | + ) { |
| 25 | + } |
| 26 | + |
| 27 | + |
| 28 | + /** |
| 29 | + * Resolves a table name to an ObjectType for the entity row class. |
| 30 | + * Returns null if no mapping applies (class does not exist). |
| 31 | + */ |
| 32 | + public function resolve(string $tableName): ?ObjectType |
| 33 | + { |
| 34 | + if (isset($this->tables[$tableName])) { |
| 35 | + $className = $this->tables[$tableName]; |
| 36 | + return $this->reflectionProvider->hasClass($className) |
| 37 | + ? new ObjectType($className) |
| 38 | + : null; |
| 39 | + } |
| 40 | + |
| 41 | + if ($this->convention === '') { |
| 42 | + return null; |
| 43 | + } |
| 44 | + |
| 45 | + $className = str_replace('*', $this->snakeToPascalCase($tableName), $this->convention); |
| 46 | + return $this->reflectionProvider->hasClass($className) |
| 47 | + ? new ObjectType($className) |
| 48 | + : null; |
| 49 | + } |
| 50 | + |
| 51 | + |
| 52 | + /** |
| 53 | + * Extracts the table name from a key parameter. |
| 54 | + * For related()/ref(), key can be 'table' or 'table.column'. |
| 55 | + */ |
| 56 | + public function extractTableName(string $key): string |
| 57 | + { |
| 58 | + $pos = strpos($key, '.'); |
| 59 | + return $pos !== false ? substr($key, 0, $pos) : $key; |
| 60 | + } |
| 61 | + |
| 62 | + |
| 63 | + private function snakeToPascalCase(string $table): string |
| 64 | + { |
| 65 | + return str_replace(' ', '', ucwords(strtr($table, '_', ' '))); |
| 66 | + } |
| 67 | +} |
0 commit comments