|
| 1 | +<?php |
| 2 | + |
| 3 | +declare(strict_types=1); |
| 4 | + |
| 5 | +/** |
| 6 | + * This file is part of CodeIgniter 4 framework. |
| 7 | + * |
| 8 | + * (c) 2023 CodeIgniter Foundation <admin@codeigniter.com> |
| 9 | + * |
| 10 | + * For the full copyright and license information, please view |
| 11 | + * the LICENSE file that was distributed with this source code. |
| 12 | + */ |
| 13 | + |
| 14 | +namespace CodeIgniter\PHPStan\Database; |
| 15 | + |
| 16 | +use CodeIgniter\Database\SQLite3\Connection; |
| 17 | +use CodeIgniter\PHPStan\Database\Schema\Column; |
| 18 | +use CodeIgniter\PHPStan\Database\Schema\Schema; |
| 19 | +use CodeIgniter\PHPStan\Database\Schema\Table; |
| 20 | + |
| 21 | +/** |
| 22 | + * Reads the tables and columns of a live database connection into a `Schema`. |
| 23 | + */ |
| 24 | +final class SchemaIntrospector |
| 25 | +{ |
| 26 | + /** |
| 27 | + * Tables created by the framework that are not part of the user's domain schema. |
| 28 | + */ |
| 29 | + private const IGNORED_TABLES = [ |
| 30 | + 'migrations', |
| 31 | + ]; |
| 32 | + |
| 33 | + public function introspect(Connection $db, string $hash): Schema |
| 34 | + { |
| 35 | + $tableNames = $db->listTables(); |
| 36 | + |
| 37 | + if ($tableNames === false) { |
| 38 | + return new Schema(hash: $hash, tables: []); |
| 39 | + } |
| 40 | + |
| 41 | + $tables = []; |
| 42 | + |
| 43 | + foreach ($tableNames as $tableName) { |
| 44 | + if (in_array($tableName, self::IGNORED_TABLES, true)) { |
| 45 | + continue; |
| 46 | + } |
| 47 | + |
| 48 | + $columns = []; |
| 49 | + |
| 50 | + foreach ($db->getFieldData($tableName) as $field) { |
| 51 | + $name = $field->name; |
| 52 | + |
| 53 | + if (! is_string($name)) { |
| 54 | + continue; |
| 55 | + } |
| 56 | + |
| 57 | + $type = $field->type; |
| 58 | + $default = $field->default; |
| 59 | + |
| 60 | + $columns[$name] = new Column( |
| 61 | + name: $name, |
| 62 | + type: is_string($type) ? $type : '', |
| 63 | + nullable: (bool) $field->nullable, |
| 64 | + primaryKey: (bool) $field->primary_key, |
| 65 | + default: is_string($default) ? $default : null, |
| 66 | + ); |
| 67 | + } |
| 68 | + |
| 69 | + $tables[$tableName] = new Table(name: $tableName, columns: $columns); |
| 70 | + } |
| 71 | + |
| 72 | + return new Schema(hash: $hash, tables: $tables); |
| 73 | + } |
| 74 | +} |
0 commit comments