|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace Backpack\CRUD\app\Library\Database; |
|
4
|
|
|
|
|
5
|
|
|
use Illuminate\Support\Facades\DB; |
|
6
|
|
|
use Illuminate\Support\LazyCollection; |
|
7
|
|
|
|
|
8
|
|
|
final class DatabaseSchema |
|
9
|
|
|
{ |
|
10
|
|
|
private static $schema; |
|
11
|
|
|
|
|
12
|
|
|
/** |
|
13
|
|
|
* Return the schema for the table. |
|
14
|
|
|
* |
|
15
|
|
|
* @param string $connection |
|
16
|
|
|
* @param string $table |
|
17
|
|
|
* @return array |
|
18
|
|
|
*/ |
|
19
|
|
|
public static function getForTable(string $connection, string $table) |
|
20
|
|
|
{ |
|
21
|
|
|
self::generateDatabaseSchema($connection, $table); |
|
22
|
|
|
|
|
23
|
|
|
return self::$schema[$connection][$table] ?? []; |
|
24
|
|
|
} |
|
25
|
|
|
|
|
26
|
|
|
/** |
|
27
|
|
|
* Generates and store the database schema. |
|
28
|
|
|
* |
|
29
|
|
|
* @param string $connection |
|
30
|
|
|
* @param string $table |
|
31
|
|
|
* @return void |
|
32
|
|
|
*/ |
|
33
|
|
|
private static function generateDatabaseSchema(string $connection, string $table) |
|
34
|
|
|
{ |
|
35
|
|
|
if (! isset(self::$schema[$connection]) || ! isset(self::$schema[$connection][$table])) { |
|
36
|
|
|
self::$schema[$connection] = self::mapTables($connection); |
|
37
|
|
|
} |
|
38
|
|
|
} |
|
39
|
|
|
|
|
40
|
|
|
/** |
|
41
|
|
|
* Map the tables from raw db values into an usable array. |
|
42
|
|
|
* |
|
43
|
|
|
* @param Doctrine\DBAL\Schema\Schema $rawTables |
|
|
|
|
|
|
44
|
|
|
* @return array |
|
45
|
|
|
*/ |
|
46
|
|
|
private static function mapTables(string $connection) |
|
47
|
|
|
{ |
|
48
|
|
|
return LazyCollection::make(self::getSchemaManager($connection)->getTables())->mapWithKeys(function ($table, $key) use ($connection) { |
|
|
|
|
|
|
49
|
|
|
$tableName = is_array($table) ? $table['name'] : $table->getName(); |
|
50
|
|
|
if (is_array($table)) { |
|
51
|
|
|
$columns = self::getSchemaManager($connection)->getColumns($tableName); |
|
|
|
|
|
|
52
|
|
|
$table = new Table($columns); |
|
53
|
|
|
} |
|
54
|
|
|
|
|
55
|
|
|
return [$tableName => $table]; |
|
56
|
|
|
})->toArray(); |
|
57
|
|
|
} |
|
58
|
|
|
|
|
59
|
|
|
private static function getSchemaManager(string $connection) |
|
60
|
|
|
{ |
|
61
|
|
|
$connection = DB::connection($connection); |
|
62
|
|
|
|
|
63
|
|
|
return method_exists($connection, 'getDoctrineSchemaManager') ? $connection->getDoctrineSchemaManager()->createSchema() : $connection->getSchemaBuilder(); |
|
|
|
|
|
|
64
|
|
|
} |
|
65
|
|
|
} |
|
66
|
|
|
|