├── .styleci.yml ├── CHANGELOG.md ├── CONTRIBUTING.md ├── LICENSE.md ├── README.md ├── composer.json ├── config ├── .gitkeep └── config.php └── src ├── Edge.php ├── ErdGeneratorServiceProvider.php ├── GenerateDiagramCommand.php ├── GraphBuilder.php ├── Model.php ├── ModelFinder.php ├── ModelRelation.php └── RelationFinder.php /.styleci.yml: -------------------------------------------------------------------------------- 1 | preset: laravel 2 | 3 | disabled: 4 | - single_class_element_per_statement 5 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Changelog 2 | 3 | All notable changes to `laravel-er-diagram-generator` will be documented in this file 4 | 5 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing 2 | 3 | Contributions are **welcome** and will be fully **credited**. 4 | 5 | Please read and understand the contribution guide before creating an issue or pull request. 6 | 7 | ## Etiquette 8 | 9 | This project is open source, and as such, the maintainers give their free time to build and maintain the source code 10 | held within. They make the code freely available in the hope that it will be of use to other developers. It would be 11 | extremely unfair for them to suffer abuse or anger for their hard work. 12 | 13 | Please be considerate towards maintainers when raising issues or presenting pull requests. Let's show the 14 | world that developers are civilized and selfless people. 15 | 16 | It's the duty of the maintainer to ensure that all submissions to the project are of sufficient 17 | quality to benefit the project. Many developers have different skillsets, strengths, and weaknesses. Respect the maintainer's decision, and do not be upset or abusive if your submission is not used. 18 | 19 | ## Viability 20 | 21 | When requesting or submitting new features, first consider whether it might be useful to others. Open 22 | source projects are used by many developers, who may have entirely different needs to your own. Think about 23 | whether or not your feature is likely to be used by other users of the project. 24 | 25 | ## Procedure 26 | 27 | Before filing an issue: 28 | 29 | - Attempt to replicate the problem, to ensure that it wasn't a coincidental incident. 30 | - Check to make sure your feature suggestion isn't already present within the project. 31 | - Check the pull requests tab to ensure that the bug doesn't have a fix in progress. 32 | - Check the pull requests tab to ensure that the feature isn't already in progress. 33 | 34 | Before submitting a pull request: 35 | 36 | - Check the codebase to ensure that your feature doesn't already exist. 37 | - Check the pull requests to ensure that another person hasn't already submitted the feature or fix. 38 | 39 | ## Requirements 40 | 41 | If the project maintainer has any additional requirements, you will find them listed here. 42 | 43 | - **[PSR-2 Coding Standard](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-2-coding-style-guide.md)** - The easiest way to apply the conventions is to install [PHP Code Sniffer](https://pear.php.net/package/PHP_CodeSniffer). 44 | 45 | - **Add tests!** - Your patch won't be accepted if it doesn't have tests. 46 | 47 | - **Document any change in behaviour** - Make sure the `README.md` and any other relevant documentation are kept up-to-date. 48 | 49 | - **Consider our release cycle** - We try to follow [SemVer v2.0.0](https://semver.org/). Randomly breaking public APIs is not an option. 50 | 51 | - **One pull request per feature** - If you want to do more than one thing, send multiple pull requests. 52 | 53 | - **Send coherent history** - Make sure each individual commit in your pull request is meaningful. If you had to make multiple intermediate commits while developing, please [squash them](https://www.git-scm.com/book/en/v2/Git-Tools-Rewriting-History#Changing-Multiple-Commit-Messages) before submitting. 54 | 55 | **Happy coding**! 56 | -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) Beyond Code GmbH 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in 13 | all copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 21 | THE SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Laravel ER Diagram Generator 2 | 3 | [![Latest Version on Packagist](https://img.shields.io/packagist/v/beyondcode/laravel-er-diagram-generator.svg?style=flat-square)](https://packagist.org/packages/beyondcode/laravel-er-diagram-generator) 4 | [![Total Downloads](https://img.shields.io/packagist/dt/beyondcode/laravel-er-diagram-generator.svg?style=flat-square)](https://packagist.org/packages/beyondcode/laravel-er-diagram-generator) 5 | 6 | This package lets you generate entity relation diagrams by inspecting the relationships defined in your model files. 7 | It is highly customizable. 8 | Behind the scenes, it uses [GraphViz](https://www.graphviz.org) to generate the graph. 9 | 10 | > If you want to learn how to create reusable PHP packages yourself, take a look at my upcoming [PHP Package Development](https://phppackagedevelopment.com) video course. 11 | 12 | ## Prerequisites 13 | 14 | The minimum required PHP version is 7.1.0. 15 | 16 | ## Requirements 17 | 18 | This package requires the `graphviz` tool. 19 | 20 | You can install Graphviz on MacOS via homebrew: 21 | 22 | ```bash 23 | brew install graphviz 24 | ``` 25 | 26 | Or, if you are using Homestead: 27 | 28 | ```bash 29 | sudo apt-get install graphviz 30 | ``` 31 | 32 | To install Graphviz on Windows, download it from the [official website](https://graphviz.gitlab.io/_pages/Download/Download_windows.html). 33 | 34 | ## Installation 35 | 36 | You can install the package via composer: 37 | 38 | ```bash 39 | composer require beyondcode/laravel-er-diagram-generator --dev 40 | ``` 41 | 42 | If you are using Laravel 5.5+, the package will automatically register the service provider for you. 43 | 44 | If you are using Lumen, you will need to add the following to `bootstrap\app.php`: 45 | 46 | ```php 47 | # Register Service Providers 48 | $app->register(BeyondCode\ErdGenerator\ErdGeneratorServiceProvider::class); 49 | ``` 50 | 51 | ## Usage 52 | 53 | By default, the package will automatically detect all models in your `app/Models` directory that extend the Eloquent Model class. If you would like you explicitly define where your models are located, you can publish the configuration file using the following command. 54 | 55 | ```bash 56 | php artisan vendor:publish --provider=BeyondCode\\ErdGenerator\\ErdGeneratorServiceProvider 57 | ``` 58 | 59 | If you're using Lumen and you want to customize the config, you'll need to copy the config file from the vendor directory: 60 | 61 | ```bash 62 | cp ./vendor/beyondcode/laravel-er-diagram-generator/config/config.php config/erd-generator.php 63 | ``` 64 | 65 | ## Generating Diagrams 66 | 67 | You can generate entity relation diagrams using the provided artisan command: 68 | 69 | ```bash 70 | php artisan generate:erd 71 | ``` 72 | 73 | This will generate a file called `graph.png`. 74 | 75 | You can also specify a custom filename: 76 | 77 | ```bash 78 | php artisan generate:erd output.png 79 | ``` 80 | 81 | Or use one of the other [output formats](https://www.graphviz.org/doc/info/output.html), like SVG: 82 | 83 | ```bash 84 | php artisan generate:erd output.svg --format=svg 85 | ``` 86 | 87 | ## Customization 88 | 89 | Please take a look at the published `erd-generator.php` configuration file for all available customization options. 90 | 91 | ## Examples 92 | 93 | Here are some examples taken from the [Laravel.io](https://laravel.io) codebase. 94 | 95 | ![Using Database Schema](https://beyondco.de/github/erd-generator/schema.png) 96 | 97 | ![Customized](https://beyondco.de/github/erd-generator/customized.png) 98 | 99 | ### Testing 100 | 101 | ``` bash 102 | composer test 103 | ``` 104 | 105 | ### Changelog 106 | 107 | Please see [CHANGELOG](CHANGELOG.md) for more information what has changed recently. 108 | 109 | ## Contributing 110 | 111 | Please see [CONTRIBUTING](CONTRIBUTING.md) for details. 112 | 113 | ### Security 114 | 115 | If you discover any security related issues, please email marcel@beyondco.de instead of using the issue tracker. 116 | 117 | ## Credits 118 | 119 | - [Marcel Pociot](https://github.com/mpociot) 120 | - [All Contributors](../../contributors) 121 | 122 | ## License 123 | 124 | The MIT License (MIT). Please see [License File](LICENSE.md) for more information. 125 | -------------------------------------------------------------------------------- /composer.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "beyondcode/laravel-er-diagram-generator", 3 | "description": "Generate ER diagrams from your Laravel models.", 4 | "keywords": [ 5 | "beyondcode", 6 | "laravel-er-diagram-generator" 7 | ], 8 | "homepage": "https://github.com/beyondcode/laravel-er-diagram-generator", 9 | "license": "MIT", 10 | "authors": [ 11 | { 12 | "name": "Marcel Pociot", 13 | "email": "marcel@beyondco.de", 14 | "homepage": "https://beyondcode.de", 15 | "role": "Developer" 16 | } 17 | ], 18 | "require": { 19 | "php": "^7.1|^8.0", 20 | "doctrine/dbal": "~2.3|^3.3|^4.0", 21 | "phpdocumentor/graphviz": "^1.0", 22 | "nikic/php-parser": "^2.0|^3.0|^4.0|^5.0" 23 | }, 24 | "require-dev": { 25 | "larapack/dd": "^1.0", 26 | "orchestra/testbench": "~3.5|~3.6|~3.7|~3.8|^4.0|^7.0|^8.0|^9.0", 27 | "phpunit/phpunit": "^7.0| ^8.0|^9.5.10|^10.5|^11.0.1", 28 | "spatie/phpunit-snapshot-assertions": "^1.3|^4.2|^5.1" 29 | }, 30 | "autoload": { 31 | "psr-4": { 32 | "BeyondCode\\ErdGenerator\\": "src" 33 | } 34 | }, 35 | "autoload-dev": { 36 | "psr-4": { 37 | "BeyondCode\\ErdGenerator\\Tests\\": "tests" 38 | } 39 | }, 40 | "scripts": { 41 | "test": "vendor/bin/phpunit", 42 | "test-coverage": "vendor/bin/phpunit --coverage-html coverage" 43 | }, 44 | "config": { 45 | "sort-packages": true 46 | }, 47 | "extra": { 48 | "laravel": { 49 | "providers": [ 50 | "BeyondCode\\ErdGenerator\\ErdGeneratorServiceProvider" 51 | ] 52 | } 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /config/.gitkeep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/beyondcode/laravel-er-diagram-generator/07254be884d7d022559a7c88a10b41b9edd1e4ed/config/.gitkeep -------------------------------------------------------------------------------- /config/config.php: -------------------------------------------------------------------------------- 1 | [ 10 | base_path('app' . DIRECTORY_SEPARATOR . 'Models'), 11 | ], 12 | 13 | /* 14 | * If you want to ignore complete models or certain relations of a specific model, 15 | * you can specify them here. 16 | * To ignore a model completely, just add the fully qualified classname. 17 | * To ignore only a certain relation of a model, enter the classname as the key 18 | * and an array of relation names to ignore. 19 | */ 20 | 'ignore' => [ 21 | // User::class, 22 | // Post::class => [ 23 | // 'user' 24 | // ] 25 | ], 26 | 27 | /* 28 | * If you want to see only specific models, specify them here using fully qualified 29 | * classnames. 30 | * 31 | * Note: that if this array is filled, the 'ignore' array will not be used. 32 | */ 33 | 'whitelist' => [ 34 | // App\User::class, 35 | // App\Post::class, 36 | ], 37 | 38 | /* 39 | * If true, all directories specified will be scanned recursively for models. 40 | * Set this to false if you prefer to explicitly define each directory that should 41 | * be scanned for models. 42 | */ 43 | 'recursive' => true, 44 | 45 | /* 46 | * The generator will automatically try to look up the model specific columns 47 | * and add them to the generated output. If you do not wish to use this 48 | * feature, you can disable it here. 49 | */ 50 | 'use_db_schema' => true, 51 | 52 | /* 53 | * This setting toggles weather the column types (VARCHAR, INT, TEXT, etc.) 54 | * should be visible on the generated diagram. This option requires 55 | * 'use_db_schema' to be set to true. 56 | */ 57 | 'use_column_types' => true, 58 | 59 | /* 60 | * These colors will be used in the table representation for each entity in 61 | * your graph. 62 | */ 63 | 'table' => [ 64 | 'header_background_color' => '#d3d3d3', 65 | 'header_font_color' => '#333333', 66 | 'row_background_color' => '#ffffff', 67 | 'row_font_color' => '#333333', 68 | ], 69 | 70 | /* 71 | * Here you can define all the available Graphviz attributes that should be applied to your graph, 72 | * to its nodes and to the edge (the connection between the nodes). Depending on the size of 73 | * your diagram, different settings might produce better looking results for you. 74 | * 75 | * See http://www.graphviz.org/doc/info/attrs.html#d:label for a full list of attributes. 76 | */ 77 | 'graph' => [ 78 | 'style' => 'filled', 79 | 'bgcolor' => '#F7F7F7', 80 | 'fontsize' => 12, 81 | 'labelloc' => 't', 82 | 'concentrate' => true, 83 | 'splines' => 'polyline', 84 | 'overlap' => false, 85 | 'nodesep' => 1, 86 | 'rankdir' => 'LR', 87 | 'pad' => 0.5, 88 | 'ranksep' => 2, 89 | 'esep' => true, 90 | 'fontname' => 'Helvetica Neue' 91 | ], 92 | 93 | 'node' => [ 94 | 'margin' => 0, 95 | 'shape' => 'rectangle', 96 | 'fontname' => 'Helvetica Neue' 97 | ], 98 | 99 | 'edge' => [ 100 | 'color' => '#003049', 101 | 'penwidth' => 1.8, 102 | 'fontname' => 'Helvetica Neue' 103 | ], 104 | 105 | 'relations' => [ 106 | 'HasOne' => [ 107 | 'dir' => 'both', 108 | 'color' => '#D62828', 109 | 'arrowhead' => 'tee', 110 | 'arrowtail' => 'none', 111 | ], 112 | 'BelongsTo' => [ 113 | 'dir' => 'both', 114 | 'color' => '#F77F00', 115 | 'arrowhead' => 'tee', 116 | 'arrowtail' => 'crow', 117 | ], 118 | 'HasMany' => [ 119 | 'dir' => 'both', 120 | 'color' => '#FCBF49', 121 | 'arrowhead' => 'crow', 122 | 'arrowtail' => 'none', 123 | ], 124 | ] 125 | 126 | ]; 127 | -------------------------------------------------------------------------------- /src/Edge.php: -------------------------------------------------------------------------------- 1 | fromPort = $fromPort; 35 | } 36 | 37 | /** 38 | * @param null $toPort 39 | */ 40 | public function setToPort($toPort): void 41 | { 42 | $this->toPort = $toPort; 43 | } 44 | 45 | /** 46 | * Returns the edge definition as is requested by GraphViz. 47 | * 48 | * @return string 49 | */ 50 | public function __toString() 51 | { 52 | $attributes = array(); 53 | foreach ($this->attributes as $value) { 54 | $attributes[] = (string)$value; 55 | } 56 | $attributes = implode("\n", $attributes); 57 | 58 | $from_name = addslashes($this->getFrom()->getName()); 59 | $to_name = addslashes($this->getTo()->getName()); 60 | $from_name .= (!empty($this->fromPort)) ? ':' . $this->fromPort : ''; 61 | $to_name .= (!empty($this->toPort)) ? ':' . $this->toPort : ''; 62 | 63 | return << $to_name [ 65 | $attributes 66 | ] 67 | DOT; 68 | } 69 | } -------------------------------------------------------------------------------- /src/ErdGeneratorServiceProvider.php: -------------------------------------------------------------------------------- 1 | app->runningInConsole()) { 15 | $this->publishes([ 16 | __DIR__.'/../config/config.php' => base_path('config/erd-generator.php'), 17 | ], 'config'); 18 | } 19 | } 20 | 21 | /** 22 | * Register the application services. 23 | */ 24 | public function register() 25 | { 26 | $this->mergeConfigFrom(__DIR__.'/../config/config.php', 'erd-generator'); 27 | 28 | $this->app->bind('command.generate:diagram', GenerateDiagramCommand::class); 29 | 30 | $this->commands([ 31 | 'command.generate:diagram', 32 | ]); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/GenerateDiagramCommand.php: -------------------------------------------------------------------------------- 1 | relationFinder = $relationFinder; 48 | $this->modelFinder = $modelFinder; 49 | $this->graphBuilder = $graphBuilder; 50 | } 51 | 52 | /** 53 | * @throws \phpDocumentor\GraphViz\Exception 54 | */ 55 | public function handle() 56 | { 57 | $models = $this->getModelsThatShouldBeInspected(); 58 | 59 | $this->info("Found {$models->count()} models."); 60 | $this->info("Inspecting model relations."); 61 | 62 | $bar = $this->output->createProgressBar($models->count()); 63 | 64 | $models->transform(function ($model) use ($bar) { 65 | $bar->advance(); 66 | return new GraphModel( 67 | $model, 68 | (new ReflectionClass($model))->getShortName(), 69 | $this->relationFinder->getModelRelations($model) 70 | ); 71 | }); 72 | 73 | $graph = $this->graphBuilder->buildGraph($models); 74 | 75 | if ($this->option('format') === self::FORMAT_TEXT) { 76 | $this->info($graph->__toString()); 77 | return; 78 | } 79 | 80 | $graph->export($this->option('format'), $this->getOutputFileName()); 81 | 82 | $this->info(PHP_EOL); 83 | $this->info('Wrote diagram to ' . $this->getOutputFileName()); 84 | } 85 | 86 | protected function getOutputFileName(): string 87 | { 88 | return $this->argument('filename') ?: 89 | static::DEFAULT_FILENAME . '.' . $this->option('format'); 90 | } 91 | 92 | protected function getModelsThatShouldBeInspected(): Collection 93 | { 94 | $directories = config('erd-generator.directories'); 95 | 96 | $modelsFromDirectories = $this->getAllModelsFromEachDirectory($directories); 97 | 98 | return $modelsFromDirectories; 99 | } 100 | 101 | protected function getAllModelsFromEachDirectory(array $directories): Collection 102 | { 103 | return collect($directories) 104 | ->map(function ($directory) { 105 | return $this->modelFinder->getModelsInDirectory($directory)->all(); 106 | }) 107 | ->flatten(); 108 | } 109 | } 110 | -------------------------------------------------------------------------------- /src/GraphBuilder.php: -------------------------------------------------------------------------------- 1 | graph = new Graph(); 23 | 24 | foreach (config('erd-generator.graph') as $key => $value) { 25 | $this->graph->{"set{$key}"}($value); 26 | } 27 | 28 | $this->addModelsToGraph($models); 29 | 30 | return $this->graph; 31 | } 32 | 33 | protected function getTableColumnsFromModel(EloquentModel $model) 34 | { 35 | try { 36 | 37 | $table = $model->getConnection()->getTablePrefix() . $model->getTable(); 38 | $schema = $model->getConnection()->getDoctrineSchemaManager($table); 39 | $databasePlatform = $schema->getDatabasePlatform(); 40 | $databasePlatform->registerDoctrineTypeMapping('enum', 'string'); 41 | 42 | $database = null; 43 | 44 | if (strpos($table, '.')) { 45 | list($database, $table) = explode('.', $table); 46 | } 47 | 48 | return $schema->listTableColumns($table, $database); 49 | } catch (\Throwable $e) { 50 | } 51 | 52 | return []; 53 | } 54 | 55 | protected function getModelLabel(EloquentModel $model, string $label) 56 | { 57 | 58 | $table = '<' . PHP_EOL; 59 | $table .= '' . PHP_EOL; 60 | 61 | if (config('erd-generator.use_db_schema')) { 62 | $columns = $this->getTableColumnsFromModel($model); 63 | foreach ($columns as $column) { 64 | $label = $column->getName(); 65 | if (config('erd-generator.use_column_types')) { 66 | $label .= ' ('.$column->getType()->getName().')'; 67 | } 68 | $table .= '' . PHP_EOL; 69 | } 70 | } 71 | 72 | $table .= '
' . $label . '
' . $label . '
>'; 73 | 74 | return $table; 75 | } 76 | 77 | protected function addModelsToGraph(Collection $models) 78 | { 79 | // Add models to graph 80 | $models->map(function (Model $model) { 81 | $eloquentModel = app($model->getModel()); 82 | $this->addNodeToGraph($eloquentModel, $model->getNodeName(), $model->getLabel()); 83 | }); 84 | 85 | // Create relations 86 | $models->map(function ($model) { 87 | $this->addRelationToGraph($model); 88 | }); 89 | } 90 | 91 | protected function addNodeToGraph(EloquentModel $eloquentModel, string $nodeName, string $label) 92 | { 93 | $node = Node::create($nodeName); 94 | $node->setLabel($this->getModelLabel($eloquentModel, $label)); 95 | 96 | foreach (config('erd-generator.node') as $key => $value) { 97 | $node->{"set{$key}"}($value); 98 | } 99 | 100 | $this->graph->setNode($node); 101 | } 102 | 103 | protected function addRelationToGraph(Model $model) 104 | { 105 | 106 | $modelNode = $this->graph->findNode($model->getNodeName()); 107 | 108 | /** @var ModelRelation $relation */ 109 | foreach ($model->getRelations() as $relation) { 110 | $relatedModelNode = $this->graph->findNode($relation->getModelNodeName()); 111 | 112 | if ($relatedModelNode !== null) { 113 | $this->connectByRelation($model, $relation, $modelNode, $relatedModelNode); 114 | } 115 | } 116 | } 117 | 118 | /** 119 | * @param Node $modelNode 120 | * @param Node $relatedModelNode 121 | * @param ModelRelation $relation 122 | */ 123 | protected function connectNodes(Node $modelNode, Node $relatedModelNode, ModelRelation $relation): void 124 | { 125 | $edge = Edge::create($modelNode, $relatedModelNode); 126 | $edge->setFromPort($relation->getLocalKey()); 127 | $edge->setToPort($relation->getForeignKey()); 128 | $edge->setLabel(' '); 129 | $edge->setXLabel($relation->getType() . PHP_EOL . $relation->getName()); 130 | 131 | foreach (config('erd-generator.edge') as $key => $value) { 132 | $edge->{"set{$key}"}($value); 133 | } 134 | 135 | foreach (config('erd-generator.relations.' . $relation->getType(), []) as $key => $value) { 136 | $edge->{"set{$key}"}($value); 137 | } 138 | 139 | $this->graph->link($edge); 140 | } 141 | 142 | /** 143 | * @param Model $model 144 | * @param ModelRelation $relation 145 | * @param Node $modelNode 146 | * @param Node $relatedModelNode 147 | * @return void 148 | */ 149 | protected function connectBelongsToMany( 150 | Model $model, 151 | ModelRelation $relation, 152 | Node $modelNode, 153 | Node $relatedModelNode 154 | ): void { 155 | $relationName = $relation->getName(); 156 | $eloquentModel = app($model->getModel()); 157 | 158 | /** @var BelongsToMany $eloquentRelation */ 159 | $eloquentRelation = $eloquentModel->$relationName(); 160 | 161 | if (!$eloquentRelation instanceof BelongsToMany) { 162 | return; 163 | } 164 | 165 | $pivotClass = $eloquentRelation->getPivotClass(); 166 | 167 | try { 168 | /** @var EloquentModel $relationModel */ 169 | $pivotModel = app($pivotClass); 170 | $pivotModel->setTable($eloquentRelation->getTable()); 171 | $label = (new \ReflectionClass($pivotClass))->getShortName(); 172 | $pivotTable = $eloquentRelation->getTable(); 173 | $this->addNodeToGraph($pivotModel, $pivotTable, $label); 174 | 175 | $pivotModelNode = $this->graph->findNode($pivotTable); 176 | 177 | $relation = new ModelRelation( 178 | $relationName, 179 | 'BelongsToMany', 180 | $model->getModel(), 181 | $eloquentRelation->getParent()->getKeyName(), 182 | $eloquentRelation->getForeignPivotKeyName() 183 | ); 184 | 185 | $this->connectNodes($modelNode, $pivotModelNode, $relation); 186 | 187 | $relation = new ModelRelation( 188 | $relationName, 189 | 'BelongsToMany', 190 | $model->getModel(), 191 | $eloquentRelation->getRelatedPivotKeyName(), 192 | $eloquentRelation->getRelated()->getKeyName() 193 | ); 194 | 195 | $this->connectNodes($pivotModelNode, $relatedModelNode, $relation); 196 | } catch (\ReflectionException $e){} 197 | } 198 | 199 | /** 200 | * @param Model $model 201 | * @param ModelRelation $relation 202 | * @param Node $modelNode 203 | * @param Node $relatedModelNode 204 | */ 205 | protected function connectByRelation( 206 | Model $model, 207 | ModelRelation $relation, 208 | Node $modelNode, 209 | Node $relatedModelNode 210 | ): void { 211 | 212 | if ($relation->getType() === 'BelongsToMany') { 213 | $this->connectBelongsToMany($model, $relation, $modelNode, $relatedModelNode); 214 | return; 215 | } 216 | 217 | $this->connectNodes($modelNode, $relatedModelNode, $relation); 218 | } 219 | } 220 | -------------------------------------------------------------------------------- /src/Model.php: -------------------------------------------------------------------------------- 1 | model = $model; 17 | $this->label = $label; 18 | $this->relations = $relations; 19 | } 20 | 21 | /** 22 | * @return mixed 23 | */ 24 | public function getModel() 25 | { 26 | return $this->model; 27 | } 28 | 29 | /** 30 | * @return string 31 | */ 32 | public function getNodeName() 33 | { 34 | return str_replace('-', '', Str::slug($this->model)); 35 | } 36 | 37 | /** 38 | * @return mixed 39 | */ 40 | public function getLabel() 41 | { 42 | return $this->label; 43 | } 44 | 45 | /** 46 | * @return Collection 47 | */ 48 | public function getRelations() 49 | { 50 | return $this->relations; 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /src/ModelFinder.php: -------------------------------------------------------------------------------- 1 | filesystem = $filesystem; 25 | } 26 | 27 | public function getModelsInDirectory(string $directory): Collection 28 | { 29 | $files = config('erd-generator.recursive') ? 30 | $this->filesystem->allFiles($directory) : 31 | $this->filesystem->files($directory); 32 | 33 | $ignoreModels = array_filter(config('erd-generator.ignore', []), 'is_string'); 34 | $whitelistModels = array_filter(config('erd-generator.whitelist', []), 'is_string'); 35 | 36 | $collection = Collection::make($files)->filter(function ($path) { 37 | return Str::endsWith($path, '.php'); 38 | })->map(function ($path) { 39 | return $this->getFullyQualifiedClassNameFromFile($path); 40 | })->filter(function (string $className) { 41 | return !empty($className) 42 | && is_subclass_of($className, EloquentModel::class) 43 | && ! (new ReflectionClass($className))->isAbstract(); 44 | }); 45 | 46 | if(!count($whitelistModels)) { 47 | return $collection->diff($ignoreModels)->sort(); 48 | } 49 | 50 | return $collection->filter(function (string $className) use ($whitelistModels) { 51 | return in_array($className, $whitelistModels); 52 | }); 53 | } 54 | 55 | protected function getFullyQualifiedClassNameFromFile(string $path): string 56 | { 57 | $factory = new ParserFactory(); 58 | $parser = method_exists($factory, 'createForHostVersion') 59 | ? $factory->createForHostVersion() 60 | : $factory->create(ParserFactory::PREFER_PHP7); 61 | 62 | $traverser = new NodeTraverser(); 63 | $traverser->addVisitor(new NameResolver()); 64 | 65 | $code = file_get_contents($path); 66 | 67 | $statements = $parser->parse($code); 68 | $statements = $traverser->traverse($statements); 69 | 70 | // get the first namespace declaration in the file 71 | $root_statement = collect($statements)->first(function ($statement) { 72 | return $statement instanceof Namespace_; 73 | }); 74 | 75 | if (! $root_statement) { 76 | return ''; 77 | } 78 | 79 | return collect($root_statement->stmts) 80 | ->filter(function ($statement) { 81 | return $statement instanceof Class_; 82 | }) 83 | ->map(function (Class_ $statement) { 84 | return $statement->namespacedName->toString(); 85 | }) 86 | ->first() ?? ''; 87 | } 88 | } 89 | -------------------------------------------------------------------------------- /src/ModelRelation.php: -------------------------------------------------------------------------------- 1 | type = $type; 17 | $this->model = $model; 18 | $this->localKey = $localKey; 19 | $this->foreignKey = $foreignKey; 20 | $this->name = $name; 21 | } 22 | 23 | /** 24 | * @return mixed 25 | */ 26 | public function getModel() 27 | { 28 | return $this->model; 29 | } 30 | 31 | /** 32 | * @return string 33 | */ 34 | public function getModelNodeName() 35 | { 36 | return Str::slug($this->model); 37 | } 38 | 39 | /** 40 | * @return mixed 41 | */ 42 | public function getType() 43 | { 44 | return $this->type; 45 | } 46 | 47 | /** 48 | * @return null 49 | */ 50 | public function getLocalKey() 51 | { 52 | return $this->localKey; 53 | } 54 | 55 | /** 56 | * @return mixed 57 | */ 58 | public function getForeignKey() 59 | { 60 | return $this->foreignKey; 61 | } 62 | 63 | /** 64 | * @return mixed 65 | */ 66 | public function getName() 67 | { 68 | return $this->name; 69 | } 70 | } 71 | -------------------------------------------------------------------------------- /src/RelationFinder.php: -------------------------------------------------------------------------------- 1 | getTraits())->map(function (ReflectionClass $trait) { 28 | return Collection::make($trait->getMethods(ReflectionMethod::IS_PUBLIC)); 29 | })->flatten(); 30 | 31 | $methods = Collection::make($class->getMethods(ReflectionMethod::IS_PUBLIC)) 32 | ->merge($traitMethods) 33 | ->reject(function (ReflectionMethod $method) use ($model) { 34 | return $method->class !== $model || $method->getNumberOfParameters() > 0 || $method->isStatic();; 35 | }); 36 | 37 | $relations = Collection::make(); 38 | 39 | $methods->map(function (ReflectionMethod $method) use ($model, &$relations) { 40 | $relations = $relations->merge($this->getRelationshipFromMethodAndModel($method, $model)); 41 | }); 42 | 43 | $relations = $relations->filter(); 44 | 45 | if ($ignoreRelations = Arr::get(config('erd-generator.ignore', []),$model)) 46 | { 47 | $relations = $relations->diffKeys(array_flip($ignoreRelations)); 48 | } 49 | 50 | return $relations; 51 | } 52 | 53 | /** 54 | * @param string $qualifiedKeyName 55 | * @return mixed 56 | */ 57 | protected function getParentKey(string $qualifiedKeyName) 58 | { 59 | $segments = explode('.', $qualifiedKeyName); 60 | 61 | return end($segments); 62 | } 63 | 64 | /** 65 | * @param ReflectionMethod $method 66 | * @param string $model 67 | * @return array|null 68 | */ 69 | protected function getRelationshipFromMethodAndModel(ReflectionMethod $method, string $model) 70 | { 71 | try { 72 | $return = $method->invoke(app($model)); 73 | 74 | if ($return instanceof Relation) { 75 | $localKey = null; 76 | $foreignKey = null; 77 | 78 | if ($return instanceof HasOneOrMany) { 79 | $localKey = $this->getParentKey($return->getQualifiedParentKeyName()); 80 | $foreignKey = $return->getForeignKeyName(); 81 | } 82 | 83 | if ($return instanceof BelongsTo) { 84 | $foreignKey = $this->getParentKey($return->getQualifiedOwnerKeyName()); 85 | $localKey = method_exists($return, 'getForeignKeyName') ? $return->getForeignKeyName() : $return->getForeignKey(); 86 | } 87 | 88 | return [ 89 | $method->getName() => new ModelRelation( 90 | $method->getShortName(), 91 | (new ReflectionClass($return))->getShortName(), 92 | (new ReflectionClass($return->getRelated()))->getName(), 93 | $localKey, 94 | $foreignKey 95 | ) 96 | ]; 97 | } 98 | } catch (\Throwable $e) {} 99 | return null; 100 | } 101 | 102 | } 103 | --------------------------------------------------------------------------------