generate_entity_diagrams 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. #!/usr/bin/env php
  2. <?php
  3. define('INSTALL_DIR', dirname(__DIR__));
  4. require INSTALL_DIR . '/vendor/autoload.php';
  5. use App\Util\Formatting;
  6. use App\Util\HTML as H;
  7. use Functional as F;
  8. $template = '
  9. graph database {
  10. %tables%
  11. %edges%
  12. }
  13. ';
  14. $files = glob(INSTALL_DIR . '/src/Entity/*.php');
  15. $tables = [];
  16. $edges = [];
  17. $classes = [];
  18. foreach ($files as $file) {
  19. require_once $file;
  20. $class = '';
  21. $declared = get_declared_classes();
  22. foreach ($declared as $dc) {
  23. if (preg_match('/^(App|(Component|Plugin)\\\\[^\\\\]+)\\\\Entity/', $dc) && !in_array($dc, $classes)) {
  24. $class = $dc;
  25. $classes[] = $class;
  26. break;
  27. }
  28. }
  29. $schema = $class::schemaDef();
  30. $table = preg_replace(',`?([^`]+)`?,', '$1', $schema['name']);
  31. $fields = [['name' => $table, 'type' => '']];
  32. foreach ($schema['fields'] as $name => $opts) {
  33. $fields[] = [
  34. 'name' => $name,
  35. 'type' => ": {$opts['type']}" . ($opts['type'] == 'varchar' ? "({$opts['length']})" : ''),
  36. ];
  37. }
  38. foreach ($schema['fields'] as $field => $opts) {
  39. if (isset($opts['foreign key'])) {
  40. [$foreign_entity, $foreign_key] = explode('.', $opts['target']);
  41. $foreign_table = Formatting::camelCaseToSnakeCase(preg_replace('/Actor/', 'actor', $foreign_entity));
  42. $edges[] = "{$table}:{$field} -- {$foreign_table}:{$foreign_key}";
  43. }
  44. }
  45. $cell = function ($field) {
  46. $def = $field['name'] . $field['type'];
  47. return ['tr' => ['td' => ['attrs' => ['port' => $field['name']], $def]]];
  48. };
  49. $html = ['table' => array_merge(
  50. ['attrs' => ['border' => '0', 'cellborder' => '1', 'cellspacing' => '0']],
  51. F\map($fields, $cell)),
  52. ];
  53. $tables[] = Formatting::indent("{$table} [shape=none, label=<\n" . Formatting::indent(H::html($html)) . "\n>]");
  54. }
  55. $replace = [
  56. '/%tables%/' => Formatting::indent(implode("\n", $tables)),
  57. '/%edges%/' => Formatting::indent(implode("\n", $edges)),
  58. // '/_/' => '\textunderscore ',
  59. ];
  60. $out = $template;
  61. foreach ($replace as $from => $to) {
  62. $out = preg_replace($from, $to, $out);
  63. }
  64. $path = dirname(__DIR__) . '/docs/developer/src/database';
  65. $outfile = $path . '/database.dot';
  66. file_put_contents($outfile, $out);
  67. system("neato -Goverlap=false -Gsplines=true -Tpdf {$path}/database.dot -o {$path}/database.pdf");
  68. echo "Generated database diagram. See {$path}/database.pdf\n";