commit 6bc3c69c3ec8c70fe021df8bcd0b9b004286f477 Author: Mark Gregory Date: Tue Apr 21 09:12:51 2026 +0100 Initial Commit diff --git a/.DS_Store b/.DS_Store new file mode 100644 index 0000000..0c9137c Binary files /dev/null and b/.DS_Store differ diff --git a/.editorconfig b/.editorconfig new file mode 100755 index 0000000..5dc96b4 --- /dev/null +++ b/.editorconfig @@ -0,0 +1,14 @@ +; This file is for unifying the coding style for different editors and IDEs. + +root = true; + +[*] +charset = utf_8 +indent_size = 4 +indent_style = space +end_of_line = lf +insert_final_newline = true +trim_trailing_whitespace = true + +[*.md] +trim_trailing_whitespace = false diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100755 index 0000000..079366b --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,569 @@ +# Changelog + +All Notable changes to `laravel-modules` will be documented in this file. + +## Next + +## 9.0.1 - 2025-05-07 +- Added new generators for helper and also components +## 8.0 - 2020-10-03 + +### Added + +- Laravel 8 support + +### Updated + +- Update `ListenerMakeCommand` to properly use the `--events` option + +## 7.2.0 - 2020-07-30 + +### Added + +- Added return statements in artisan commands. Helpful to validate if something was successfully ran. (#1026) + +### Changed + +- Update JsonResource namespace, using the new `Illuminate\Http\Resources\Json\JsonResource`. (#969) +- Enable command returns the status code (#978) +- Removing module service provider from composer.json stub (#996) +- Fixed custom stub path issue. Replacing a hardcoded stub path. (#1016) +- Controller return type changed to `Illuminate\Contracts\Support\Renderable`. (#1020) +- Change bigIncrements method to id (#1029) +- Adding force option for module:seed (#1030) + +## 7.1.0 - 2020-04-14 + +### Changed + +- `php artsian module:enable` (without any arguments) will enable all modules +- `php artsian module:disable` (without any arguments) will disable all modules +- Updating Laravel Mix version as well as cross-env. + +## 7.0.0 - 2020-03-26 + +### Added + +- Laravel 7.0 support + +## 6.2.0 - 2019-11-12 + +### Changed + +- Properly guessing the namespace from the path (in `GeneratorPath` class) +- Fixing generation of resource file if the resource has been disabled to generate +- Fix when using a custom service provider namespace, namespace is correctly referenced in module.json and compose.json +- Fix when using custom service provider namespace, module path is correctly referenced in the `RouteServiceProvider` and `ModuleServiceProvider` +- Fix when using a custom path for controllers in the controller stub + +## 6.1.0 - 2019-11-01 + +### Added + +- Added new `module:delete` command + +### Changed + +- Add optional path parameter to `module_path` helper (PR#861) +- The default path of the `module_statuses.json` file has been moved to the Application's base path. This is to improve its visibility and the fact that it can be committed by default. +- Throw an exception when no proper activator class was configured + +## 6.0.0 - 2019-09-19 + +### Added + +- New File Activator feature. [PR #790](https://github.com/nWidart/laravel-modules/pull/790) from @ryssbowh + + This feature changes how modules are activated and de-activated. Currently module statuses are stored on disk, this features adds the possibility of storing this status information in a database. + + **Use the command `php artisan module:v6:migrate` to have old modules active status migrated to the new system.** + +### Changed + +- Alternate way to define the namespace of modules in [PR #776](https://github.com/nWidart/laravel-modules/pull/776) by @daison12006013 + + This allows to have the content of the module under an `src/` folder for example. +- **BREAKING** New way to handle active and inactive modules. + + Modules don't store their active status in their module.json file anymore, but in a file under the storage folder. + Run `php artisan module:v6:migrate` to use the new system. +- **BREAKING** Renamed method `enabled` to `isEnabled` in `\Nwidart\Modules\Module`. +- **BREAKING** Renamed method `disabled` to `isDisabled` in `\Nwidart\Modules\Module`. +- **BREAKING** Renamed method `enabled` to `isEnabled` in `\Nwidart\Modules\FileRepository`. +- **BREAKING** Renamed method `disabled` to `isDisabled` in `\Nwidart\Modules\FileRepository`. +- **BREAKING** Removed the `__get` magic method on the `\Nwidart\Modules\Module` class. Use `get()` or `json()->get()` instead. +- The `module:make-listener` command now correctly uses the namespace configuration +- The generated Factories now has type hints for the `\Illuminate\Database\Eloquent\Factory` class +- Improved foreign key constraint generation +- Exception handling in the `SeedCommand` has been improved + +## 5.0.1 - 2019-05-11 + +### Added + +- `artisan module:route-provider` has a `--force` option to overwrite existing file + +### Changed + +- Fixing the `RouteServiceProvider` generation to properly use the `routes/web` and `routes/api` stubs +- Replacing `@stop` with `@endsection` in the view stub file +- `Module` class does not extend Laravel's Service Provider class anymore + +## 5.0.0 - 2019-03-18 + +### Added + +- Laravel 5.8 support + +### Changed + +- Deprecated string and array methods have been replaced +- Fixed caching not being cleared after disabling and enabling modules +- Update Route Provider stub to not affect the root namespace of the URL generator (#727) + +### Removed + +- **PHP 7.1 support** + +## 4.1.0 - 2019-03-04 + +### Changed + +- Updated to laravel mix 4 +- Add `--api` argument to `module:make-controller` command +- Seeding modules outside out `Modules` namespace + +## 4.0.0 - 2018-09-30 + +### Added + +- New way of handling routes by default using a RouteServiceProvider (instead of start.php) +- Laravel 5.7 support + +### Changed + +- Allow class resolution on short name and abstract +- `module:seed` accepts a `--class` option + +## 3.3.1 - 2018-07-13 + +### Changed + +- Added the ability to set a sub-namespace to controllers `module:make-controller Api\\TestController` + +## 3.3.0 - 2018-06-21 + +### Changed + +- `module:update` command has now the possibility to update all modules at once +- Fixing commented code for Laravel Mix + +## 3.2.0 - 2018-04-16 + +### Added + +- Added possibility to update all modules at once if any not specified (PR #523) + +### Changed + +- Mix: Fix css relative urls by changing the route folder (PR #521) +- Mix: Prevents every build from deleting previous Mix config file (PR #521) + +## 3.1.0 - 2018-04-01 + +### Added + +- Laravel mix configuration (https://nwidart.com/laravel-modules/v3/basic-usage/compiling-assets) + +### Changed + +- Allow symlinks in module path +- Returns the parameter `--class` to the `SeedCommand`. +- Generate folders recursively +- Removing link that has become a 404 +- Fixed seed command exception typehint + +### Removed + +- Removed the optimize command on the `module:make-migration` command + +## 3.0.1 - 2018-02-16 + +### Changed + +- Update publish commands to use the new API to get all enabled modules (PR #483 ) + +## 3.0.0 - 2018-02-14 + +## Added + +- Added support for laravel 5.6 +- Using phpunit 7 + +## Changed + +- **BC:** `Repository` class: renamed `enabled` to `allEnabled` +- **BC:** `Repository` class: renamed `disabled` to `allDisabled` +- **BC:** `Repository` class: renamed `active` to `enabled` +- **BC:** `Repository` class: renamed `notActive` to `disabled` + +## Removed + +- Dropped php 7.0 support +- **BC:** `Module` class: Deprecated `active()` method, use `enabled()` +- **BC:** `Module` class: Deprecated `notActive()` method, use `disabled()` +- **BC:** `Repository` class: Deprecated `addPath()` method, use `addLocation()` +- **BC:** `Repository` class: Deprecated `get()` method, use `find()` +- **BC:** `Repository` class: Deprecated `getUsed()` method, use `getUsedNow()` + + +## 2.7.0 - 2018-01-13 + +## Changed + +- Rename the `before` method to `boot` in the `RouterServiceProvider` stub file +- Fixing caching issue if modules were loaded from a different directory +- Fixing how modules are loaded from vendor directory (#423 #417) +- Update to Mockery 1.0 +- use default file stubs only if override does not exists +- Fix non well formed numeric value in seed command + +## 2.6.0 - 2017-11-07 + +## Added + +- Ability to customise the destination folder & namespace of a generated class +- Added `php artisan module:migrate-status` command +- `config_path()` helper for Lumen +- Added views tag to view config in ServiceProvider +- added package auto discovery for laravel 5.5 in generated module `composer.json` + +## Changed + +- Adding the ability to correctly load modules from multiple locations, together +- Custom seeder path now also used in the `module:seed` command + +## 2.5.1 - 2017-10-13 + +## Changed + +- added config_path helper to helpers for Lumen support +- updated readme on how to install laravel-modules in Lumen + +## 2.5.0 - 2017-10-03 + +## Changed + +- Making the path to migrations for `loadMigrationsFrom()` call dynamic based of configuration +- Making the factory path dynamic for master service provider & make-factory command +- Make the route file location dynamic in start.php based of `stubs.files.routes` +- Making the route path dynamic on the route service provider based of `stubs.files.routes` +- New structure in configuration to set which folders will be generated on `module:make` (old format still supported) +- Setting new sensible defaults to what folders to generate by default. +- Change the assets directory default location `resources/assets` + +## 2.4.1 - 2017-09-27 + +## Changed + +- Setting a default value for `modules.paths.modules` configuration key + + +## 2.4.0 - 2017-09-27 + +## Added + +- New `module:make-resource` command to generate resource classes +- New `module:make-test` command to generate test classes + +## Changed + +- Improved error output of the `module:seed` command +- Marking methods that served as proxies in `Module` and `Repository` classes as deprecated for next major +- Fixed `module:make` and `module:make-provider` to generate the correct master service provider +- Tests: tests are now using `spatie/phpunit-snapshot-assertions` to make sure the generated files have the correct content +- Adding a sync option to the `module:make-job` command to make a synchronous job class +- Changed `module:make-event` command to allow duck typed events (not type hinted event class) +- Changed `module:make-listener` to allow a `--queued` option to make the event queueable +- Changed `module:make-listener` command to not use the full class typehint when class was previous imported + +## 2.3.0 - 2017-09-26 + +## Added + +- Ability to ignore some folders to generate +- Creating an module:unuse command to forget the previously saved module +- New command to generate Policy classes +- New command for creating factories +- New command for creating rules +- new `public_path` helper for Lumen + +## Changed + +- Refactored class names that generate something to be fully consistent + +## 2.2.1 - 2017-09-14 + +## Changed + +- Fixed class namespace to `Repository` in `ContractsServiceProvider` + +## 2.2.0 - 2017-09-14 + +### Added + +- Lumen compatibility with new way to register providers + + +## 2.1.0 - 2017-09-10 + +### Changed + +- Register module migrations +- Fixed issue with `module:migrate-refresh` command +- Improved module loading of their service providers. Using laravel caching system. Allowing usage of deferred providers. +- Fixed path to module factories + +## 2.0.0 - 2017-08-31 + +### Added + +- Support Laravel 5.5 + + +## 1.27.2 - 2017-08-29 + +### Changed + +- Allow migrate-refresh command to be run without module argument +- Module name was added to the module enable and disable events + +## 1.27.1 - 2017-07-31 + +### Changed + +- Only run composer require on the module:update command if there's something to require +- Fixing lumen support + +## 1.27.0 - 2017-07-19 + +### Added + +- Laravel Lumen support + +### Changed + +- Update dev dependencies grumphp and phpcsfixer to latest versions +- The `make:model` command with the `-m` flag to create the associated migration is now using a current migration file name + +## 1.26.0 - 2017-07-06 + +### Changed + +- Throw an exception if asset name structure was not correct when using `{!! Module::asset() !!}` +- Create the module used file if non existent. Will provide for a better error message if module is omitted in console commands without a module:use. + +## 1.25.1 - 2017-06-29 + +### Changed + +- More flexibility to the `json()` method, while keeping the performance improvements. + +## 1.25.0 - 2017-06-29 + +### Changed + +- Improving performance by only instantiating Json class for the module.json file once +- Added support for generic git hosts + +## 1.24.0 - 2017-06-12 + +### Changed + +- Using `resource_path` to register module views +- Changed the method to load additional eloquent factory paths + +## 1.23.0 - 2017-06-09 + +## Added + +- A `--migration` flag to the `module:make-model` command to generate the migration file with a model +- Factories are now also defined in the master service providers. This is used in the `module:make` command without the `--plain` flag, or using `module:make-provider` with the `--master` flag. +- `module_path()` helper function. + +### Changed + +- The default location of event listeners is now in `Listeners/`, from `Events/Handlers` + +## 1.22.0 - 2017-05-22 + +### Changed + +- Fixed the `--plain` on the `make:module` command, to not include a service provider in the `module.json` file as it's not generated. +- Add command description to the `GenerateNotificationCommand`. + +## 1.21.0 - 2017-05-10 + +### Added + +- Added the `Macroable` trait to the `Module` class. + +### Changed + +- The `collections` method now accepts an optional parameter to get modules by status, in a laravel collection. +- Allow laravel `5.5.*` to be used. + + +## 1.20.0 - 2017-04-19 + +### Changed + +- `module:update`: Copy over the scripts key to main composer.json file +- Add a `--subpath` option to migrate command +- `module:update`: Install / require all require & require-dev package at once, instead of multiple calls to composer require. +- `module:publish-config` command now uses the namespace set up in the configuration file. + +## 1.19.0 - 2017-03-16 + +### Changed + +- `module:update` command now also takes the `require-dev` key into account +- Making the `$migrations` parameter optional on `getLastBatchNumber()` + +## 1.18.0 - 2017-03-13 + +### Changed + +- The module list command (`module:list`) now returns the native module name + +## 1.17.1 - 2017-03-02 + +### Changed + +- Fixed issues with route file location in `start.php` + +## 1.17.0 - 2017-02-27 + +### Changed + +- Add checking for failure to parse module JSON + +## 1.16.0 - 2017-01-24 + +### Added + +- Support for Laravel 5.4 +- Adding show method on resource controller +- Added check for cached routes to not load them multiple times + +## 1.15.0 - 2017-01-12 + +### Added + +- Module requirements (PR #117) +- Added `Macroable` trait to `Module` class (PR #116) + +### Changed + +- Added missing import of the `Schema` facade on migration stubs +- A default plain migration will be used if the name was not matched against a predefined structure (create, add, delete and drop) +- Add tests for all the different migration structures above +- Fix: respecting order in reverse migrations (PR #98) +- Fix: `module:reset` and `module:migrate-rollback` didn't have `--database` option (PR #88) +- Fix: `Module::asset()`, removed obsolete backslash. (PR #91) + +## 1.14.0 - 2016-10-19 + +### Added + +- `module:make-notification` command to generate a notification class + +### Changed + +- Usage of the `lists()` method on the laravel collection has been removed in favor of `pluck()` +- Modules can now overwrite the default migration and seed paths in the `module.json` file + +## 0.13.1 - 2016-09-09 + +### Changed + +- Generated emails are now generated in the `Emails` folder by default + +## 0.13.0 - 2016-09-08 + +### Changed + +- Ability to set default value on the config() method of a module. +- Mail: Setting default value to config. Using that as the namespace. +- Using PSR2 for generated stubs + + +## 0.12.0 - 2016-09-08 + +### Added + +- Generation of Mailable classes + + +## 0.11.2 - 2016-08-29 + +### Changed + +- Using stable version of laravelcollective/html (5.3) + +## 0.11.1 - 2016-08-25 + +### Changed + +- Using stable development of laravelcollective/html + + +## 0.11 - 2016-08-24 + +### Added + +- Adding `module:make-job` command to generate a job class +- Adding support for Laravel 5.3 + +### Changed + +- Added force option to module:seed command + +## 0.10 - 2016-08-10 + +### Added + +- Experimental Laravel 5.3 support + +### Changed + +- Make sure the class name has `Controller` appended to it as well. Previously only the file had it suffixed. + +### Removed + +- Dependencies: `pingpong/support` and `pingpong/generators` + +## 0.9 - 2016-07-30 + +### Added + +- Adding a plain option to the generate controller command + +### Changed + +- Generate controller command now generates all resource methods + +## 0.8 - 2016-07-28 + +### Fixed + +- Module generation namespace now works with `StudlyCase` ([Issue #14](https://github.com/nWidart/laravel-modules/issues/14)) +- No module namespace fix (#13) + +### Changed + +- Using new service provider stub for module generation too + +## 0.1 - 2016-06-27 + +Initial release diff --git a/LICENSE.md b/LICENSE.md new file mode 100755 index 0000000..9ef8f84 --- /dev/null +++ b/LICENSE.md @@ -0,0 +1,23 @@ +# The MIT License (MIT) + +Copyright (c) 2014 Pingpong Labs + +Copyright (c) 2026 Mark Gregory + +> Permission is hereby granted, free of charge, to any person obtaining a copy +> of this software and associated documentation files (the "Software"), to deal +> in the Software without restriction, including without limitation the rights +> to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +> copies of the Software, and to permit persons to whom the Software is +> furnished to do so, subject to the following conditions: +> +> The above copyright notice and this permission notice shall be included in +> all copies or substantial portions of the Software. +> +> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +> IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +> FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +> AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +> LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +> OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +> THE SOFTWARE. diff --git a/README.md b/README.md new file mode 100755 index 0000000..74d3d67 --- /dev/null +++ b/README.md @@ -0,0 +1,83 @@ +# Laravel-Modules + +[![Latest Version on Packagist](https://img.shields.io/packagist/v/nwidart/laravel-modules.svg?style=flat-square)](https://packagist.org/packages/nwidart/laravel-modules) +[![Software License](https://img.shields.io/badge/license-MIT-brightgreen.svg?style=flat-square)](LICENSE.md) +[![Build Status](https://img.shields.io/travis/nWidart/laravel-modules/master.svg?style=flat-square)](https://travis-ci.org/nWidart/laravel-modules) +[![Scrutinizer Coverage](https://img.shields.io/scrutinizer/coverage/g/nWidart/laravel-modules.svg?maxAge=86400&style=flat-square)](https://scrutinizer-ci.com/g/nWidart/laravel-modules/?branch=master) +[![Quality Score](https://img.shields.io/scrutinizer/g/nWidart/laravel-modules.svg?style=flat-square)](https://scrutinizer-ci.com/g/nWidart/laravel-modules) +[![Total Downloads](https://img.shields.io/packagist/dt/nwidart/laravel-modules.svg?style=flat-square)](https://packagist.org/packages/nwidart/laravel-modules) + +| **Laravel** | **laravel-modules** | +|-------------|---------------------| +| 5.4 | ^1.0 | +| 5.5 | ^2.0 | +| 5.6 | ^3.0 | +| 5.7 | ^4.0 | +| 5.8 | ^5.0 | +| 6.0 | ^6.0 | +| 7.0 | ^7.0 | +| 9.0 | ^9.0 | +| 10.0 | ^10.0 | +| 11.0 | ^11.0 | +| 12.0 | ^12.0 | +| 12.0 | ^13.0 | + +`mpba/laravel-modules` is a Laravel package which created to manage your large Laravel app using modules. Module is like a Laravel package, it has some views, controllers or models. This package is supported and tested in Laravel 8. + +This package is a re-published, re-organised and maintained version of [pingpong/modules](https://github.com/pingpong-labs/modules), which isn't maintained anymore. This package is used in [AsgardCMS](https://asgardcms.com/). + +With one big added bonus that the original package didn't have: **tests**. + +Find out why you should use this package in the article: [Writing modular applications with laravel-modules](https://nicolaswidart.com/blog/writing-modular-applications-with-laravel-modules). + +## Install + +To install through Composer, by run the following command: + +``` bash +composer require mpba/laravel-modules +``` + +The package will automatically register a service provider and alias. + +Optionally, publish the package's configuration file by running: + +``` bash +php artisan vendor:publish --provider="mpba\Modules\LaravelModulesServiceProvider" +``` + +### Autoloading + +By default, the module classes are not loaded automatically. You can autoload your modules using `psr-4`. For example: + +``` json +{ + "autoload": { + "psr-4": { + "App\\": "app/", + "Modules\\": "Modules/" + } + } +} +``` + +**Tip: don't forget to run `composer dump-autoload` afterwards.** + +## Documentation + + + +## Credits + +- [Nicolas Widart](https://github.com/nwidart) +- [gravitano](https://github.com/gravitano) +- [All Contributors](../../contributors) + +## About Nicolas Widart + +Nicolas Widart is a freelance web developer specialising on the Laravel framework. View all my packages [on my website](https://nwidart.com/), or visit [my website](https://nicolaswidart.com). + + +## License + +The MIT License (MIT). Please see [License File](LICENSE.md) for more information. diff --git a/composer.json b/composer.json new file mode 100755 index 0000000..54676b8 --- /dev/null +++ b/composer.json @@ -0,0 +1,69 @@ +{ + "name": "mpba/laravel-modules", + "description": "Laravel Module management", + "version":"13.0.0", + "keywords": [ + "modules", + "laravel", + "mpba", + "module", + "rad" + ], + "license": "MIT", + "authors": [ + { + "name": "Mark Gregory", + "email": "mark.gregory@mpba.co.uk", + "homepage": "https://mpba.co.uk", + "role": "Developer" + } + ], + "require": { + "php": ">=7.3", + "ext-json": "*" + }, + "require-dev": { + "phpunit/phpunit": "^8.5", + "mockery/mockery": "~1.0", + "orchestra/testbench": "^6.0", + "friendsofphp/php-cs-fixer": "^2.16", + "laravel/framework": "^8.0", + "spatie/phpunit-snapshot-assertions": "^2.1.0", + "phpstan/phpstan": "^0.12.14" + }, + "autoload": { + "psr-4": { + "mpba\\Modules\\": "src" + }, + "files": [ + "src/helpers.php" + ] + }, + "autoload-dev": { + "psr-4": { + "mpba\\Modules\\Tests\\": "tests", + "Modules\\Recipe\\": "tests/stubs/valid/Recipe" + } + }, + "extra": { + "laravel": { + "providers": [ + "mpba\\Modules\\LaravelModulesServiceProvider" + ], + "aliases": { + "Module": "mpba\\Modules\\Facades\\Module" + } + }, + "branch-alias": { + "dev-master": "8.0-dev" + } + }, + "scripts": { + "update-snapshots": "./vendor/bin/phpunit --no-coverage -d --update-snapshots", + "test": "vendor/bin/phpunit", + "test-coverage": "vendor/bin/phpunit --debug --coverage-html coverage", + "pcf": "vendor/bin/php-cs-fixer fix --verbose" + }, + "minimum-stability": "dev", + "prefer-stable": false +} diff --git a/config/config.php b/config/config.php new file mode 100755 index 0000000..94aa5ff --- /dev/null +++ b/config/config.php @@ -0,0 +1,222 @@ + 'Modules', + + /* + |-------------------------------------------------------------------------- + | Module Stubs + |-------------------------------------------------------------------------- + | + | Default module stubs. + | + */ + + 'stubs' => [ + 'enabled' => false, + 'path' => base_path() . '/Vendors/mpba/laravel-modules/src/Commands/stubs', + 'files' => [ + 'routes/web' => 'Routes/web.php', + 'routes/api' => 'Routes/api.php', + 'views/index' => 'Resources/views/index.blade.php', + 'views/master' => 'Resources/views/layouts/master.blade.php', + 'scaffold/config' => 'Config/config.php', + 'composer' => 'composer.json', + 'assets/js/app' => 'Resources/assets/js/app.js', + 'assets/sass/app' => 'Resources/assets/sass/app.scss', + 'webpack' => 'webpack.mix.js', + 'package' => 'package.json', + ], + 'replacements' => [ + 'routes/web' => ['LOWER_NAME', 'STUDLY_NAME'], + 'routes/api' => ['LOWER_NAME'], + 'webpack' => ['LOWER_NAME'], + 'json' => ['LOWER_NAME', 'STUDLY_NAME', 'MODULE_NAMESPACE', 'PROVIDER_NAMESPACE'], + 'views/index' => ['LOWER_NAME'], + 'views/master' => ['LOWER_NAME', 'STUDLY_NAME'], + 'scaffold/config' => ['STUDLY_NAME'], + 'composer' => [ + 'LOWER_NAME', + 'STUDLY_NAME', + 'VENDOR', + 'AUTHOR_NAME', + 'AUTHOR_EMAIL', + 'MODULE_NAMESPACE', + 'PROVIDER_NAMESPACE', + ], + ], + 'gitkeep' => true, + ], + 'paths' => [ + /* + |-------------------------------------------------------------------------- + | Modules path + |-------------------------------------------------------------------------- + | + | This path used for save the generated module. This path also will be added + | automatically to list of scanned folders. + | + */ + + 'modules' => base_path('modules'), + /* + |-------------------------------------------------------------------------- + | Modules assets path + |-------------------------------------------------------------------------- + | + | Here you may update the modules assets path. + | + */ + + 'assets' => public_path('modules'), + /* + |-------------------------------------------------------------------------- + | The migrations path + |-------------------------------------------------------------------------- + | + | Where you run 'module:publish-migration' command, where do you publish the + | the migration files? + | + */ + + 'migration' => base_path('database/migrations'), + /* + |-------------------------------------------------------------------------- + | Generator path + |-------------------------------------------------------------------------- + | Customise the paths where the folders will be generated. + | Set the generate key to false to not generate that folder + */ + 'generator' => [ + 'config' => ['path' => 'Config', 'generate' => true], + 'trait' => ['path' => 'Traits', 'generate' => true], + 'helper' => ['path' => 'Helpers', 'generate' => true], + 'command' => ['path' => 'Console', 'generate' => true], + 'support' => ['path' => 'Support', 'generate' => true], + 'migration' => ['path' => 'Database/Migrations', 'generate' => true], + 'seeder' => ['path' => 'Database/Seeders', 'generate' => true], + 'factory' => ['path' => 'Database/factories', 'generate' => true], + 'model' => ['path' => 'Models', 'generate' => true], + 'routes' => ['path' => 'Routes', 'generate' => true], + 'controller' => ['path' => 'Http/Controllers', 'generate' => true], + 'filter' => ['path' => 'Http/Middleware', 'generate' => true], + 'request' => ['path' => 'Http/Requests', 'generate' => true], + 'provider' => ['path' => 'Providers', 'generate' => true], + 'assets' => ['path' => 'Resources/assets', 'generate' => true], + 'lang' => ['path' => 'Resources/lang', 'generate' => true], + 'views' => ['path' => 'Resources/views', 'generate' => true], + 'test' => ['path' => 'Tests/Unit', 'generate' => true], + 'test-feature' => ['path' => 'Tests/Feature', 'generate' => true], + 'repository' => ['path' => 'Repositories', 'generate' => false], + 'event' => ['path' => 'Events', 'generate' => false], + 'listener' => ['path' => 'Listeners', 'generate' => false], + 'policies' => ['path' => 'Policies', 'generate' => false], + 'rules' => ['path' => 'Rules', 'generate' => false], + 'jobs' => ['path' => 'Jobs', 'generate' => false], + 'emails' => ['path' => 'Emails', 'generate' => false], + 'notifications' => ['path' => 'Notifications', 'generate' => false], + 'resource' => ['path' => 'Transformers', 'generate' => false], + 'component' => ['path' => 'View', 'generate' => true], + ], + ], + /* + |-------------------------------------------------------------------------- + | Scan Path + |-------------------------------------------------------------------------- + | + | Here you define which folder will be scanned. By default will scan Vendors + | directory. This is useful if you host the package in packagist website. + | + */ + + 'scan' => [ + 'enabled' => false, + 'paths' => [ + base_path('Vendors/*/*'), + ], + ], + /* + |-------------------------------------------------------------------------- + | Composer File Template + |-------------------------------------------------------------------------- + | + | Here is the config for composer.json file, generated by this package + | + */ + + 'composer' => [ + 'Vendors' => 'mpba', + 'author' => [ + 'name' => 'Mark Gregory', + 'email' => 'mark.gregory@mpba.co.uk', + ], + ], + /* + |-------------------------------------------------------------------------- + | Caching + |-------------------------------------------------------------------------- + | + | Here is the config for setting up caching feature. + | + */ + 'cache' => [ + 'enabled' => false, + 'key' => 'laravel-modules', + 'lifetime' => 60, + ], + /* + |-------------------------------------------------------------------------- + | Choose what laravel-modules will register as custom namespaces. + | Setting one to false will require you to register that part + | in your own Service Provider class. + |-------------------------------------------------------------------------- + */ + 'register' => [ + 'translations' => true, + /** + * load files on boot or register method + * + * @example boot|register + */ + 'files' => 'register', + ], + + /* + |-------------------------------------------------------------------------- + | Activators + |-------------------------------------------------------------------------- + | + | You can define new types of activators here, file, database etc. The only + | required parameter is 'class'. + | The file activator will store the activation status in storage/installed_modules + */ + 'activators' => [ + 'file' => [ + 'class' => FileActivator::class, + 'statuses-file' => base_path('modules_statuses.json'), + 'cache-key' => 'activator.installed', + 'cache-lifetime' => 604800, + ], + 'database' => [ + 'class' => DatabaseActivator::class, + 'cache-key' => 'activator.installed', + 'cache-lifetime' => 604800, + ], + ], + + 'activator' => 'file', +]; diff --git a/src/.DS_Store b/src/.DS_Store new file mode 100644 index 0000000..f81b3bc Binary files /dev/null and b/src/.DS_Store differ diff --git a/src/Activators/DatabaseActivator.php b/src/Activators/DatabaseActivator.php new file mode 100644 index 0000000..b118557 --- /dev/null +++ b/src/Activators/DatabaseActivator.php @@ -0,0 +1,63 @@ +setActive($module, true); + } + + public function disable(Module $module): void + { + $this->setActive($module, false); + } + + public function hasStatus(Module $module, bool $status): bool + { + return $this->getStatus($module, ! $status) === $status; + } + + public function setActive(Module $module, bool $active): void + { + $this->setActiveByName($module->getName(), $active); + } + + public function setActiveByName(string $name, bool $active): void + { + DB::table('module_statuses')->updateOrInsert( + ['module' => $name], + ['enabled' => $active] + ); + } + + public function delete(Module $module): void + { + DB::table('module_statuses') + ->where('module', $module->getName()) + ->delete(); + } + + public function reset(): void + { + DB::table('module_statuses')->truncate(); + } + + protected function getStatus(Module $module, bool $default = false): bool + { + $row = DB::table('module_statuses') + ->where('module', $module->getName()) + ->first(); + + if ($row === null) { + return $default; + } + + return (bool) $row->enabled; + } +} diff --git a/src/Activators/FileActivator.php b/src/Activators/FileActivator.php new file mode 100755 index 0000000..240dbd9 --- /dev/null +++ b/src/Activators/FileActivator.php @@ -0,0 +1,206 @@ +cache = $app['cache']; + $this->files = $app['files']; + $this->config = $app['config']; + $this->statusesFile = $this->config('statuses-file'); + $this->cacheKey = $this->config('cache-key'); + $this->cacheLifetime = $this->config('cache-lifetime'); + $this->modulesStatuses = $this->getModulesStatuses(); + } + + /** + * Get the path of the file where statuses are stored + */ + public function getStatusesFilePath(): string + { + return $this->statusesFile; + } + + /** + * {@inheritDoc} + */ + public function reset(): void + { + if ($this->files->exists($this->statusesFile)) { + $this->files->delete($this->statusesFile); + } + $this->modulesStatuses = []; + $this->flushCache(); + } + + /** + * {@inheritDoc} + */ + public function enable(Module $module): void + { + $this->setActiveByName($module->getName(), true); + } + + /** + * {@inheritDoc} + */ + public function disable(Module $module): void + { + $this->setActiveByName($module->getName(), false); + } + + /** + * {@inheritDoc} + */ + public function hasStatus(Module $module, bool $status): bool + { + if (! isset($this->modulesStatuses[$module->getName()])) { + return $status === false; + } + + return $this->modulesStatuses[$module->getName()] === $status; + } + + /** + * {@inheritDoc} + */ + public function setActive(Module $module, bool $active): void + { + $this->setActiveByName($module->getName(), $active); + } + + /** + * {@inheritDoc} + */ + public function setActiveByName(string $name, bool $status): void + { + $this->modulesStatuses[$name] = $status; + $this->writeJson(); + $this->flushCache(); + } + + /** + * {@inheritDoc} + */ + public function delete(Module $module): void + { + if (! isset($this->modulesStatuses[$module->getName()])) { + return; + } + unset($this->modulesStatuses[$module->getName()]); + $this->writeJson(); + $this->flushCache(); + } + + /** + * Writes the activation statuses in a file, as json + */ + private function writeJson(): void + { + $this->files->put($this->statusesFile, json_encode($this->modulesStatuses, JSON_PRETTY_PRINT)); + } + + /** + * Reads the json file that contains the activation statuses. + * + * @throws FileNotFoundException + */ + private function readJson(): array + { + if (! $this->files->exists($this->statusesFile)) { + return []; + } + + return json_decode($this->files->get($this->statusesFile), true); + } + + /** + * Get modules statuses, either from the cache or from + * the json statuses file if the cache is disabled. + * + * @throws FileNotFoundException + */ + private function getModulesStatuses(): array + { + if (! $this->config->get('modules.cache.enabled')) { + return $this->readJson(); + } + + return $this->cache->remember($this->cacheKey, $this->cacheLifetime, function () { + return $this->readJson(); + }); + } + + /** + * Reads a config parameter under the 'activators.file' key + * + * @return mixed + */ + private function config(string $key, $default = null) + { + return $this->config->get('modules.activators.file.'.$key, $default); + } + + /** + * Flushes the modules activation statuses cache + */ + private function flushCache(): void + { + $this->cache->forget($this->cacheKey); + } +} diff --git a/src/Collection.php b/src/Collection.php new file mode 100755 index 0000000..7877337 --- /dev/null +++ b/src/Collection.php @@ -0,0 +1,38 @@ +items; + } + + /** + * Get the collection of items as a plain array. + * + * @return array + */ + public function toArray() + { + return array_map(function ($value) { + if ($value instanceof Module) { + $attributes = $value->json()->getAttributes(); + $attributes['path'] = $value->getPath(); + + return $attributes; + } + + return $value instanceof Arrayable ? $value->toArray() : $value; + }, $this->items); + } +} diff --git a/src/Commands/CommandMakeCommand.php b/src/Commands/CommandMakeCommand.php new file mode 100755 index 0000000..e44cb47 --- /dev/null +++ b/src/Commands/CommandMakeCommand.php @@ -0,0 +1,110 @@ +laravel['modules']; + + return $module->config('paths.generator.command.namespace') ?: $module->config('paths.generator.command.path', 'Console'); + } + + /** + * Get the console command arguments. + * + * @return array + */ + protected function getArguments() + { + return [ + ['name', InputArgument::REQUIRED, 'The name of the command.'], + ['module', InputArgument::OPTIONAL, 'The name of module will be used.'], + ]; + } + + /** + * Get the console command options. + * + * @return array + */ + protected function getOptions() + { + return [ + ['command', null, InputOption::VALUE_OPTIONAL, 'The terminal command that should be assigned.', null], + ]; + } + + /** + * @return mixed + */ + protected function getTemplateContents() + { + $module = $this->laravel['modules']->findOrFail($this->getModuleName()); + + return (new Stub('/command.stub', [ + 'COMMAND_NAME' => $this->getCommandName(), + 'NAMESPACE' => $this->getClassNamespace($module), + 'CLASS' => $this->getClass(), + ]))->render(); + } + + /** + * @return string + */ + private function getCommandName() + { + return $this->option('command') ?: 'command:name'; + } + + /** + * @return mixed + */ + protected function getDestinationFilePath() + { + $path = $this->laravel['modules']->getModulePath($this->getModuleName()); + + $commandPath = GenerateConfigReader::read('command'); + + return $path.$commandPath->getPath().'/'.$this->getFileName().'.php'; + } + + /** + * @return string + */ + private function getFileName() + { + return Str::studly($this->argument('name')); + } +} diff --git a/src/Commands/ComponentMakeCommand.php b/src/Commands/ComponentMakeCommand.php new file mode 100755 index 0000000..ba5abf5 --- /dev/null +++ b/src/Commands/ComponentMakeCommand.php @@ -0,0 +1,260 @@ +files = $files; + } + + /** + * Get the default namespace for the component + */ + public function getDefaultNamespace(): string + { + $module = $this->laravel['modules']; + + return $module->config('paths.generator.component.namespace') ?: $module->config('paths.generator.component.path', 'Component'); + } + + /** + * Recover the arguments + * + * @return array[] + */ + protected function getArguments(): array + { + return [ + ['component', InputArgument::REQUIRED, 'The name of the component class.'], + ['module', InputArgument::OPTIONAL, 'The name of module will be used.'], + ]; + } + + /** + * Recover the options + * + * @return array[] + */ + protected function getOptions(): array + { + return [ + ['component', null, InputOption::VALUE_OPTIONAL, 'The name of the component', null], + ]; + } + + /** + * returns the proper case and separated name + */ + public function to_snake_case(string $input): string + { + return strtolower(preg_replace('/(?createViewFile(); + $this->registerComponentNamespaceInServiceProvider(); + + return true; + } + + /** + * Recover the stub and provide the required replacements + */ + protected function getTemplateContents(): string + { + $module = $this->laravel['modules']->findOrFail($this->getModuleName()); + + return (new Stub($this->getStubName(), [ + 'MODULE' => $this->getModuleName(), + 'NAMESPACE' => $module->getStudlyName(), + 'CLASS_NAMESPACE' => $this->getClassNamespace($module), + 'CLASS' => $this->getControllerNameWithoutNamespace(), + 'VIEW_NAME' => $this->to_snake_case($this->getControllerNameWithoutNamespace()), + ]))->render(); + } + + /** + * Generate the view name as componentName.blade.php + */ + protected function getComponentView(): string + { + $base = Str::kebab($this->argument('component')); + + // Strip "-component" if the user supplied "SomethingComponent" + return 'components/'.Str::of($base)->replace('-component', '').'.blade.php'; + } + + /** + * Creates the required view file + */ + protected function createViewFile(): void + { + $viewPath = module_path($this->getModuleName()).'/Resources/views'; + $viewFile = $viewPath.'/'.$this->getComponentView(); + + if (! $this->files->exists(dirname($viewFile))) { + $this->files->makeDirectory(dirname($viewFile), 0755, true); + } + + if (! $this->files->exists($viewFile)) { + $stub = new Stub($this->getStubName(true), [ + 'COMPONENT' => $this->argument('component'), + 'MODULE' => $this->getModuleName(), + 'CLASS' => $this->getControllerNameWithoutNamespace(), + ]); + $this->files->put($viewFile, $stub->render()); + $this->info("View created: {$viewFile}"); + } else { + $this->warn("View already exists: {$viewFile}"); + } + } + + /** + * Recover the real controller name without the namespace + */ + private function getControllerNameWithoutNamespace(): array|string + { + return class_basename($this->getControllerName()); + } + + /** + * Return the controller name to be used + */ + protected function getControllerName(): array|string + { + $controller = Str::studly($this->argument('component')); + + if (Str::contains(strtolower($controller), 'component') === false) { + $controller .= 'Component'; + } + + return $controller; + } + + /** + * Get the component name from the provided arguments + */ + protected function getComponentName(): array|string + { + $component = Str::studly($this->argument('component')); + if (Str::contains(strtolower($component), 'component') === false) { + $component .= 'Component'; + } + + return $component; + } + + /** + * Get the destination path from the entry in modules.config + */ + protected function getDestinationFilePath(): string + { + + $path = $this->laravel['modules']->getModulePath($this->getModuleName()); + $helperPath = GenerateConfigReader::read('component'); + + return $path.$helperPath->getPath().'/'.$this->getComponentName().'.php'; + } + + /** + * Set the view name + */ + protected function getFileName(): string + { + return 'view'; + } + + /** + * Sets the view or controller stub based on a flag + */ + protected function getStubName($view = false): string + { + if ($view) { + return '/component/view.stub'; + } + + return '/component/controller.stub'; + } + + /** + * Recover the module name from the provided arguments + */ + protected function getModuleName(): string + { + return $this->argument('module'); + } + + /** + * Adds the required use statement(s) and also the Blade definition to the + * modules service provider. + * + * @throws FileNotFoundException + */ + protected function registerComponentNamespaceInServiceProvider(): void + { + $moduleName = $this->getModuleName(); + $namespace = "Modules\\$moduleName\\View\\Components"; + $alias = 'components'; + + $providerPath = module_path($moduleName)."/Providers/{$moduleName}ServiceProvider.php"; + + if (! $this->files->exists($providerPath)) { + $this->warn("Service provider not found: $providerPath"); + + return; + } + + $contents = $this->files->get($providerPath); + $registration = "Blade::componentNamespace('{$namespace}', '{$alias}');"; + $import = 'use Illuminate\\Support\\Facades\\Blade;'; + + // Insert 'use Blade' after the last existing use statements + if (! Str::contains($contents, $import)) { + $contents = preg_replace_callback( + '/^(use .+?;\n)+/m', + function ($matches) use ($import) { + return $matches[0].$import."\n"; + }, + $contents, + 1 + ); + $this->info('Added Blade import to ServiceProvider.'); + } + + // Add registration if not already present in the service provider + if (! Str::contains($contents, $registration)) { + $contents = preg_replace_callback( + '/public function boot\(\): void\s*\{/', + fn ($matches) => $matches[0]."\n {$registration}", + $contents + ); + $this->files->put($providerPath, $contents); + $this->info("Registered Blade component namespace in {$moduleName} ServiceProvider."); + } + + } +} diff --git a/src/Commands/ControllerMakeCommand.php b/src/Commands/ControllerMakeCommand.php new file mode 100755 index 0000000..13253f6 --- /dev/null +++ b/src/Commands/ControllerMakeCommand.php @@ -0,0 +1,142 @@ +laravel['modules']->getModulePath($this->getModuleName()); + + $controllerPath = GenerateConfigReader::read('controller'); + + return $path.$controllerPath->getPath().'/'.$this->getControllerName().'.php'; + } + + /** + * @return string + */ + protected function getTemplateContents() + { + $module = $this->laravel['modules']->findOrFail($this->getModuleName()); + + return (new Stub($this->getStubName(), [ + 'MODULENAME' => $module->getStudlyName(), + 'CONTROLLERNAME' => $this->getControllerName(), + 'NAMESPACE' => $module->getStudlyName(), + 'CLASS_NAMESPACE' => $this->getClassNamespace($module), + 'CLASS' => $this->getControllerNameWithoutNamespace(), + 'LOWER_NAME' => $module->getLowerName(), + 'MODULE' => $this->getModuleName(), + 'NAME' => $this->getModuleName(), + 'STUDLY_NAME' => $module->getStudlyName(), + 'MODULE_NAMESPACE' => $this->laravel['modules']->config('namespace'), + ]))->render(); + } + + /** + * Get the console command arguments. + * + * @return array + */ + protected function getArguments() + { + return [ + ['controller', InputArgument::REQUIRED, 'The name of the controller class.'], + ['module', InputArgument::OPTIONAL, 'The name of module will be used.'], + ]; + } + + /** + * @return array + */ + protected function getOptions() + { + return [ + ['plain', 'p', InputOption::VALUE_NONE, 'Generate a plain controller', null], + ['api', null, InputOption::VALUE_NONE, 'Exclude the create and edit methods from the controller.'], + ]; + } + + /** + * @return array|string + */ + protected function getControllerName() + { + $controller = Str::studly($this->argument('controller')); + + if (Str::contains(strtolower($controller), 'controller') === false) { + $controller .= 'Controller'; + } + + return $controller; + } + + /** + * @return array|string + */ + private function getControllerNameWithoutNamespace() + { + return class_basename($this->getControllerName()); + } + + public function getDefaultNamespace(): string + { + $module = $this->laravel['modules']; + + return $module->config('paths.generator.controller.namespace') ?: $module->config('paths.generator.controller.path', 'Http/Controllers'); + } + + /** + * Get the stub file name based on the options + * + * @return string + */ + protected function getStubName() + { + if ($this->option('plain') === true) { + $stub = '/controller-plain.stub'; + } elseif ($this->option('api') === true) { + $stub = '/controller-api.stub'; + } else { + $stub = '/controller.stub'; + } + + return $stub; + } +} diff --git a/src/Commands/DisableCommand.php b/src/Commands/DisableCommand.php new file mode 100755 index 0000000..58de34f --- /dev/null +++ b/src/Commands/DisableCommand.php @@ -0,0 +1,83 @@ +argument('module') === null) { + $this->disableAll(); + } + + /** @var Module $module */ + $module = $this->laravel['modules']->findOrFail($this->argument('module')); + + if ($module->isEnabled()) { + $module->disable(); + + $this->info("Module [{$module}] disabled successful."); + } else { + $this->comment("Module [{$module}] has already disabled."); + } + + return 0; + } + + /** + * disableAll + * + * @return void + */ + public function disableAll() + { + /** @var Modules $modules */ + $modules = $this->laravel['modules']->all(); + + foreach ($modules as $module) { + if ($module->isEnabled()) { + $module->disable(); + + $this->info("Module [{$module}] disabled successful."); + } else { + $this->comment("Module [{$module}] has already disabled."); + } + } + } + + /** + * Get the console command arguments. + * + * @return array + */ + protected function getArguments() + { + return [ + ['module', InputArgument::OPTIONAL, 'Module name.'], + ]; + } +} diff --git a/src/Commands/DumpCommand.php b/src/Commands/DumpCommand.php new file mode 100755 index 0000000..d5914d8 --- /dev/null +++ b/src/Commands/DumpCommand.php @@ -0,0 +1,64 @@ +info('Generating optimized autoload modules.'); + + if ($module = $this->argument('module')) { + $this->dump($module); + } else { + foreach ($this->laravel['modules']->all() as $module) { + $this->dump($module->getStudlyName()); + } + } + + return 0; + } + + public function dump($module) + { + $module = $this->laravel['modules']->findOrFail($module); + + $this->line("Running for module: {$module}"); + + chdir($module->getPath()); + + passthru('composer dump -o -n -q'); + } + + /** + * Get the console command arguments. + * + * @return array + */ + protected function getArguments() + { + return [ + ['module', InputArgument::OPTIONAL, 'Module name.'], + ]; + } +} diff --git a/src/Commands/EnableCommand.php b/src/Commands/EnableCommand.php new file mode 100755 index 0000000..d5a6701 --- /dev/null +++ b/src/Commands/EnableCommand.php @@ -0,0 +1,85 @@ +argument('module') === null) { + $this->enableAll(); + + return 0; + } + + /** @var Module $module */ + $module = $this->laravel['modules']->findOrFail($this->argument('module')); + + if ($module->isDisabled()) { + $module->enable(); + + $this->info("Module [{$module}] enabled successful."); + } else { + $this->comment("Module [{$module}] has already enabled."); + } + + return 0; + } + + /** + * enableAll + * + * @return void + */ + public function enableAll() + { + /** @var Modules $modules */ + $modules = $this->laravel['modules']->all(); + + foreach ($modules as $module) { + if ($module->isDisabled()) { + $module->enable(); + + $this->info("Module [{$module}] enabled successful."); + } else { + $this->comment("Module [{$module}] has already enabled."); + } + } + } + + /** + * Get the console command arguments. + * + * @return array + */ + protected function getArguments() + { + return [ + ['module', InputArgument::OPTIONAL, 'Module name.'], + ]; + } +} diff --git a/src/Commands/EventMakeCommand.php b/src/Commands/EventMakeCommand.php new file mode 100755 index 0000000..41edabf --- /dev/null +++ b/src/Commands/EventMakeCommand.php @@ -0,0 +1,77 @@ +laravel['modules']->findOrFail($this->getModuleName()); + + return (new Stub('/event.stub', [ + 'NAMESPACE' => $this->getClassNamespace($module), + 'CLASS' => $this->getClass(), + ]))->render(); + } + + public function getDestinationFilePath() + { + $path = $this->laravel['modules']->getModulePath($this->getModuleName()); + + $eventPath = GenerateConfigReader::read('event'); + + return $path.$eventPath->getPath().'/'.$this->getFileName().'.php'; + } + + /** + * @return string + */ + protected function getFileName() + { + return Str::studly($this->argument('name')); + } + + public function getDefaultNamespace(): string + { + $module = $this->laravel['modules']; + + return $module->config('paths.generator.event.namespace') ?: $module->config('paths.generator.event.path', 'Events'); + } + + /** + * Get the console command arguments. + * + * @return array + */ + protected function getArguments() + { + return [ + ['name', InputArgument::REQUIRED, 'The name of the event.'], + ['module', InputArgument::OPTIONAL, 'The name of module will be used.'], + ]; + } +} diff --git a/src/Commands/FactoryMakeCommand.php b/src/Commands/FactoryMakeCommand.php new file mode 100755 index 0000000..b43f9b9 --- /dev/null +++ b/src/Commands/FactoryMakeCommand.php @@ -0,0 +1,76 @@ +render(); + } + + /** + * @return mixed + */ + protected function getDestinationFilePath() + { + $path = $this->laravel['modules']->getModulePath($this->getModuleName()); + + $factoryPath = GenerateConfigReader::read('factory'); + + return $path.$factoryPath->getPath().'/'.$this->getFileName(); + } + + /** + * @return string + */ + private function getFileName() + { + return Str::studly($this->argument('name')).'.php'; + } +} diff --git a/src/Commands/GeneratorCommand.php b/src/Commands/GeneratorCommand.php new file mode 100755 index 0000000..35c7a3a --- /dev/null +++ b/src/Commands/GeneratorCommand.php @@ -0,0 +1,101 @@ +getDestinationFilePath()); + + if (! $this->laravel['files']->isDirectory($dir = dirname($path))) { + $this->laravel['files']->makeDirectory($dir, 0777, true); + } + + $contents = $this->getTemplateContents(); + + try { + $overwriteFile = $this->hasOption('force') ? $this->option('force') : false; + (new FileGenerator($path, $contents))->withFileOverwrite($overwriteFile)->generate(); + + $this->info("Created : {$path}"); + } catch (FileAlreadyExistException $e) { + $this->error("File : {$path} already exists."); + + return E_ERROR; + } + + return 0; + } + + /** + * Get class name. + * + * @return string + */ + public function getClass() + { + return class_basename($this->argument($this->argumentName)); + } + + /** + * Get default namespace. + */ + public function getDefaultNamespace(): string + { + return ''; + } + + /** + * Get class namespace. + * + * @param \mpba\Modules\Module $module + * @return string + */ + public function getClassNamespace($module) + { + $extra = str_replace($this->getClass(), '', $this->argument($this->argumentName)); + + $extra = str_replace('/', '\\', $extra); + + $namespace = $this->laravel['modules']->config('namespace'); + + $namespace .= '\\'.$module->getStudlyName(); + + $namespace .= '\\'.$this->getDefaultNamespace(); + + $namespace .= '\\'.$extra; + + $namespace = str_replace('/', '\\', $namespace); + + return trim($namespace, '\\'); + } +} diff --git a/src/Commands/HelperMakeCommand.php b/src/Commands/HelperMakeCommand.php new file mode 100755 index 0000000..c9d8a6f --- /dev/null +++ b/src/Commands/HelperMakeCommand.php @@ -0,0 +1,90 @@ +laravel['modules']; + + return $module->config('paths.generator.helpers.namespace') ?: $module->config('paths.generator.helpers.path', 'Helpers'); + } + + protected function getArguments() + { + return [ + ['module', InputArgument::REQUIRED, 'The name of module.'], + ]; + } + + protected function getOptions() + { + return [ + ['helper', null, InputOption::VALUE_OPTIONAL, 'Unused for now.', null], + ]; + } + + protected function getTemplateContents() + { + + return (new Stub($this->getStubName(), [ + 'MODULE' => $this->getModuleName(), + 'MODULE_LOWER' => strtolower($this->getModuleName()), + ]))->render(); + + } + + /** + * @return array|string + */ + protected function getHelperName() + { + $helper = Str::studly($this->option('helper')); + + if (Str::contains(strtolower($helper), 'helper') === false) { + $helper .= 'Helper'; + } + + return $helper; + } + + protected function getDestinationFilePath() + { + + $path = $this->laravel['modules']->getModulePath($this->getModuleName()); + $helperPath = GenerateConfigReader::read('helper'); + + return $path.$helperPath->getPath().'/'.$this->getHelperName().'.php'; + } + + protected function getFileName() + { + return 'helper'; + } + + protected function getStubName() + { + return '/helper.stub'; + } + + protected function getModuleName(): string + { + return $this->argument('module'); + } +} diff --git a/src/Commands/InstallCommand.php b/src/Commands/InstallCommand.php new file mode 100755 index 0000000..5443265 --- /dev/null +++ b/src/Commands/InstallCommand.php @@ -0,0 +1,148 @@ +argument('name'))) { + return $this->installFromFile(); + } + + $this->install( + $this->argument('name'), + $this->argument('version'), + $this->option('type'), + $this->option('tree') + ); + + return 0; + } + + /** + * Install modules from modules.json file. + */ + protected function installFromFile(): int + { + if (!file_exists($path = base_path('modules.json'))) { + $this->error("File 'modules.json' does not exist in your project root."); + + return E_ERROR; + } + + $modules = Json::make($path); + + $dependencies = $modules->get('require', []); + + foreach ($dependencies as $module) { + $module = collect($module); + + $this->install( + $module->get('name'), + $module->get('version'), + $module->get('type') + ); + } + + return 0; + } + + /** + * Install the specified module. + * + * @param string $name + * @param string $version + * @param string $type + * @param bool $tree + */ + protected function install($name, $version = 'dev-master', $type = 'composer', $tree = false) + { + $installer = new Installer( + $name, + $version, + $type ?: $this->option('type'), + $tree ?: $this->option('tree') + ); + + $installer->setRepository($this->laravel['modules']); + + $installer->setConsole($this); + + if ($timeout = $this->option('timeout')) { + $installer->setTimeout($timeout); + } + + if ($path = $this->option('path')) { + $installer->setPath($path); + } + + $installer->run(); + + if (!$this->option('no-update')) { + $this->call('module:update', [ + 'module' => $installer->getModuleName(), + ]); + } + } + + /** + * Get the console command arguments. + * + * @return array + */ + protected function getArguments() + { + return [ + ['name', InputArgument::OPTIONAL, 'The name of module will be installed.'], + ['version', InputArgument::OPTIONAL, 'The version of module will be installed.'], + ]; + } + + /** + * Get the console command options. + * + * @return array + */ + protected function getOptions() + { + return [ + ['timeout', null, InputOption::VALUE_OPTIONAL, 'The process timeout.', null], + ['path', null, InputOption::VALUE_OPTIONAL, 'The installation path.', null], + ['type', null, InputOption::VALUE_OPTIONAL, 'The type of installation.', null], + ['tree', null, InputOption::VALUE_NONE, 'Install the module as a git subtree', null], + ['no-update', null, InputOption::VALUE_NONE, 'Disables the automatic update of the dependencies.', null], + ]; + } +} diff --git a/src/Commands/JobMakeCommand.php b/src/Commands/JobMakeCommand.php new file mode 100755 index 0000000..883455f --- /dev/null +++ b/src/Commands/JobMakeCommand.php @@ -0,0 +1,109 @@ +laravel['modules']; + + return $module->config('paths.generator.jobs.namespace') ?: $module->config('paths.generator.jobs.path', 'Jobs'); + } + + /** + * Get the console command arguments. + * + * @return array + */ + protected function getArguments() + { + return [ + ['name', InputArgument::REQUIRED, 'The name of the job.'], + ['module', InputArgument::OPTIONAL, 'The name of module will be used.'], + ]; + } + + /** + * Get the console command options. + * + * @return array + */ + protected function getOptions() + { + return [ + ['sync', null, InputOption::VALUE_NONE, 'Indicates that job should be synchronous.'], + ]; + } + + /** + * Get template contents. + * + * @return string + */ + protected function getTemplateContents() + { + $module = $this->laravel['modules']->findOrFail($this->getModuleName()); + + return (new Stub($this->getStubName(), [ + 'NAMESPACE' => $this->getClassNamespace($module), + 'CLASS' => $this->getClass(), + ]))->render(); + } + + /** + * Get the destination file path. + * + * @return string + */ + protected function getDestinationFilePath() + { + $path = $this->laravel['modules']->getModulePath($this->getModuleName()); + + $jobPath = GenerateConfigReader::read('jobs'); + + return $path.$jobPath->getPath().'/'.$this->getFileName().'.php'; + } + + /** + * @return string + */ + private function getFileName() + { + return Str::studly($this->argument('name')); + } + + protected function getStubName(): string + { + if ($this->option('sync')) { + return '/job.stub'; + } + + return '/job-queued.stub'; + } +} diff --git a/src/Commands/LaravelModulesV6Migrator.php b/src/Commands/LaravelModulesV6Migrator.php new file mode 100755 index 0000000..0a50215 --- /dev/null +++ b/src/Commands/LaravelModulesV6Migrator.php @@ -0,0 +1,40 @@ +laravel['modules']; + + $modules = $modules->all(); + /** @var Module $module */ + foreach ($modules as $module) { + if ($module->json()->get('active') === 1) { + $module->enable(); + $moduleStatuses[] = [$module->getName(), 'Enabled']; + } + if ($module->json()->get('active') === 0) { + $module->disable(); + $moduleStatuses[] = [$module->getName(), 'Disabled']; + } + } + $this->info('All modules have been migrated.'); + $this->table(['Module name', 'Status'], $moduleStatuses); + + return 0; + } +} diff --git a/src/Commands/ListCommand.php b/src/Commands/ListCommand.php new file mode 100755 index 0000000..5f36469 --- /dev/null +++ b/src/Commands/ListCommand.php @@ -0,0 +1,90 @@ +table(['Name', 'Status', 'Order', 'Path'], $this->getRows()); + + return 0; + } + + /** + * Get table rows. + * + * @return array + */ + public function getRows() + { + $rows = []; + + /** @var Module $module */ + foreach ($this->getModules() as $module) { + $rows[] = [ + $module->getName(), + $module->isEnabled() ? 'Enabled' : 'Disabled', + $module->get('order'), + $module->getPath(), + ]; + } + + return $rows; + } + + public function getModules() + { + switch ($this->option('only')) { + case 'enabled': + return $this->laravel['modules']->getByStatus(1); + break; + + case 'disabled': + return $this->laravel['modules']->getByStatus(0); + break; + + case 'ordered': + return $this->laravel['modules']->getOrdered($this->option('direction')); + break; + + default: + return $this->laravel['modules']->all(); + break; + } + } + + /** + * Get the console command options. + * + * @return array + */ + protected function getOptions() + { + return [ + ['only', 'o', InputOption::VALUE_OPTIONAL, 'Types of modules will be displayed.', null], + ['direction', 'd', InputOption::VALUE_OPTIONAL, 'The direction of ordering.', 'asc'], + ]; + } +} diff --git a/src/Commands/ListenerMakeCommand.php b/src/Commands/ListenerMakeCommand.php new file mode 100755 index 0000000..f88383b --- /dev/null +++ b/src/Commands/ListenerMakeCommand.php @@ -0,0 +1,126 @@ +laravel['modules']->findOrFail($this->getModuleName()); + + return (new Stub($this->getStubName(), [ + 'NAMESPACE' => $this->getClassNamespace($module), + 'EVENTNAME' => $this->getEventName($module), + 'SHORTEVENTNAME' => $this->getShortEventName(), + 'CLASS' => $this->getClass(), + ]))->render(); + } + + public function getDefaultNamespace(): string + { + $module = $this->laravel['modules']; + + return $module->config('paths.generator.listener.namespace') ?: $module->config('paths.generator.listener.path', 'Listeners'); + } + + protected function getEventName(Module $module) + { + $namespace = $this->laravel['modules']->config('namespace').'\\'.$module->getStudlyName(); + $eventPath = GenerateConfigReader::read('event'); + + $eventName = $namespace.'\\'.$eventPath->getPath().'\\'.$this->option('event'); + + return str_replace('/', '\\', $eventName); + } + + protected function getShortEventName() + { + return class_basename($this->option('event')); + } + + protected function getDestinationFilePath() + { + $path = $this->laravel['modules']->getModulePath($this->getModuleName()); + + $listenerPath = GenerateConfigReader::read('listener'); + + return $path.$listenerPath->getPath().'/'.$this->getFileName().'.php'; + } + + /** + * @return string + */ + protected function getFileName() + { + return Str::studly($this->argument('name')); + } + + protected function getStubName(): string + { + if ($this->option('queued')) { + if ($this->option('event')) { + return '/listener-queued.stub'; + } + + return '/listener-queued-duck.stub'; + } + + if ($this->option('event')) { + return '/listener.stub'; + } + + return '/listener-duck.stub'; + } +} diff --git a/src/Commands/MailMakeCommand.php b/src/Commands/MailMakeCommand.php new file mode 100755 index 0000000..31ddf71 --- /dev/null +++ b/src/Commands/MailMakeCommand.php @@ -0,0 +1,87 @@ +laravel['modules']; + + return $module->config('paths.generator.emails.namespace') ?: $module->config('paths.generator.emails.path', 'Emails'); + } + + /** + * Get the console command arguments. + * + * @return array + */ + protected function getArguments() + { + return [ + ['name', InputArgument::REQUIRED, 'The name of the mailable.'], + ['module', InputArgument::OPTIONAL, 'The name of module will be used.'], + ]; + } + + /** + * Get template contents. + * + * @return string + */ + protected function getTemplateContents() + { + $module = $this->laravel['modules']->findOrFail($this->getModuleName()); + + return (new Stub('/mail.stub', [ + 'NAMESPACE' => $this->getClassNamespace($module), + 'CLASS' => $this->getClass(), + ]))->render(); + } + + /** + * Get the destination file path. + * + * @return string + */ + protected function getDestinationFilePath() + { + $path = $this->laravel['modules']->getModulePath($this->getModuleName()); + + $mailPath = GenerateConfigReader::read('emails'); + + return $path.$mailPath->getPath().'/'.$this->getFileName().'.php'; + } + + /** + * @return string + */ + private function getFileName() + { + return Str::studly($this->argument('name')); + } +} diff --git a/src/Commands/MiddlewareMakeCommand.php b/src/Commands/MiddlewareMakeCommand.php new file mode 100755 index 0000000..9424882 --- /dev/null +++ b/src/Commands/MiddlewareMakeCommand.php @@ -0,0 +1,88 @@ +laravel['modules']; + + return $module->config('paths.generator.filter.namespace') ?: $module->config('paths.generator.filter.path', 'Http/Middleware'); + } + + /** + * Get the console command arguments. + * + * @return array + */ + protected function getArguments() + { + return [ + ['name', InputArgument::REQUIRED, 'The name of the command.'], + ['module', InputArgument::OPTIONAL, 'The name of module will be used.'], + ]; + } + + /** + * @return mixed + */ + protected function getTemplateContents() + { + $module = $this->laravel['modules']->findOrFail($this->getModuleName()); + + return (new Stub('/middleware.stub', [ + 'NAMESPACE' => $this->getClassNamespace($module), + 'CLASS' => $this->getClass(), + ]))->render(); + } + + /** + * @return mixed + */ + protected function getDestinationFilePath() + { + $path = $this->laravel['modules']->getModulePath($this->getModuleName()); + + $middlewarePath = GenerateConfigReader::read('filter'); + + return $path.$middlewarePath->getPath().'/'.$this->getFileName().'.php'; + } + + /** + * @return string + */ + private function getFileName() + { + return Str::studly($this->argument('name')); + } +} diff --git a/src/Commands/MigrateCommand.php b/src/Commands/MigrateCommand.php new file mode 100755 index 0000000..41c2a6e --- /dev/null +++ b/src/Commands/MigrateCommand.php @@ -0,0 +1,111 @@ +module = $this->laravel['modules']; + + $name = $this->argument('module'); + + if ($name) { + $module = $this->module->findOrFail($name); + + $this->migrate($module); + + return 0; + } + + foreach ($this->module->getOrdered($this->option('direction')) as $module) { + $this->line('Running for module: '.$module->getName().''); + + $this->migrate($module); + } + + return 0; + } + + /** + * Run the migration from the specified module. + */ + protected function migrate(Module $module) + { + $path = str_replace(base_path(), '', (new Migrator($module, $this->getLaravel()))->getPath()); + + if ($this->option('subpath')) { + $path = $path.'/'.$this->option('subpath'); + } + + $this->call('migrate', [ + '--path' => $path, + '--database' => $this->option('database'), + '--pretend' => $this->option('pretend'), + '--force' => $this->option('force'), + ]); + + if ($this->option('seed')) { + $this->call('module:seed', ['module' => $module->getName(), '--force' => $this->option('force')]); + } + } + + /** + * Get the console command arguments. + * + * @return array + */ + protected function getArguments() + { + return [ + ['module', InputArgument::OPTIONAL, 'The name of module will be used.'], + ]; + } + + /** + * Get the console command options. + * + * @return array + */ + protected function getOptions() + { + return [ + ['direction', 'd', InputOption::VALUE_OPTIONAL, 'The direction of ordering.', 'asc'], + ['database', null, InputOption::VALUE_OPTIONAL, 'The database connection to use.'], + ['pretend', null, InputOption::VALUE_NONE, 'Dump the SQL queries that would be run.'], + ['force', null, InputOption::VALUE_NONE, 'Force the operation to run when in production.'], + ['seed', null, InputOption::VALUE_NONE, 'Indicates if the seed task should be re-run.'], + ['subpath', null, InputOption::VALUE_OPTIONAL, 'Indicate a subpath to run your migrations from'], + ]; + } +} diff --git a/src/Commands/MigrateRefreshCommand.php b/src/Commands/MigrateRefreshCommand.php new file mode 100755 index 0000000..9336c9a --- /dev/null +++ b/src/Commands/MigrateRefreshCommand.php @@ -0,0 +1,100 @@ +argument('module'); + + if ($module && ! $this->getModuleName()) { + $this->error("Module [$module] does not exists."); + + return E_ERROR; + } + + $this->call('module:migrate-reset', [ + 'module' => $this->getModuleName(), + '--database' => $this->option('database'), + '--force' => $this->option('force'), + ]); + + $this->call('module:migrate', [ + 'module' => $this->getModuleName(), + '--database' => $this->option('database'), + '--force' => $this->option('force'), + ]); + + if ($this->option('seed')) { + $this->call('module:seed', [ + 'module' => $this->getModuleName(), + ]); + } + + return 0; + } + + /** + * Get the console command arguments. + * + * @return array + */ + protected function getArguments() + { + return [ + ['module', InputArgument::OPTIONAL, 'The name of module will be used.'], + ]; + } + + /** + * Get the console command options. + * + * @return array + */ + protected function getOptions() + { + return [ + ['database', null, InputOption::VALUE_OPTIONAL, 'The database connection to use.'], + ['force', null, InputOption::VALUE_NONE, 'Force the operation to run when in production.'], + ['seed', null, InputOption::VALUE_NONE, 'Indicates if the seed task should be re-run.'], + ]; + } + + public function getModuleName() + { + $module = $this->argument('module'); + + if (! $module) { + return null; + } + + $module = app('modules')->find($module); + + return $module ? $module->getStudlyName() : null; + } +} diff --git a/src/Commands/MigrateResetCommand.php b/src/Commands/MigrateResetCommand.php new file mode 100755 index 0000000..157c92d --- /dev/null +++ b/src/Commands/MigrateResetCommand.php @@ -0,0 +1,114 @@ +module = $this->laravel['modules']; + + $name = $this->argument('module'); + + if (! empty($name)) { + $this->reset($name); + + return 0; + } + + foreach ($this->module->getOrdered($this->option('direction')) as $module) { + $this->line('Running for module: '.$module->getName().''); + + $this->reset($module); + } + + return 0; + } + + /** + * Rollback migration from the specified module. + */ + public function reset($module) + { + if (is_string($module)) { + $module = $this->module->findOrFail($module); + } + + $migrator = new Migrator($module, $this->getLaravel()); + + $database = $this->option('database'); + + if (! empty($database)) { + $migrator->setDatabase($database); + } + + $migrated = $migrator->reset(); + + if (count($migrated)) { + foreach ($migrated as $migration) { + $this->line("Rollback: {$migration}"); + } + + return; + } + + $this->comment('Nothing to rollback.'); + } + + /** + * Get the console command arguments. + * + * @return array + */ + protected function getArguments() + { + return [ + ['module', InputArgument::OPTIONAL, 'The name of module will be used.'], + ]; + } + + /** + * Get the console command options. + * + * @return array + */ + protected function getOptions() + { + return [ + ['direction', 'd', InputOption::VALUE_OPTIONAL, 'The direction of ordering.', 'desc'], + ['database', null, InputOption::VALUE_OPTIONAL, 'The database connection to use.'], + ['force', null, InputOption::VALUE_NONE, 'Force the operation to run when in production.'], + ['pretend', null, InputOption::VALUE_NONE, 'Dump the SQL queries that would be run.'], + ]; + } +} diff --git a/src/Commands/MigrateRollbackCommand.php b/src/Commands/MigrateRollbackCommand.php new file mode 100755 index 0000000..c9cbdbb --- /dev/null +++ b/src/Commands/MigrateRollbackCommand.php @@ -0,0 +1,114 @@ +module = $this->laravel['modules']; + + $name = $this->argument('module'); + + if (! empty($name)) { + $this->rollback($name); + + return 0; + } + + foreach ($this->module->getOrdered($this->option('direction')) as $module) { + $this->line('Running for module: '.$module->getName().''); + + $this->rollback($module); + } + + return 0; + } + + /** + * Rollback migration from the specified module. + */ + public function rollback($module) + { + if (is_string($module)) { + $module = $this->module->findOrFail($module); + } + + $migrator = new Migrator($module, $this->getLaravel()); + + $database = $this->option('database'); + + if (! empty($database)) { + $migrator->setDatabase($database); + } + + $migrated = $migrator->rollback(); + + if (count($migrated)) { + foreach ($migrated as $migration) { + $this->line("Rollback: {$migration}"); + } + + return; + } + + $this->comment('Nothing to rollback.'); + } + + /** + * Get the console command arguments. + * + * @return array + */ + protected function getArguments() + { + return [ + ['module', InputArgument::OPTIONAL, 'The name of module will be used.'], + ]; + } + + /** + * Get the console command options. + * + * @return array + */ + protected function getOptions() + { + return [ + ['direction', 'd', InputOption::VALUE_OPTIONAL, 'The direction of ordering.', 'desc'], + ['database', null, InputOption::VALUE_OPTIONAL, 'The database connection to use.'], + ['force', null, InputOption::VALUE_NONE, 'Force the operation to run when in production.'], + ['pretend', null, InputOption::VALUE_NONE, 'Dump the SQL queries that would be run.'], + ]; + } +} diff --git a/src/Commands/MigrateStatusCommand.php b/src/Commands/MigrateStatusCommand.php new file mode 100755 index 0000000..b5a8951 --- /dev/null +++ b/src/Commands/MigrateStatusCommand.php @@ -0,0 +1,96 @@ +module = $this->laravel['modules']; + + $name = $this->argument('module'); + + if ($name) { + $module = $this->module->findOrFail($name); + + $this->migrateStatus($module); + + return 0; + } + + foreach ($this->module->getOrdered($this->option('direction')) as $module) { + $this->line('Running for module: '.$module->getName().''); + $this->migrateStatus($module); + } + + return 0; + } + + /** + * Run the migration from the specified module. + */ + protected function migrateStatus(Module $module) + { + $path = str_replace(base_path(), '', (new Migrator($module, $this->getLaravel()))->getPath()); + + $this->call('migrate:status', [ + '--path' => $path, + '--database' => $this->option('database'), + ]); + } + + /** + * Get the console command arguments. + * + * @return array + */ + protected function getArguments() + { + return [ + ['module', InputArgument::OPTIONAL, 'The name of module will be used.'], + ]; + } + + /** + * Get the console command options. + * + * @return array + */ + protected function getOptions() + { + return [ + ['direction', 'd', InputOption::VALUE_OPTIONAL, 'The direction of ordering.', 'asc'], + ['database', null, InputOption::VALUE_OPTIONAL, 'The database connection to use.'], + ]; + } +} diff --git a/src/Commands/MigrationMakeCommand.php b/src/Commands/MigrationMakeCommand.php new file mode 100755 index 0000000..a3f2b1d --- /dev/null +++ b/src/Commands/MigrationMakeCommand.php @@ -0,0 +1,166 @@ +option('fields')); + } + + /** + * @return mixed + * + * @throws \InvalidArgumentException + */ + protected function getTemplateContents() + { + $parser = new NameParser($this->argument('name')); + + if ($parser->isCreate()) { + return Stub::create('/migration/create.stub', [ + 'class' => $this->getClass(), + 'table' => $parser->getTableName(), + 'fields' => $this->getSchemaParser()->render(), + ]); + } elseif ($parser->isAdd()) { + return Stub::create('/migration/add.stub', [ + 'class' => $this->getClass(), + 'table' => $parser->getTableName(), + 'fields_up' => $this->getSchemaParser()->up(), + 'fields_down' => $this->getSchemaParser()->down(), + ]); + } elseif ($parser->isDelete()) { + return Stub::create('/migration/delete.stub', [ + 'class' => $this->getClass(), + 'table' => $parser->getTableName(), + 'fields_down' => $this->getSchemaParser()->up(), + 'fields_up' => $this->getSchemaParser()->down(), + ]); + } elseif ($parser->isDrop()) { + return Stub::create('/migration/drop.stub', [ + 'class' => $this->getClass(), + 'table' => $parser->getTableName(), + 'fields' => $this->getSchemaParser()->render(), + ]); + } + + return Stub::create('/migration/plain.stub', [ + 'class' => $this->getClass(), + ]); + } + + /** + * @return mixed + */ + protected function getDestinationFilePath() + { + $path = $this->laravel['modules']->getModulePath($this->getModuleName()); + + $generatorPath = GenerateConfigReader::read('migration'); + + return $path.$generatorPath->getPath().'/'.$this->getFileName().'.php'; + } + + /** + * @return string + */ + private function getFileName() + { + return date('Y_m_d_His_').$this->getSchemaName(); + } + + /** + * @return array|string + */ + private function getSchemaName() + { + return $this->argument('name'); + } + + /** + * @return string + */ + private function getClassName() + { + return Str::studly($this->argument('name')); + } + + public function getClass() + { + return $this->getClassName(); + } + + /** + * Run the command. + */ + public function handle(): int + { + if (parent::handle() === E_ERROR) { + return E_ERROR; + } + + if (app()->environment() === 'testing') { + return 0; + } + + return 0; + } +} diff --git a/src/Commands/ModelMakeCommand.php b/src/Commands/ModelMakeCommand.php new file mode 100755 index 0000000..8d4c934 --- /dev/null +++ b/src/Commands/ModelMakeCommand.php @@ -0,0 +1,172 @@ +handleOptionalMigrationOption(); + + return 0; + } + + /** + * Create a proper migration name: + * ProductDetail: product_details + * Product: products + * + * @return string + */ + private function createMigrationName() + { + $pieces = preg_split('/(?=[A-Z])/', $this->argument('model'), -1, PREG_SPLIT_NO_EMPTY); + + $string = ''; + foreach ($pieces as $i => $piece) { + if ($i + 1 < count($pieces)) { + $string .= strtolower($piece).'_'; + } else { + $string .= Str::plural(strtolower($piece)); + } + } + + return $string; + } + + /** + * Get the console command arguments. + * + * @return array + */ + protected function getArguments() + { + return [ + ['model', InputArgument::REQUIRED, 'The name of model will be created.'], + ['module', InputArgument::OPTIONAL, 'The name of module will be used.'], + ]; + } + + /** + * Get the console command options. + * + * @return array + */ + protected function getOptions() + { + return [ + ['fillable', null, InputOption::VALUE_OPTIONAL, 'The fillable attributes.', null], + ['migration', 'm', InputOption::VALUE_NONE, 'Flag to create associated migrations', null], + ]; + } + + /** + * Create the migration file with the given model if migration flag was used + */ + private function handleOptionalMigrationOption() + { + if ($this->option('migration') === true) { + $migrationName = 'create_'.$this->createMigrationName().'_table'; + $this->call('module:make-migration', ['name' => $migrationName, 'module' => $this->argument('module')]); + } + } + + /** + * @return mixed + */ + protected function getTemplateContents() + { + $module = $this->laravel['modules']->findOrFail($this->getModuleName()); + + return (new Stub('/model.stub', [ + 'NAME' => $this->getModelName(), + 'FILLABLE' => $this->getFillable(), + 'NAMESPACE' => $this->getClassNamespace($module), + 'CLASS' => $this->getClass(), + 'LOWER_NAME' => $module->getLowerName(), + 'MODULE' => $this->getModuleName(), + 'STUDLY_NAME' => $module->getStudlyName(), + 'MODULE_NAMESPACE' => $this->laravel['modules']->config('namespace'), + ]))->render(); + } + + /** + * @return mixed + */ + protected function getDestinationFilePath() + { + $path = $this->laravel['modules']->getModulePath($this->getModuleName()); + + $modelPath = GenerateConfigReader::read('model'); + + return $path.$modelPath->getPath().'/'.$this->getModelName().'.php'; + } + + /** + * @return mixed|string + */ + private function getModelName() + { + return Str::studly($this->argument('model')); + } + + /** + * @return string + */ + private function getFillable() + { + $fillable = $this->option('fillable'); + + if (! is_null($fillable)) { + $arrays = explode(',', $fillable); + + return json_encode($arrays); + } + + return '[]'; + } + + /** + * Get default namespace. + */ + public function getDefaultNamespace(): string + { + $module = $this->laravel['modules']; + + return $module->config('paths.generator.model.namespace') ?: $module->config('paths.generator.model.path', 'Modles'); + } +} diff --git a/src/Commands/ModuleDeleteCommand.php b/src/Commands/ModuleDeleteCommand.php new file mode 100755 index 0000000..19af7d7 --- /dev/null +++ b/src/Commands/ModuleDeleteCommand.php @@ -0,0 +1,29 @@ +laravel['modules']->delete($this->argument('module')); + + $this->info("Module {$this->argument('module')} has been deleted."); + + return 0; + } + + protected function getArguments() + { + return [ + ['module', InputArgument::REQUIRED, 'The name of module to delete.'], + ]; + } +} diff --git a/src/Commands/ModuleMakeCommand.php b/src/Commands/ModuleMakeCommand.php new file mode 100755 index 0000000..9008d91 --- /dev/null +++ b/src/Commands/ModuleMakeCommand.php @@ -0,0 +1,75 @@ +argument('name'); + $success = true; + + foreach ($names as $name) { + $code = with(new ModuleGenerator($name)) + ->setFilesystem($this->laravel['files']) + ->setModule($this->laravel['modules']) + ->setConfig($this->laravel['config']) + ->setActivator($this->laravel[ActivatorInterface::class]) + ->setConsole($this) + ->setForce($this->option('force')) + ->setPlain($this->option('plain')) + ->setActive(! $this->option('disabled')) + ->generate(); + + if ($code === E_ERROR) { + $success = false; + } + } + + return $success ? 0 : E_ERROR; + } + + /** + * Get the console command arguments. + * + * @return array + */ + protected function getArguments() + { + return [ + ['name', InputArgument::IS_ARRAY, 'The names of modules will be created.'], + ]; + } + + protected function getOptions() + { + return [ + ['plain', 'p', InputOption::VALUE_NONE, 'Generate a plain module (without some resources).'], + ['disabled', 'd', InputOption::VALUE_NONE, 'Do not enable the module at creation.'], + ['force', null, InputOption::VALUE_NONE, 'Force the operation to run when the module already exists.'], + ]; + } +} diff --git a/src/Commands/NotificationMakeCommand.php b/src/Commands/NotificationMakeCommand.php new file mode 100755 index 0000000..c355c12 --- /dev/null +++ b/src/Commands/NotificationMakeCommand.php @@ -0,0 +1,87 @@ +laravel['modules']; + + return $module->config('paths.generator.notifications.namespace') ?: $module->config('paths.generator.notifications.path', 'Notifications'); + } + + /** + * Get template contents. + * + * @return string + */ + protected function getTemplateContents() + { + $module = $this->laravel['modules']->findOrFail($this->getModuleName()); + + return (new Stub('/notification.stub', [ + 'NAMESPACE' => $this->getClassNamespace($module), + 'CLASS' => $this->getClass(), + ]))->render(); + } + + /** + * Get the destination file path. + * + * @return string + */ + protected function getDestinationFilePath() + { + $path = $this->laravel['modules']->getModulePath($this->getModuleName()); + + $notificationPath = GenerateConfigReader::read('notifications'); + + return $path.$notificationPath->getPath().'/'.$this->getFileName().'.php'; + } + + /** + * @return string + */ + private function getFileName() + { + return Str::studly($this->argument('name')); + } + + /** + * Get the console command arguments. + * + * @return array + */ + protected function getArguments() + { + return [ + ['name', InputArgument::REQUIRED, 'The name of the notification class.'], + ['module', InputArgument::OPTIONAL, 'The name of module will be used.'], + ]; + } +} diff --git a/src/Commands/PolicyMakeCommand.php b/src/Commands/PolicyMakeCommand.php new file mode 100755 index 0000000..4c79254 --- /dev/null +++ b/src/Commands/PolicyMakeCommand.php @@ -0,0 +1,88 @@ +laravel['modules']; + + return $module->config('paths.generator.policies.namespace') ?: $module->config('paths.generator.policies.path', 'Policies'); + } + + /** + * Get the console command arguments. + * + * @return array + */ + protected function getArguments() + { + return [ + ['name', InputArgument::REQUIRED, 'The name of the policy class.'], + ['module', InputArgument::OPTIONAL, 'The name of module will be used.'], + ]; + } + + /** + * @return mixed + */ + protected function getTemplateContents() + { + $module = $this->laravel['modules']->findOrFail($this->getModuleName()); + + return (new Stub('/policy.plain.stub', [ + 'NAMESPACE' => $this->getClassNamespace($module), + 'CLASS' => $this->getClass(), + ]))->render(); + } + + /** + * @return mixed + */ + protected function getDestinationFilePath() + { + $path = $this->laravel['modules']->getModulePath($this->getModuleName()); + + $policyPath = GenerateConfigReader::read('policies'); + + return $path.$policyPath->getPath().'/'.$this->getFileName().'.php'; + } + + /** + * @return string + */ + private function getFileName() + { + return Str::studly($this->argument('name')); + } +} diff --git a/src/Commands/ProviderMakeCommand.php b/src/Commands/ProviderMakeCommand.php new file mode 100755 index 0000000..dfc9309 --- /dev/null +++ b/src/Commands/ProviderMakeCommand.php @@ -0,0 +1,115 @@ +laravel['modules']; + + return $module->config('paths.generator.provider.namespace') ?: $module->config('paths.generator.provider.path', 'Providers'); + } + + /** + * Get the console command arguments. + * + * @return array + */ + protected function getArguments() + { + return [ + ['name', InputArgument::REQUIRED, 'The service provider name.'], + ['module', InputArgument::OPTIONAL, 'The name of module will be used.'], + ]; + } + + /** + * Get the console command options. + * + * @return array + */ + protected function getOptions() + { + return [ + ['master', null, InputOption::VALUE_NONE, 'Indicates the master service provider', null], + ]; + } + + /** + * @return mixed + */ + protected function getTemplateContents() + { + $stub = $this->option('master') ? 'scaffold/provider' : 'provider'; + + /** @var Module $module */ + $module = $this->laravel['modules']->findOrFail($this->getModuleName()); + + return (new Stub('/'.$stub.'.stub', [ + 'NAMESPACE' => $this->getClassNamespace($module), + 'CLASS' => $this->getClass(), + 'LOWER_NAME' => $module->getLowerName(), + 'MODULE' => $this->getModuleName(), + 'NAME' => $this->getFileName(), + 'STUDLY_NAME' => $module->getStudlyName(), + 'MODULE_NAMESPACE' => $this->laravel['modules']->config('namespace'), + 'PATH_VIEWS' => GenerateConfigReader::read('views')->getPath(), + 'PATH_LANG' => GenerateConfigReader::read('lang')->getPath(), + 'PATH_CONFIG' => GenerateConfigReader::read('config')->getPath(), + 'MIGRATIONS_PATH' => GenerateConfigReader::read('migration')->getPath(), + 'FACTORIES_PATH' => GenerateConfigReader::read('factory')->getPath(), + ]))->render(); + } + + /** + * @return mixed + */ + protected function getDestinationFilePath() + { + $path = $this->laravel['modules']->getModulePath($this->getModuleName()); + + $generatorPath = GenerateConfigReader::read('provider'); + + return $path.$generatorPath->getPath().'/'.$this->getFileName().'.php'; + } + + /** + * @return string + */ + private function getFileName() + { + return Str::studly($this->argument('name')); + } +} diff --git a/src/Commands/PublishCommand.php b/src/Commands/PublishCommand.php new file mode 100755 index 0000000..eddb6d2 --- /dev/null +++ b/src/Commands/PublishCommand.php @@ -0,0 +1,84 @@ +argument('module')) { + $this->publish($name); + + return 0; + } + + $this->publishAll(); + + return 0; + } + + /** + * Publish assets from all modules. + */ + public function publishAll() + { + foreach ($this->laravel['modules']->allEnabled() as $module) { + $this->publish($module); + } + } + + /** + * Publish assets from the specified module. + * + * @param string $name + */ + public function publish($name) + { + if ($name instanceof Module) { + $module = $name; + } else { + $module = $this->laravel['modules']->findOrFail($name); + } + + with(new AssetPublisher($module)) + ->setRepository($this->laravel['modules']) + ->setConsole($this) + ->publish(); + + $this->line("Published: {$module->getStudlyName()}"); + } + + /** + * Get the console command arguments. + * + * @return array + */ + protected function getArguments() + { + return [ + ['module', InputArgument::OPTIONAL, 'The name of module will be used.'], + ]; + } +} diff --git a/src/Commands/PublishConfigurationCommand.php b/src/Commands/PublishConfigurationCommand.php new file mode 100755 index 0000000..5913b67 --- /dev/null +++ b/src/Commands/PublishConfigurationCommand.php @@ -0,0 +1,89 @@ +argument('module')) { + $this->publishConfiguration($module); + + return 0; + } + + foreach ($this->laravel['modules']->allEnabled() as $module) { + $this->publishConfiguration($module->getName()); + } + + return 0; + } + + /** + * @param string $module + * @return string + */ + private function getServiceProviderForModule($module) + { + $namespace = $this->laravel['config']->get('modules.namespace'); + $studlyName = Str::studly($module); + + return "$namespace\\$studlyName\\Providers\\{$studlyName}ServiceProvider"; + } + + /** + * @param string $module + */ + private function publishConfiguration($module) + { + $this->call('Vendors:publish', [ + '--provider' => $this->getServiceProviderForModule($module), + '--force' => $this->option('force'), + '--tag' => ['config'], + ]); + } + + /** + * Get the console command arguments. + * + * @return array + */ + protected function getArguments() + { + return [ + ['module', InputArgument::OPTIONAL, 'The name of module being used.'], + ]; + } + + /** + * @return array + */ + protected function getOptions() + { + return [ + ['--force', '-f', InputOption::VALUE_NONE, 'Force the publishing of config files'], + ]; + } +} diff --git a/src/Commands/PublishMigrationCommand.php b/src/Commands/PublishMigrationCommand.php new file mode 100755 index 0000000..c93e948 --- /dev/null +++ b/src/Commands/PublishMigrationCommand.php @@ -0,0 +1,70 @@ +argument('module')) { + $module = $this->laravel['modules']->findOrFail($name); + + $this->publish($module); + + return 0; + } + + foreach ($this->laravel['modules']->allEnabled() as $module) { + $this->publish($module); + } + + return 0; + } + + /** + * Publish migration for the specified module. + * + * @param \mpba\Modules\Module $module + */ + public function publish($module) + { + with(new MigrationPublisher(new Migrator($module, $this->getLaravel()))) + ->setRepository($this->laravel['modules']) + ->setConsole($this) + ->publish(); + } + + /** + * Get the console command arguments. + * + * @return array + */ + protected function getArguments() + { + return [ + ['module', InputArgument::OPTIONAL, 'The name of module being used.'], + ]; + } +} diff --git a/src/Commands/PublishTranslationCommand.php b/src/Commands/PublishTranslationCommand.php new file mode 100755 index 0000000..a9682c3 --- /dev/null +++ b/src/Commands/PublishTranslationCommand.php @@ -0,0 +1,84 @@ +argument('module')) { + $this->publish($name); + + return 0; + } + + $this->publishAll(); + + return 0; + } + + /** + * Publish assets from all modules. + */ + public function publishAll() + { + foreach ($this->laravel['modules']->allEnabled() as $module) { + $this->publish($module); + } + } + + /** + * Publish assets from the specified module. + * + * @param string $name + */ + public function publish($name) + { + if ($name instanceof Module) { + $module = $name; + } else { + $module = $this->laravel['modules']->findOrFail($name); + } + + with(new LangPublisher($module)) + ->setRepository($this->laravel['modules']) + ->setConsole($this) + ->publish(); + + $this->line("Published: {$module->getStudlyName()}"); + } + + /** + * Get the console command arguments. + * + * @return array + */ + protected function getArguments() + { + return [ + ['module', InputArgument::OPTIONAL, 'The name of module will be used.'], + ]; + } +} diff --git a/src/Commands/RequestMakeCommand.php b/src/Commands/RequestMakeCommand.php new file mode 100755 index 0000000..04337a6 --- /dev/null +++ b/src/Commands/RequestMakeCommand.php @@ -0,0 +1,88 @@ +laravel['modules']; + + return $module->config('paths.generator.request.namespace') ?: $module->config('paths.generator.request.path', 'Http/Requests'); + } + + /** + * Get the console command arguments. + * + * @return array + */ + protected function getArguments() + { + return [ + ['name', InputArgument::REQUIRED, 'The name of the form request class.'], + ['module', InputArgument::OPTIONAL, 'The name of module will be used.'], + ]; + } + + /** + * @return mixed + */ + protected function getTemplateContents() + { + $module = $this->laravel['modules']->findOrFail($this->getModuleName()); + + return (new Stub('/request.stub', [ + 'NAMESPACE' => $this->getClassNamespace($module), + 'CLASS' => $this->getClass(), + ]))->render(); + } + + /** + * @return mixed + */ + protected function getDestinationFilePath() + { + $path = $this->laravel['modules']->getModulePath($this->getModuleName()); + + $requestPath = GenerateConfigReader::read('request'); + + return $path.$requestPath->getPath().'/'.$this->getFileName().'.php'; + } + + /** + * @return string + */ + private function getFileName() + { + return Str::studly($this->argument('name')); + } +} diff --git a/src/Commands/ResourceMakeCommand.php b/src/Commands/ResourceMakeCommand.php new file mode 100755 index 0000000..0ee0644 --- /dev/null +++ b/src/Commands/ResourceMakeCommand.php @@ -0,0 +1,99 @@ +laravel['modules']; + + return $module->config('paths.generator.resource.namespace') ?: $module->config('paths.generator.resource.path', 'Transformers'); + } + + /** + * Get the console command arguments. + * + * @return array + */ + protected function getArguments() + { + return [ + ['name', InputArgument::REQUIRED, 'The name of the resource class.'], + ['module', InputArgument::OPTIONAL, 'The name of module will be used.'], + ]; + } + + protected function getOptions() + { + return [ + ['collection', 'c', InputOption::VALUE_NONE, 'Create a resource collection.'], + ]; + } + + /** + * @return mixed + */ + protected function getTemplateContents() + { + $module = $this->laravel['modules']->findOrFail($this->getModuleName()); + + return (new Stub($this->getStubName(), [ + 'NAMESPACE' => $this->getClassNamespace($module), + 'CLASS' => $this->getClass(), + ]))->render(); + } + + /** + * @return mixed + */ + protected function getDestinationFilePath() + { + $path = $this->laravel['modules']->getModulePath($this->getModuleName()); + + $resourcePath = GenerateConfigReader::read('resource'); + + return $path.$resourcePath->getPath().'/'.$this->getFileName().'.php'; + } + + /** + * @return string + */ + private function getFileName() + { + return Str::studly($this->argument('name')); + } + + /** + * Determine if the command is generating a resource collection. + */ + protected function collection(): bool + { + return $this->option('collection') || + Str::endsWith($this->argument('name'), 'Collection'); + } + + protected function getStubName(): string + { + if ($this->collection()) { + return '/resource-collection.stub'; + } + + return '/resource.stub'; + } +} diff --git a/src/Commands/RouteProviderMakeCommand.php b/src/Commands/RouteProviderMakeCommand.php new file mode 100755 index 0000000..d8c91a9 --- /dev/null +++ b/src/Commands/RouteProviderMakeCommand.php @@ -0,0 +1,122 @@ +laravel['modules']->findOrFail($this->getModuleName()); + + return (new Stub('/route-provider.stub', [ + 'NAMESPACE' => $this->getClassNamespace($module), + 'CLASS' => $this->getFileName(), + 'MODULE_NAMESPACE' => $this->laravel['modules']->config('namespace'), + 'MODULE' => $this->getModuleName(), + 'CONTROLLER_NAMESPACE' => $this->getControllerNameSpace(), + 'WEB_ROUTES_PATH' => $this->getWebRoutesPath(), + 'API_ROUTES_PATH' => $this->getApiRoutesPath(), + 'LOWER_NAME' => $module->getLowerName(), + ]))->render(); + } + + /** + * @return string + */ + private function getFileName() + { + return 'RouteServiceProvider'; + } + + /** + * Get the destination file path. + * + * @return string + */ + protected function getDestinationFilePath() + { + $path = $this->laravel['modules']->getModulePath($this->getModuleName()); + + $generatorPath = GenerateConfigReader::read('provider'); + + return $path.$generatorPath->getPath().'/'.$this->getFileName().'.php'; + } + + /** + * @return mixed + */ + protected function getWebRoutesPath() + { + return '/'.$this->laravel['modules']->config('stubs.files.routes/web', 'Routes/web.php'); + } + + /** + * @return mixed + */ + protected function getApiRoutesPath() + { + return '/'.$this->laravel['modules']->config('stubs.files.routes/api', 'Routes/api.php'); + } + + public function getDefaultNamespace(): string + { + $module = $this->laravel['modules']; + + return $module->config('paths.generator.provider.namespace') ?: $module->config('paths.generator.provider.path', 'Providers'); + } + + private function getControllerNameSpace(): string + { + $module = $this->laravel['modules']; + + return str_replace('/', '\\', $module->config('paths.generator.controller.namespace') ?: $module->config('paths.generator.controller.path', 'Controller')); + } +} diff --git a/src/Commands/RuleMakeCommand.php b/src/Commands/RuleMakeCommand.php new file mode 100755 index 0000000..20f73b3 --- /dev/null +++ b/src/Commands/RuleMakeCommand.php @@ -0,0 +1,88 @@ +laravel['modules']; + + return $module->config('paths.generator.rules.namespace') ?: $module->config('paths.generator.rules.path', 'Rules'); + } + + /** + * Get the console command arguments. + * + * @return array + */ + protected function getArguments() + { + return [ + ['name', InputArgument::REQUIRED, 'The name of the rule class.'], + ['module', InputArgument::OPTIONAL, 'The name of module will be used.'], + ]; + } + + /** + * @return mixed + */ + protected function getTemplateContents() + { + $module = $this->laravel['modules']->findOrFail($this->getModuleName()); + + return (new Stub('/rule.stub', [ + 'NAMESPACE' => $this->getClassNamespace($module), + 'CLASS' => $this->getClass(), + ]))->render(); + } + + /** + * @return mixed + */ + protected function getDestinationFilePath() + { + $path = $this->laravel['modules']->getModulePath($this->getModuleName()); + + $rulePath = GenerateConfigReader::read('rules'); + + return $path.$rulePath->getPath().'/'.$this->getFileName().'.php'; + } + + /** + * @return string + */ + private function getFileName() + { + return Str::studly($this->argument('name')); + } +} diff --git a/src/Commands/SeedCommand.php b/src/Commands/SeedCommand.php new file mode 100755 index 0000000..8752576 --- /dev/null +++ b/src/Commands/SeedCommand.php @@ -0,0 +1,239 @@ +argument('module')) { + $name = Str::studly($name); + $this->moduleSeed($this->getModuleByName($name)); + } else { + $modules = $this->getModuleRepository()->getOrdered(); + array_walk($modules, [$this, 'moduleSeed']); + $this->info('All modules seeded.'); + } + } catch (\Error $e) { + $e = new ErrorException($e->getMessage(), $e->getCode(), 1, $e->getFile(), $e->getLine(), $e); + $this->reportException($e); + $this->renderException($this->getOutput(), $e); + + return E_ERROR; + } catch (\Exception $e) { + $this->reportException($e); + $this->renderException($this->getOutput(), $e); + + return E_ERROR; + } + + return 0; + } + + /** + * @throws RuntimeException + */ + public function getModuleRepository(): RepositoryInterface + { + $modules = $this->laravel['modules']; + if (! $modules instanceof RepositoryInterface) { + throw new RuntimeException('Module repository not found!'); + } + + return $modules; + } + + /** + * @return Module + * + * @throws RuntimeException + */ + public function getModuleByName($name) + { + $modules = $this->getModuleRepository(); + if ($modules->has($name) === false) { + throw new RuntimeException("Module [$name] does not exists."); + } + + return $modules->find($name); + } + + /** + * @return void + */ + public function moduleSeed(Module $module) + { + $seeders = []; + $name = $module->getName(); + $config = $module->get('migration'); + if (is_array($config) && array_key_exists('seeds', $config)) { + foreach ((array) $config['seeds'] as $class) { + if (class_exists($class)) { + $seeders[] = $class; + } + } + } else { + $class = $this->getSeederName($name); // legacy support + if (class_exists($class)) { + $seeders[] = $class; + } else { + // look at other namespaces + $classes = $this->getSeederNames($name); + foreach ($classes as $class) { + if (class_exists($class)) { + $seeders[] = $class; + } + } + } + } + + if (count($seeders) > 0) { + array_walk($seeders, [$this, 'dbSeed']); + $this->info("Module [$name] seeded."); + } + } + + /** + * Seed the specified module. + * + * @param string $className + */ + protected function dbSeed($className) + { + if ($option = $this->option('class')) { + $params['--class'] = Str::finish(substr($className, 0, strrpos($className, '\\')), '\\').$option; + } else { + $params = ['--class' => $className]; + } + + if ($option = $this->option('database')) { + $params['--database'] = $option; + } + + if ($option = $this->option('force')) { + $params['--force'] = $option; + } + + $this->call('db:seed', $params); + } + + /** + * Get master database seeder name for the specified module. + * + * @param string $name + * @return string + */ + public function getSeederName($name) + { + $name = Str::studly($name); + + $namespace = $this->laravel['modules']->config('namespace'); + $config = GenerateConfigReader::read('seeder'); + $seederPath = str_replace('/', '\\', $config->getPath()); + + return $namespace.'\\'.$name.'\\'.$seederPath.'\\'.$name.'DatabaseSeeder'; + } + + /** + * Get master database seeder name for the specified module under a different namespace than Modules. + * + * @param string $name + * @return array $foundModules array containing namespace paths + */ + public function getSeederNames($name) + { + $name = Str::studly($name); + + $seederPath = GenerateConfigReader::read('seeder'); + $seederPath = str_replace('/', '\\', $seederPath->getPath()); + + $foundModules = []; + foreach ($this->laravel['modules']->config('scan.paths') as $path) { + $namespace = array_slice(explode('/', $path), -1)[0]; + $foundModules[] = $namespace.'\\'.$name.'\\'.$seederPath.'\\'.$name.'DatabaseSeeder'; + } + + return $foundModules; + } + + /** + * Report the exception to the exception handler. + * + * @param \Symfony\Component\Console\Output\OutputInterface $output + * @param \Throwable $e + * @return void + */ + protected function renderException($output, \Exception $e) + { + $this->laravel[ExceptionHandler::class]->renderForConsole($output, $e); + } + + /** + * Report the exception to the exception handler. + * + * @param \Throwable $e + * @return void + */ + protected function reportException(\Exception $e) + { + $this->laravel[ExceptionHandler::class]->report($e); + } + + /** + * Get the console command arguments. + * + * @return array + */ + protected function getArguments() + { + return [ + ['module', InputArgument::OPTIONAL, 'The name of module will be used.'], + ]; + } + + /** + * Get the console command options. + * + * @return array + */ + protected function getOptions() + { + return [ + ['class', null, InputOption::VALUE_OPTIONAL, 'The class name of the root seeder.'], + ['database', null, InputOption::VALUE_OPTIONAL, 'The database connection to seed.'], + ['force', null, InputOption::VALUE_NONE, 'Force the operation to run when in production.'], + ]; + } +} diff --git a/src/Commands/SeedMakeCommand.php b/src/Commands/SeedMakeCommand.php new file mode 100755 index 0000000..0e0274a --- /dev/null +++ b/src/Commands/SeedMakeCommand.php @@ -0,0 +1,113 @@ +laravel['modules']->findOrFail($this->getModuleName()); + + return (new Stub('/seeder.stub', [ + 'NAME' => $this->getSeederName(), + 'MODULE' => $this->getModuleName(), + 'NAMESPACE' => $this->getClassNamespace($module), + + ]))->render(); + } + + /** + * @return mixed + */ + protected function getDestinationFilePath() + { + $this->clearCache(); + + $path = $this->laravel['modules']->getModulePath($this->getModuleName()); + + $seederPath = GenerateConfigReader::read('seeder'); + + return $path.$seederPath->getPath().'/'.$this->getSeederName().'.php'; + } + + /** + * Get seeder name. + * + * @return string + */ + private function getSeederName() + { + $end = $this->option('master') ? 'DatabaseSeeder' : 'TableSeeder'; + + return Str::studly($this->argument('name')).$end; + } + + /** + * Get default namespace. + */ + public function getDefaultNamespace(): string + { + $module = $this->laravel['modules']; + + return $module->config('paths.generator.seeder.namespace') ?: $module->config('paths.generator.seeder.path', 'Database/Seeders'); + } +} diff --git a/src/Commands/SetupCommand.php b/src/Commands/SetupCommand.php new file mode 100755 index 0000000..9916352 --- /dev/null +++ b/src/Commands/SetupCommand.php @@ -0,0 +1,74 @@ +generateModulesFolder(); + + return $this->generateAssetsFolder() | $code; + } + + /** + * Generate the modules folder. + */ + public function generateModulesFolder() + { + return $this->generateDirectory( + $this->laravel['modules']->config('paths.modules'), + 'Modules directory created successfully', + 'Modules directory already exist' + ); + } + + /** + * Generate the assets folder. + */ + public function generateAssetsFolder() + { + return $this->generateDirectory( + $this->laravel['modules']->config('paths.assets'), + 'Assets directory created successfully', + 'Assets directory already exist' + ); + } + + /** + * Generate the specified directory by given $dir. + */ + protected function generateDirectory($dir, $success, $error): int + { + if (! $this->laravel['files']->isDirectory($dir)) { + $this->laravel['files']->makeDirectory($dir, 0755, true, true); + + $this->info($success); + + return 0; + } + + $this->error($error); + + return E_ERROR; + } +} diff --git a/src/Commands/SupportMakeCommand.php b/src/Commands/SupportMakeCommand.php new file mode 100755 index 0000000..e152a75 --- /dev/null +++ b/src/Commands/SupportMakeCommand.php @@ -0,0 +1,106 @@ +laravel['modules']; + + return $module->config('paths.generator.support.namespace') ?: $module->config('paths.generator.support.path', 'Support'); + } + + protected function getArguments() + { + return [ + ['module', InputArgument::REQUIRED, 'The name of module.'], + ]; + } + + protected function getOptions() + { + return [ + ['support', null, InputOption::VALUE_OPTIONAL, 'Unused for now.', null], + ]; + } + + protected function getTemplateContents() + { + $module = $this->laravel['modules']->findOrFail($this->getModuleName()); + + return (new Stub('/moduleinfo.stub', [ + 'NAMESPACE' => $this->getClassNamespace($module), + 'MODULE' => $this->getModuleName(), + ]))->render(); + + } + + /** + * @return array|string + */ + protected function getPathName() + { + $pathName = Str::studly($this->option('support')); + + if (Str::contains(strtolower($pathName), 'support') === false) { + $pathName .= 'moduleInfo'; + } + + return $pathName; + } + + protected function getDestinationFilePath() + { + + $path = $this->laravel['modules']->getModulePath($this->getModuleName()); + $helperPath = GenerateConfigReader::read('support'); + + return $path.$helperPath->getPath().'/'.$this->getPathName().'.php'; + } + + protected function getFileName() + { + return 'moduleInfo'; + } + + /** + * Get class namespace. + * + * @param \mpba\Modules\Module $module + * @return string + */ + public function getClassNamespace($module) + { + $extra = str_replace($this->getClass(), '', $this->argument($this->argumentName)); + + $extra = str_replace('/', '\\', $extra); + + $namespace = $this->laravel['modules']->config('namespace'); + + $namespace .= '\\'.$module->getStudlyName(); + + $namespace .= '\\'.$this->getDefaultNamespace(); + + $namespace .= '\\'.$extra; + + $namespace = str_replace('/', '\\', $namespace); + + return trim($namespace, '\\'); + } +} diff --git a/src/Commands/TestMakeCommand.php b/src/Commands/TestMakeCommand.php new file mode 100755 index 0000000..1fb37e1 --- /dev/null +++ b/src/Commands/TestMakeCommand.php @@ -0,0 +1,93 @@ +laravel['modules']; + + if ($this->option('feature')) { + return $module->config('paths.generator.test-feature.namespace') ?: $module->config('paths.generator.test-feature.path', 'Tests/Feature'); + } + + return $module->config('paths.generator.test.namespace') ?: $module->config('paths.generator.test.path', 'Tests/Unit'); + } + + /** + * Get the console command arguments. + * + * @return array + */ + protected function getArguments() + { + return [ + ['name', InputArgument::REQUIRED, 'The name of the form request class.'], + ['module', InputArgument::OPTIONAL, 'The name of module will be used.'], + ]; + } + + /** + * Get the console command options. + * + * @return array + */ + protected function getOptions() + { + return [ + ['feature', null, InputOption::VALUE_NONE, 'Create a feature test.'], + ]; + } + + /** + * @return mixed + */ + protected function getTemplateContents() + { + $module = $this->laravel['modules']->findOrFail($this->getModuleName()); + $stub = '/unit-test.stub'; + + if ($this->option('feature')) { + $stub = '/feature-test.stub'; + } + + return (new Stub($stub, [ + 'NAMESPACE' => $this->getClassNamespace($module), + 'CLASS' => $this->getClass(), + ]))->render(); + } + + protected function getDestinationFilePath(): string + { + $path = $this->laravel['modules']->getModulePath($this->getModuleName()); + + if ($this->option('feature')) { + $testPath = GenerateConfigReader::read('test-feature'); + } else { + $testPath = GenerateConfigReader::read('test'); + } + + return $path.$testPath->getPath().'/'.$this->getFileName().'.php'; + } + + private function getFileName(): string + { + return Str::studly($this->argument('name')); + } +} diff --git a/src/Commands/TraitMakeCommand.php b/src/Commands/TraitMakeCommand.php new file mode 100755 index 0000000..8b0fa78 --- /dev/null +++ b/src/Commands/TraitMakeCommand.php @@ -0,0 +1,84 @@ +laravel['modules']; + + return $module->config('paths.generator.trait.namespace') ?: $module->config('paths.generator.trait.path', 'Traits'); + } + + protected function getArguments() + { + return [ + ['trait', InputArgument::REQUIRED, 'The name of the trait.'], + ['module', InputArgument::REQUIRED, 'The name of module.'], + ]; + } + + protected function getTemplateContents() + { + $module = $this->laravel['modules']->findOrFail($this->getModuleName()); + + return (new Stub($this->getStubName(), [ + 'TRAITNAME' => $this->getTraitName(), + 'NAMESPACE' => $this->getClassNamespace($module), + ]))->render(); + + } + + /** + * @return array|string + */ + protected function getTraitName() + { + $trait = Str::studly($this->argument('trait')); + + if (Str::contains(strtolower($trait), 'trait') === false) { + $trait .= 'Trait'; + } + + return $trait; + } + + protected function getDestinationFilePath() + { + + $path = $this->laravel['modules']->getModulePath($this->getModuleName()); + $traitPath = GenerateConfigReader::read('trait'); + + return $path.$traitPath->getPath().'/'.$this->getTraitName().'.php'; + } + + protected function getFileName() + { + return 'trait'; + } + + protected function getStubName() + { + return '/trait.stub'; + } + + protected function getModuleName(): string + { + return $this->argument('module'); + } +} diff --git a/src/Commands/UnUseCommand.php b/src/Commands/UnUseCommand.php new file mode 100755 index 0000000..6bea56c --- /dev/null +++ b/src/Commands/UnUseCommand.php @@ -0,0 +1,34 @@ +laravel['modules']->forgetUsed(); + + $this->info('Previous module used successfully forgotten.'); + + return 0; + } +} diff --git a/src/Commands/UpdateCommand.php b/src/Commands/UpdateCommand.php new file mode 100755 index 0000000..044f5f4 --- /dev/null +++ b/src/Commands/UpdateCommand.php @@ -0,0 +1,68 @@ +argument('module'); + + if ($name) { + $this->updateModule($name); + + return 0; + } + + /** @var \mpba\Modules\Module $module */ + foreach ($this->laravel['modules']->getOrdered() as $module) { + $this->updateModule($module->getName()); + } + + return 0; + } + + protected function updateModule($name) + { + $this->line('Running for module: '.$name.''); + + $this->laravel['modules']->update($name); + + $this->info("Module [{$name}] updated successfully."); + } + + /** + * Get the console command arguments. + * + * @return array + */ + protected function getArguments() + { + return [ + ['module', InputArgument::OPTIONAL, 'The name of module will be updated.'], + ]; + } +} diff --git a/src/Commands/UseCommand.php b/src/Commands/UseCommand.php new file mode 100755 index 0000000..a057360 --- /dev/null +++ b/src/Commands/UseCommand.php @@ -0,0 +1,56 @@ +argument('module')); + + if (! $this->laravel['modules']->has($module)) { + $this->error("Module [{$module}] does not exists."); + + return E_ERROR; + } + + $this->laravel['modules']->setUsed($module); + + $this->info("Module [{$module}] used successfully."); + + return 0; + } + + /** + * Get the console command arguments. + * + * @return array + */ + protected function getArguments() + { + return [ + ['module', InputArgument::REQUIRED, 'The name of module will be used.'], + ]; + } +} diff --git a/src/Commands/stubs/assets/js/app.stub b/src/Commands/stubs/assets/js/app.stub new file mode 100755 index 0000000..e69de29 diff --git a/src/Commands/stubs/assets/sass/app.stub b/src/Commands/stubs/assets/sass/app.stub new file mode 100755 index 0000000..e69de29 diff --git a/src/Commands/stubs/command.stub b/src/Commands/stubs/command.stub new file mode 100755 index 0000000..e9ef865 --- /dev/null +++ b/src/Commands/stubs/command.stub @@ -0,0 +1,68 @@ + + + diff --git a/src/Commands/stubs/composer.stub b/src/Commands/stubs/composer.stub new file mode 100755 index 0000000..08f65eb --- /dev/null +++ b/src/Commands/stubs/composer.stub @@ -0,0 +1,29 @@ +{ + "name": "$VENDOR$/$LOWER_NAME$", + "description": "", + "authors": [ + { + "name": "$AUTHOR_NAME$", + "email": "$AUTHOR_EMAIL$" + } + ], + "extra": { + "laravel": { + "providers": [], + "aliases": { + + } + } + }, + "autoload": { + "psr-4": { + "$MODULE_NAMESPACE$\\$STUDLY_NAME$\\": "" + }, + "autoload-dev": { + "psr-4": { + "Tests\\": "tests/", + "Modules\\$STUDLY_NAME$\\Tests\\": "modules/$STUDLY_NAME$/Tests/" + } + } + } +} diff --git a/src/Commands/stubs/controller-api.stub b/src/Commands/stubs/controller-api.stub new file mode 100755 index 0000000..8cdac7c --- /dev/null +++ b/src/Commands/stubs/controller-api.stub @@ -0,0 +1,60 @@ +define(Model::class, function (Faker $faker) { + return [ + // + ]; +}); diff --git a/src/Commands/stubs/feature-test.stub b/src/Commands/stubs/feature-test.stub new file mode 100755 index 0000000..f344b5d --- /dev/null +++ b/src/Commands/stubs/feature-test.stub @@ -0,0 +1,22 @@ +get('/'); + + $response->assertStatus(200); + } +} diff --git a/src/Commands/stubs/helper.stub b/src/Commands/stubs/helper.stub new file mode 100755 index 0000000..20d223a --- /dev/null +++ b/src/Commands/stubs/helper.stub @@ -0,0 +1,12 @@ +view('view.name'); + } +} diff --git a/src/Commands/stubs/middleware.stub b/src/Commands/stubs/middleware.stub new file mode 100755 index 0000000..954583e --- /dev/null +++ b/src/Commands/stubs/middleware.stub @@ -0,0 +1,21 @@ +id(); +$FIELDS$ + $table->timestamps(); + }); + } + + /** + * Reverse the migrations. + * + * @return void + */ + public function down() + { + Schema::dropIfExists('$TABLE$'); + } +} diff --git a/src/Commands/stubs/migration/delete.stub b/src/Commands/stubs/migration/delete.stub new file mode 100755 index 0000000..53ec1b3 --- /dev/null +++ b/src/Commands/stubs/migration/delete.stub @@ -0,0 +1,32 @@ +bigIncrements('id'); +$FIELDS$ + $table->timestamps(); + }); + } +} diff --git a/src/Commands/stubs/migration/plain.stub b/src/Commands/stubs/migration/plain.stub new file mode 100755 index 0000000..cc014c6 --- /dev/null +++ b/src/Commands/stubs/migration/plain.stub @@ -0,0 +1,28 @@ +line('The introduction to the notification.') + ->action('Notification Action', 'https://laravel.com') + ->line('Thank you for using our application!'); + } + + /** + * Get the array representation of the notification. + * + * @param mixed $notifiable + * @return array + */ + public function toArray($notifiable) + { + return [ + // + ]; + } +} diff --git a/src/Commands/stubs/package.stub b/src/Commands/stubs/package.stub new file mode 100755 index 0000000..4599509 --- /dev/null +++ b/src/Commands/stubs/package.stub @@ -0,0 +1,17 @@ +{ + "private": true, + "scripts": { + "dev": "npm run development", + "development": "cross-env NODE_ENV=development node_modules/webpack/bin/webpack.js --progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js", + "watch": "cross-env NODE_ENV=development node_modules/webpack/bin/webpack.js --watch --progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js", + "watch-poll": "npm run watch -- --watch-poll", + "hot": "cross-env NODE_ENV=development node_modules/webpack-dev-server/bin/webpack-dev-server.js --inline --hot --config=node_modules/laravel-mix/setup/webpack.config.js", + "prod": "npm run production", + "production": "cross-env NODE_ENV=production node_modules/webpack/bin/webpack.js --no-progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js" + }, + "devDependencies": { + "cross-env": "^7.0", + "laravel-mix": "^5.0.1", + "laravel-mix-merge-manifest": "^0.1.2" + } +} diff --git a/src/Commands/stubs/policy.plain.stub b/src/Commands/stubs/policy.plain.stub new file mode 100755 index 0000000..02e16df --- /dev/null +++ b/src/Commands/stubs/policy.plain.stub @@ -0,0 +1,20 @@ +mapApiRoutes(); + + $this->mapWebRoutes(); + } + + /** + * Define the "web" routes for the application. + * + * These routes all receive session state, CSRF protection, etc. + * + * @return void + */ + protected function mapWebRoutes() + { + Route::middleware('web') + ->namespace($this->moduleNamespace) + ->group(module_path('$MODULE$', '$WEB_ROUTES_PATH$')); + } + + /** + * Define the "api" routes for the application. + * + * These routes are typically stateless. + * + * @return void + */ + protected function mapApiRoutes() + { + Route::prefix('api') + ->middleware('api') + ->namespace($this->moduleNamespace) + ->group(module_path('$MODULE$', '$API_ROUTES_PATH$')); + } +} diff --git a/src/Commands/stubs/routes/api.stub b/src/Commands/stubs/routes/api.stub new file mode 100755 index 0000000..78681d7 --- /dev/null +++ b/src/Commands/stubs/routes/api.stub @@ -0,0 +1,18 @@ +get('/$LOWER_NAME$', function (Request $request) { + return $request->user(); +}); \ No newline at end of file diff --git a/src/Commands/stubs/routes/web.stub b/src/Commands/stubs/routes/web.stub new file mode 100755 index 0000000..ab7e7f7 --- /dev/null +++ b/src/Commands/stubs/routes/web.stub @@ -0,0 +1,16 @@ +group(function() { + Route::get('/', '$STUDLY_NAME$Controller@index'); +}); diff --git a/src/Commands/stubs/rule.stub b/src/Commands/stubs/rule.stub new file mode 100755 index 0000000..9b71632 --- /dev/null +++ b/src/Commands/stubs/rule.stub @@ -0,0 +1,40 @@ + '$STUDLY_NAME$', + 'features' => + [ + ], +]; diff --git a/src/Commands/stubs/scaffold/provider.stub b/src/Commands/stubs/scaffold/provider.stub new file mode 100755 index 0000000..80a86db --- /dev/null +++ b/src/Commands/stubs/scaffold/provider.stub @@ -0,0 +1,155 @@ +registerTranslations(); + $this->registerConfig(); + $this->registerViews(); + $this->registerHelpers(); + $this->registerCommands(); + $this->loadMigrationsFrom(module_path(ModuleInfo::name(), '$MIGRATIONS_PATH$')); + } + + /** + * Register the service provider. + * + * @return void + */ + public function register(): void + { + $this->app->register(RouteServiceProvider::class); + } + + /** + * Register the helpers. + * + * @return void + */ + protected function registerHelpers(): void + { + foreach (glob(__DIR__.'/../Helpers/*.php') as $filename) { + require_once $filename; + } + } + + /** + * Dynamically Register Commands. + * + * @return void + */ + public function registerCommands(): void + { + if (!$this->app->runningInConsole()) { + return; + } + $commandPath = __DIR__ . '/../Console'; + $commands = collect(File::allFiles($commandPath)) + ->map(function ($file) { + $class = 'Modules\\' . $this->moduleName . '\\Console\\' . $file->getFilenameWithoutExtension(); + return $class; + }) + ->filter(function ($class) { + return class_exists($class); + }) + ->values() + ->all(); + $this->commands($commands); + } + + /** + * Register config. + * + * @return void + */ + protected function registerConfig(): void + { + $this->publishes([ + module_path(ModuleInfo::name(), '$PATH_CONFIG$/config.php') => config_path( ModuleInfo::nameLower(). '.php'), + ], 'config'); + $this->mergeConfigFrom( + module_path(ModuleInfo::name(), '$PATH_CONFIG$/config.php'), ModuleInfo::nameLower() + ); + } + + /** + * Register views. + * + * @return void + */ + public function registerViews(): void + { + $viewPath = resource_path('views/modules/' . ModuleInfo::nameLower()); + $sourcePath = module_path(ModuleInfo::name(), '$PATH_VIEWS$'); + $this->publishes([ + $sourcePath => $viewPath + ], ['views', ModuleInfo::nameLower() . '-module-views']); + $this->loadViewsFrom(array_merge($this->getPublishableViewPaths(), [$sourcePath]), ModuleInfo::nameLower()); + } + + /** + * Register translations. + * + * @return void + */ + public function registerTranslations(): void + { + $langPath = resource_path('lang/modules/' . ModuleInfo::nameLower()); + + if (is_dir($langPath)) { + $this->loadTranslationsFrom($langPath, ModuleInfo::nameLower()); + } else { + $this->loadTranslationsFrom(module_path(ModuleInfo::name(), '$PATH_LANG$'), ModuleInfo::nameLower()); + } + } + + /** + * Regsiter View Paths + * @return array + */ + private function getPublishableViewPaths(): array + { + $paths = []; + foreach (Config::get('view.paths') as $path) { + if (is_dir($path . '/modules/' . ModuleInfo::nameLower())) { + $paths[] = $path . '/modules/' . ModuleInfo::nameLower(); + } + } + return $paths; + } +} diff --git a/src/Commands/stubs/seeder.stub b/src/Commands/stubs/seeder.stub new file mode 100755 index 0000000..f35057d --- /dev/null +++ b/src/Commands/stubs/seeder.stub @@ -0,0 +1,21 @@ +call("OthersTableSeeder"); + } +} diff --git a/src/Commands/stubs/trait.stub b/src/Commands/stubs/trait.stub new file mode 100755 index 0000000..2a4ae69 --- /dev/null +++ b/src/Commands/stubs/trait.stub @@ -0,0 +1,8 @@ +assertTrue(true); + } +} diff --git a/src/Commands/stubs/views/index.stub b/src/Commands/stubs/views/index.stub new file mode 100755 index 0000000..04b9288 --- /dev/null +++ b/src/Commands/stubs/views/index.stub @@ -0,0 +1,9 @@ +@extends('$LOWER_NAME$::layouts.master') + +@section('content') +

Hello World

+ +

+ This view is loaded from module: {!! config('$LOWER_NAME$.name') !!} +

+@endsection diff --git a/src/Commands/stubs/views/master.stub b/src/Commands/stubs/views/master.stub new file mode 100755 index 0000000..bb09abb --- /dev/null +++ b/src/Commands/stubs/views/master.stub @@ -0,0 +1,19 @@ + + + + + + + Module $STUDLY_NAME$ + + {{-- Laravel Mix - CSS File --}} + {{-- --}} + + + + @yield('content') + + {{-- Laravel Mix - JS File --}} + {{-- --}} + + diff --git a/src/Commands/stubs/webpack.stub b/src/Commands/stubs/webpack.stub new file mode 100755 index 0000000..90cda0e --- /dev/null +++ b/src/Commands/stubs/webpack.stub @@ -0,0 +1,11 @@ +const dotenvExpand = require('dotenv-expand'); +dotenvExpand(require('dotenv').config({ path: '../../.env'/*, debug: true*/})); + +const mix = require('laravel-mix'); + +mix.js(__dirname + '/Resources/assets/js/app.js', 'js/$LOWER_NAME$.js') + .sass( __dirname + '/Resources/assets/sass/app.scss', 'css/$LOWER_NAME$.css'); + +if (mix.inProduction()) { + mix.version(); +} diff --git a/src/Contracts/ActivatorInterface.php b/src/Contracts/ActivatorInterface.php new file mode 100755 index 0000000..75f8484 --- /dev/null +++ b/src/Contracts/ActivatorInterface.php @@ -0,0 +1,43 @@ +app = $app; + $this->path = $path; + $this->url = $app['url']; + $this->config = $app['config']; + $this->files = $app['files']; + $this->cache = $app['cache']; + } + + /** + * Add other module location. + * + * @param string $path + * @return $this + */ + public function addLocation($path) + { + $this->paths[] = $path; + + return $this; + } + + /** + * Get all additional paths. + */ + public function getPaths(): array + { + return $this->paths; + } + + /** + * Get scanned modules paths. + */ + public function getScanPaths(): array + { + $paths = $this->paths; + + $paths[] = $this->getPath(); + + if ($this->config('scan.enabled')) { + $paths = array_merge($paths, $this->config('scan.paths')); + } + + $paths = array_map(function ($path) { + return Str::endsWith($path, '/*') ? $path : Str::finish($path, '/*'); + }, $paths); + + return $paths; + } + + /** + * Creates a new Module instance + * + * @param Container $app + * @param string $args + * @param string $path + * @return \mpba\Modules\Module + */ + abstract protected function createModule(...$args); + + /** + * Get & scan all modules. + * + * @return array + */ + public function scan() + { + $paths = $this->getScanPaths(); + + $modules = []; + + foreach ($paths as $key => $path) { + $manifests = $this->getFiles()->glob("{$path}/module.json"); + + is_array($manifests) || $manifests = []; + + foreach ($manifests as $manifest) { + $name = Json::make($manifest)->get('name'); + + $modules[$name] = $this->createModule($this->app, $name, dirname($manifest)); + } + } + + return $modules; + } + + /** + * Get all modules. + */ + public function all(): array + { + if (! $this->config('cache.enabled')) { + return $this->scan(); + } + + return $this->formatCached($this->getCached()); + } + + /** + * Format the cached data as array of modules. + * + * @param array $cached + * @return array + */ + protected function formatCached($cached) + { + $modules = []; + + foreach ($cached as $name => $module) { + $path = $module['path']; + + $modules[$name] = $this->createModule($this->app, $name, $path); + } + + return $modules; + } + + /** + * Get cached modules. + * + * @return array + */ + public function getCached() + { + return $this->cache->remember($this->config('cache.key'), $this->config('cache.lifetime'), function () { + return $this->toCollection()->toArray(); + }); + } + + /** + * Get all modules as collection instance. + */ + public function toCollection(): Collection + { + return new Collection($this->scan()); + } + + /** + * Get modules by status. + */ + public function getByStatus($status): array + { + $modules = []; + + /** @var Module $module */ + foreach ($this->all() as $name => $module) { + if ($module->isStatus($status)) { + $modules[$name] = $module; + } + } + + return $modules; + } + + /** + * Determine whether the given module exist. + */ + public function has($name): bool + { + return array_key_exists($name, $this->all()); + } + + /** + * Get list of enabled modules. + */ + public function allEnabled(): array + { + return $this->getByStatus(true); + } + + /** + * Get list of disabled modules. + */ + public function allDisabled(): array + { + return $this->getByStatus(false); + } + + /** + * Get count from all modules. + */ + public function count(): int + { + return count($this->all()); + } + + /** + * Get all ordered modules. + * + * @param string $direction + */ + public function getOrdered($direction = 'asc'): array + { + $modules = $this->allEnabled(); + + uasort($modules, function (Module $a, Module $b) use ($direction) { + if ($a->get('order') === $b->get('order')) { + return 0; + } + + if ($direction === 'desc') { + return $a->get('order') < $b->get('order') ? 1 : -1; + } + + return $a->get('order') > $b->get('order') ? 1 : -1; + }); + + return $modules; + } + + /** + * {@inheritDoc} + */ + public function getPath(): string + { + return $this->path ?: $this->config('paths.modules', base_path('Modules')); + } + + /** + * {@inheritDoc} + */ + public function register(): void + { + foreach ($this->getOrdered() as $module) { + $module->register(); + } + } + + /** + * {@inheritDoc} + */ + public function boot(): void + { + foreach ($this->getOrdered() as $module) { + $module->boot(); + } + } + + /** + * {@inheritDoc} + */ + public function find(string $name) + { + foreach ($this->all() as $module) { + if ($module->getLowerName() === strtolower($name)) { + return $module; + } + } + } + + /** + * {@inheritDoc} + */ + public function findByAlias(string $alias) + { + foreach ($this->all() as $module) { + if ($module->getAlias() === $alias) { + return $module; + } + } + } + + /** + * {@inheritDoc} + */ + public function findRequirements($name): array + { + $requirements = []; + + $module = $this->findOrFail($name); + + foreach ($module->getRequires() as $requirementName) { + $requirements[] = $this->findByAlias($requirementName); + } + + return $requirements; + } + + /** + * Find a specific module, if there return that, otherwise throw exception. + * + * + * @return Module + * + * @throws ModuleNotFoundException + */ + public function findOrFail(string $name) + { + $module = $this->find($name); + + if ($module !== null) { + return $module; + } + + throw new ModuleNotFoundException("Module [{$name}] does not exist!"); + } + + /** + * Get all modules as laravel collection instance. + */ + public function collections($status = 1): Collection + { + return new Collection($this->getByStatus($status)); + } + + /** + * Get module path for a specific module. + * + * + * @return string + */ + public function getModulePath($module) + { + try { + return $this->findOrFail($module)->getPath().'/'; + } catch (ModuleNotFoundException $e) { + return $this->getPath().'/'.Str::studly($module).'/'; + } + } + + /** + * {@inheritDoc} + */ + public function assetPath(string $module): string + { + return $this->config('paths.assets').'/'.$module; + } + + /** + * {@inheritDoc} + */ + public function config(string $key, $default = null) + { + return $this->config->get('modules.'.$key, $default); + } + + /** + * Get storage path for module used. + */ + public function getUsedStoragePath(): string + { + $directory = storage_path('app/modules'); + if ($this->getFiles()->exists($directory) === false) { + $this->getFiles()->makeDirectory($directory, 0777, true); + } + + $path = storage_path('app/modules/modules.used'); + if (! $this->getFiles()->exists($path)) { + $this->getFiles()->put($path, ''); + } + + return $path; + } + + /** + * Set module used for cli session. + * + * + * @throws ModuleNotFoundException + */ + public function setUsed($name) + { + $module = $this->findOrFail($name); + + $this->getFiles()->put($this->getUsedStoragePath(), $module); + } + + /** + * Forget the module used for cli session. + */ + public function forgetUsed() + { + if ($this->getFiles()->exists($this->getUsedStoragePath())) { + $this->getFiles()->delete($this->getUsedStoragePath()); + } + } + + /** + * Get module used for cli session. + * + * @throws \mpba\Modules\Exceptions\ModuleNotFoundException + */ + public function getUsedNow(): string + { + return $this->findOrFail($this->getFiles()->get($this->getUsedStoragePath())); + } + + /** + * Get laravel filesystem instance. + */ + public function getFiles(): Filesystem + { + return $this->files; + } + + /** + * Get module assets path. + */ + public function getAssetsPath(): string + { + return $this->config('paths.assets'); + } + + /** + * Get asset url from a specific module. + * + * @param string $asset + * + * @throws InvalidAssetPath + */ + public function asset($asset): string + { + if (Str::contains($asset, ':') === false) { + throw InvalidAssetPath::missingModuleName($asset); + } + [$name, $url] = explode(':', $asset); + + $baseUrl = str_replace(public_path().DIRECTORY_SEPARATOR, '', $this->getAssetsPath()); + + $url = $this->url->asset($baseUrl."/{$name}/".$url); + + return str_replace(['http://', 'https://'], '//', $url); + } + + /** + * {@inheritDoc} + */ + public function isEnabled(string $name): bool + { + return $this->findOrFail($name)->isEnabled(); + } + + /** + * {@inheritDoc} + */ + public function isDisabled(string $name): bool + { + return ! $this->isEnabled($name); + } + + /** + * Enabling a specific module. + * + * @param string $name + * @return void + * + * @throws \mpba\Modules\Exceptions\ModuleNotFoundException + */ + public function enable($name) + { + $this->findOrFail($name)->enable(); + } + + /** + * Disabling a specific module. + * + * @param string $name + * @return void + * + * @throws \mpba\Modules\Exceptions\ModuleNotFoundException + */ + public function disable($name) + { + $this->findOrFail($name)->disable(); + } + + /** + * {@inheritDoc} + */ + public function delete(string $name): bool + { + return $this->findOrFail($name)->delete(); + } + + /** + * Update dependencies for the specified module. + * + * @param string $module + */ + public function update($module) + { + with(new Updater($this))->update($module); + } + + /** + * Install the specified module. + * + * @param string $name + * @param string $version + * @param string $type + * @param bool $subtree + * @return \Symfony\Component\Process\Process + */ + public function install($name, $version = 'dev-master', $type = 'composer', $subtree = false) + { + $installer = new Installer($name, $version, $type, $subtree); + + return $installer->run(); + } + + /** + * Get stub path. + * + * @return string|null + */ + public function getStubPath() + { + if ($this->stubPath !== null) { + return $this->stubPath; + } + + if ($this->config('stubs.enabled') === true) { + return $this->config('stubs.path'); + } + + return $this->stubPath; + } + + /** + * Set stub path. + * + * @param string $stubPath + * @return $this + */ + public function setStubPath($stubPath) + { + $this->stubPath = $stubPath; + + return $this; + } +} diff --git a/src/Generators/FileGenerator.php b/src/Generators/FileGenerator.php new file mode 100755 index 0000000..7855ac7 --- /dev/null +++ b/src/Generators/FileGenerator.php @@ -0,0 +1,139 @@ +path = $path; + $this->contents = $contents; + $this->filesystem = $filesystem ?: new Filesystem; + } + + /** + * Get contents. + * + * @return mixed + */ + public function getContents() + { + return $this->contents; + } + + /** + * Set contents. + * + * @param mixed $contents + * @return $this + */ + public function setContents($contents) + { + $this->contents = $contents; + + return $this; + } + + /** + * Get filesystem. + * + * @return mixed + */ + public function getFilesystem() + { + return $this->filesystem; + } + + /** + * Set filesystem. + * + * + * @return $this + */ + public function setFilesystem(Filesystem $filesystem) + { + $this->filesystem = $filesystem; + + return $this; + } + + /** + * Get path. + * + * @return mixed + */ + public function getPath() + { + return $this->path; + } + + /** + * Set path. + * + * @param mixed $path + * @return $this + */ + public function setPath($path) + { + $this->path = $path; + + return $this; + } + + public function withFileOverwrite(bool $overwrite): FileGenerator + { + $this->overwriteFile = $overwrite; + + return $this; + } + + /** + * Generate the file. + */ + public function generate() + { + $path = $this->getPath(); + if (! $this->filesystem->exists($path)) { + return $this->filesystem->put($path, $this->getContents()); + } + if ($this->overwriteFile === true) { + return $this->filesystem->put($path, $this->getContents()); + } + + throw new FileAlreadyExistException('File already exists!'); + } +} diff --git a/src/Generators/Generator.php b/src/Generators/Generator.php new file mode 100755 index 0000000..75be8ff --- /dev/null +++ b/src/Generators/Generator.php @@ -0,0 +1,5 @@ +name = $name; + $this->config = $config; + $this->filesystem = $filesystem; + $this->console = $console; + $this->module = $module; + $this->activator = $activator; + } + + /** + * Set plain flag. + * + * @param bool $plain + * @return $this + */ + public function setPlain($plain) + { + $this->plain = $plain; + + return $this; + } + + /** + * Set active flag. + * + * + * @return $this + */ + public function setActive(bool $active) + { + $this->isActive = $active; + + return $this; + } + + /** + * Get the name of module will created. By default in studly case. + * + * @return string + */ + public function getName() + { + return Str::studly($this->name); + } + + /** + * Get the laravel config instance. + * + * @return Config + */ + public function getConfig() + { + return $this->config; + } + + /** + * Set the laravel config instance. + * + * @param Config $config + * @return $this + */ + public function setConfig($config) + { + $this->config = $config; + + return $this; + } + + /** + * Set the modules activator + * + * + * @return $this + */ + public function setActivator(ActivatorInterface $activator) + { + $this->activator = $activator; + + return $this; + } + + /** + * Get the laravel filesystem instance. + * + * @return Filesystem + */ + public function getFilesystem() + { + return $this->filesystem; + } + + /** + * Set the laravel filesystem instance. + * + * @param Filesystem $filesystem + * @return $this + */ + public function setFilesystem($filesystem) + { + $this->filesystem = $filesystem; + + return $this; + } + + /** + * Get the laravel console instance. + * + * @return Console + */ + public function getConsole() + { + return $this->console; + } + + /** + * Set the laravel console instance. + * + * @param Console $console + * @return $this + */ + public function setConsole($console) + { + $this->console = $console; + + return $this; + } + + /** + * Get the module instance. + * + * @return \mpba\Modules\Module + */ + public function getModule() + { + return $this->module; + } + + /** + * Set the module instance. + * + * @param mixed $module + * @return $this + */ + public function setModule($module) + { + $this->module = $module; + + return $this; + } + + /** + * Get the list of folders will created. + * + * @return array + */ + public function getFolders() + { + return $this->module->config('paths.generator'); + } + + /** + * Get the list of files will created. + * + * @return array + */ + public function getFiles() + { + return $this->module->config('stubs.files'); + } + + /** + * Set force status. + * + * @param bool|int $force + * @return $this + */ + public function setForce($force) + { + $this->force = $force; + + return $this; + } + + /** + * Generate the module. + */ + public function generate(): int + { + $name = $this->getName(); + + if ($this->module->has($name)) { + if ($this->force) { + $this->module->delete($name); + } else { + $this->console->error("Module [{$name}] already exist!"); + + return E_ERROR; + } + } + + $this->generateFolders(); + + $this->generateModuleJsonFile(); + + if ($this->plain !== true) { + $this->generateFiles(); + $this->generateResources(); + } + + if ($this->plain === true) { + $this->cleanModuleJsonFile(); + } + + $this->activator->setActiveByName($name, $this->isActive); + + $this->console->info("Module [{$name}] created successfully."); + + return 0; + } + + /** + * Generate the folders. + */ + public function generateFolders() + { + foreach ($this->getFolders() as $key => $folder) { + $folder = GenerateConfigReader::read($key); + + if ($folder->generate() === false) { + continue; + } + + $path = $this->module->getModulePath($this->getName()) . '/' . $folder->getPath(); + + $this->filesystem->makeDirectory($path, 0755, true); + if (config('modules.stubs.gitkeep')) { + $this->generateGitKeep($path); + } + } + } + + /** + * Generate git keep to the specified path. + * + * @param string $path + */ + public function generateGitKeep($path) + { + $this->filesystem->put($path . '/.gitkeep', ''); + } + + /** + * Generate the files. + */ + public function generateFiles() + { + foreach ($this->getFiles() as $stub => $file) { + $path = $this->module->getModulePath($this->getName()) . $file; + + if (!$this->filesystem->isDirectory($dir = dirname($path))) { + $this->filesystem->makeDirectory($dir, 0775, true); + } + + $this->filesystem->put($path, $this->getStubContents($stub)); + + $this->console->info("Created : {$path}"); + } + } + + /** + * Generate some resources. + */ + public function generateResources() + { + if (GenerateConfigReader::read('seeder')->generate() === true) { + $this->console->call('module:make-seed', [ + 'name' => $this->getName(), + 'module' => $this->getName(), + '--master' => true, + ]); + } + + if (GenerateConfigReader::read('provider')->generate() === true) { + $this->console->call('module:make-provider', [ + 'name' => $this->getName() . 'ServiceProvider', + 'module' => $this->getName(), + '--master' => true, + ]); + $this->console->call('module:route-provider', [ + 'module' => $this->getName(), + ]); + } + + if (GenerateConfigReader::read('controller')->generate() === true) { + $this->console->call('module:make-controller', [ + 'controller' => $this->getName() . 'Controller', + 'module' => $this->getName(), + ]); + } + if (GenerateConfigReader::read('helper')->generate() === true) { + $this->console->call('module:make-helper', [ + 'module' => $this->getName(), + ]); + } + + if (GenerateConfigReader::read('support')->generate() === true) { + $this->console->call('module:make-support', [ + 'module' => $this->getName(), + ]); + } + + } + + /** + * Get the contents of the specified stub file by given stub name. + * + * + * @return string + */ + protected function getStubContents($stub) + { + return (new Stub( + '/' . $stub . '.stub', + $this->getReplacement($stub) + ) + )->render(); + } + + /** + * get the list for the replacements. + */ + public function getReplacements() + { + return $this->module->config('stubs.replacements'); + } + + /** + * Get array replacement for the specified stub. + * + * + * @return array + */ + protected function getReplacement($stub) + { + $replacements = $this->module->config('stubs.replacements'); + + if (!isset($replacements[$stub])) { + return []; + } + + $keys = $replacements[$stub]; + + $replaces = []; + + if ($stub === 'json' || $stub === 'composer') { + if (in_array('PROVIDER_NAMESPACE', $keys, true) === false) { + $keys[] = 'PROVIDER_NAMESPACE'; + } + } + foreach ($keys as $key) { + if (method_exists($this, $method = 'get' . ucfirst(Str::studly(strtolower($key))) . 'Replacement')) { + $replaces[$key] = $this->$method(); + } else { + $replaces[$key] = null; + } + } + + return $replaces; + } + + /** + * Generate the module.json file + */ + private function generateModuleJsonFile() + { + $path = $this->module->getModulePath($this->getName()) . 'module.json'; + + if (!$this->filesystem->isDirectory($dir = dirname($path))) { + $this->filesystem->makeDirectory($dir, 0775, true); + } + + $this->filesystem->put($path, $this->getStubContents('json')); + + $this->console->info("Created : {$path}"); + } + + /** + * Remove the default service provider that was added in the module.json file + * This is needed when a --plain module was created + */ + private function cleanModuleJsonFile() + { + $path = $this->module->getModulePath($this->getName()) . 'module.json'; + + $content = $this->filesystem->get($path); + $namespace = $this->getModuleNamespaceReplacement(); + $studlyName = $this->getStudlyNameReplacement(); + + $provider = '"' . $namespace . '\\\\' . $studlyName . '\\\\Providers\\\\' . $studlyName . 'ServiceProvider"'; + + $content = str_replace($provider, '', $content); + + $this->filesystem->put($path, $content); + } + + /** + * Get the module name in lower case. + * + * @return string + */ + protected function getLowerNameReplacement() + { + return strtolower($this->getName()); + } + + /** + * Get the module name in studly case. + * + * @return string + */ + protected function getStudlyNameReplacement() + { + return $this->getName(); + } + + /** + * Get replacement for $VENDOR$. + * + * @return string + */ + protected function getVendorReplacement() + { + return $this->module->config('composer.Vendors'); + } + + /** + * Get replacement for $MODULE_NAMESPACE$. + * + * @return string + */ + protected function getModuleNamespaceReplacement() + { + return str_replace('\\', '\\\\', $this->module->config('namespace')); + } + + /** + * Get replacement for $AUTHOR_NAME$. + * + * @return string + */ + protected function getAuthorNameReplacement() + { + return $this->module->config('composer.author.name'); + } + + /** + * Get replacement for $AUTHOR_EMAIL$. + * + * @return string + */ + protected function getAuthorEmailReplacement() + { + return $this->module->config('composer.author.email'); + } + + protected function getProviderNamespaceReplacement(): string + { + return str_replace('\\', '\\\\', GenerateConfigReader::read('provider')->getNamespace()); + } +} diff --git a/src/Json.php b/src/Json.php new file mode 100755 index 0000000..80d72c5 --- /dev/null +++ b/src/Json.php @@ -0,0 +1,231 @@ +path = (string) $path; + $this->filesystem = $filesystem ?: new Filesystem; + $this->attributes = Collection::make($this->getAttributes()); + } + + /** + * Get filesystem. + * + * @return Filesystem + */ + public function getFilesystem() + { + return $this->filesystem; + } + + /** + * Set filesystem. + * + * + * @return $this + */ + public function setFilesystem(Filesystem $filesystem) + { + $this->filesystem = $filesystem; + + return $this; + } + + /** + * Get path. + * + * @return string + */ + public function getPath() + { + return $this->path; + } + + /** + * Set path. + * + * @param mixed $path + * @return $this + */ + public function setPath($path) + { + $this->path = (string) $path; + + return $this; + } + + /** + * Make new instance. + * + * @param string $path + * @return static + */ + public static function make($path, ?Filesystem $filesystem = null) + { + return new static($path, $filesystem); + } + + /** + * Get file content. + * + * @return string + */ + public function getContents() + { + return $this->filesystem->get($this->getPath()); + } + + /** + * Get file contents as array. + * + * @return array + * + * @throws \Exception + */ + public function getAttributes() + { + $attributes = json_decode($this->getContents(), 1); + + // any JSON parsing errors should throw an exception + if (json_last_error() > 0) { + throw new InvalidJsonException('Error processing file: '.$this->getPath().'. Error: '.json_last_error_msg()); + } + + if (config('modules.cache.enabled') === false) { + return $attributes; + } + + return app('cache')->remember($this->getPath(), config('modules.cache.lifetime'), function () use ($attributes) { + return $attributes; + }); + } + + /** + * Convert the given array data to pretty json. + * + * + * @return string + */ + public function toJsonPretty(?array $data = null) + { + return json_encode($data ?: $this->attributes, JSON_PRETTY_PRINT); + } + + /** + * Update json contents from array data. + * + * + * @return bool + */ + public function update(array $data) + { + $this->attributes = new Collection(array_merge($this->attributes->toArray(), $data)); + + return $this->save(); + } + + /** + * Set a specific key & value. + * + * @param string $key + * @param mixed $value + * @return $this + */ + public function set($key, $value) + { + $this->attributes->offsetSet($key, $value); + + return $this; + } + + /** + * Save the current attributes array to the file storage. + * + * @return bool + */ + public function save() + { + return $this->filesystem->put($this->getPath(), $this->toJsonPretty()); + } + + /** + * Handle magic method __get. + * + * @param string $key + * @return mixed + */ + public function __get($key) + { + return $this->get($key); + } + + /** + * Get the specified attribute from json file. + * + * @param null $default + * @return mixed + */ + public function get($key, $default = null) + { + return $this->attributes->get($key, $default); + } + + /** + * Handle call to __call method. + * + * @param string $method + * @param array $arguments + * @return mixed + */ + public function __call($method, $arguments = []) + { + if (method_exists($this, $method)) { + return call_user_func_array([$this, $method], $arguments); + } + + return call_user_func_array([$this->attributes, $method], $arguments); + } + + /** + * Handle call to __toString method. + * + * @return string + */ + public function __toString() + { + return $this->getContents(); + } +} diff --git a/src/Laravel/LaravelFileRepository.php b/src/Laravel/LaravelFileRepository.php new file mode 100755 index 0000000..a68bcea --- /dev/null +++ b/src/Laravel/LaravelFileRepository.php @@ -0,0 +1,16 @@ +getSnakeName().'_module.php', $this->app->getCachedConfigPath()); + } + + return Str::replaceLast('services.php', $this->getSnakeName().'_module.php', $this->app->getCachedServicesPath()); + } + + /** + * {@inheritdoc} + */ + public function registerProviders(): void + { + (new ProviderRepository($this->app, new Filesystem, $this->getCachedServicesPath())) + ->load($this->get('providers', [])); + } + + /** + * {@inheritdoc} + */ + public function registerAliases(): void + { + $loader = AliasLoader::getInstance(); + foreach ($this->get('aliases', []) as $aliasName => $aliasClass) { + $loader->alias($aliasName, $aliasClass); + } + } +} diff --git a/src/LaravelModulesServiceProvider.php b/src/LaravelModulesServiceProvider.php new file mode 100755 index 0000000..2c72fa5 --- /dev/null +++ b/src/LaravelModulesServiceProvider.php @@ -0,0 +1,70 @@ +registerNamespaces(); + $this->registerModules(); + $this->loadMigrationsFrom(__DIR__.'/database/migrations'); + } + + /** + * Register the service provider. + */ + public function register() + { + $this->registerServices(); + $this->setupStubPath(); + $this->registerProviders(); + } + + /** + * Setup stub path. + */ + public function setupStubPath() + { + $path = $this->app['config']->get('modules.stubs.path') ?? __DIR__.'/Commands/stubs'; + Stub::setBasePath($path); + + $this->app->booted(function ($app) { + /** @var RepositoryInterface $moduleRepository */ + $moduleRepository = $app[RepositoryInterface::class]; + if ($moduleRepository->config('stubs.enabled') === true) { + Stub::setBasePath($moduleRepository->config('stubs.path')); + } + }); + } + + /** + * {@inheritdoc} + */ + protected function registerServices() + { + $this->app->singleton(RepositoryInterface::class, function ($app) { + $path = $app['config']->get('modules.paths.modules'); + + return new Laravel\LaravelFileRepository($app, $path); + }); + $this->app->singleton(Contracts\ActivatorInterface::class, function ($app) { + $activator = $app['config']->get('modules.activator'); + $class = $app['config']->get('modules.activators.'.$activator)['class']; + + if ($class === null) { + throw InvalidActivatorClass::missingConfig(); + } + + return new $class($app); + }); + $this->app->alias(RepositoryInterface::class, 'modules'); + } +} diff --git a/src/Lumen/LumenFileRepository.php b/src/Lumen/LumenFileRepository.php new file mode 100755 index 0000000..439721c --- /dev/null +++ b/src/Lumen/LumenFileRepository.php @@ -0,0 +1,16 @@ +getSnakeName().'_module.php', $this->app->basePath('storage/app/').'services.php'); + } + + /** + * {@inheritdoc} + */ + public function registerProviders(): void + { + foreach ($this->get('providers', []) as $provider) { + $this->app->register($provider); + } + } + + /** + * {@inheritdoc} + */ + public function registerAliases(): void {} +} diff --git a/src/LumenModulesServiceProvider.php b/src/LumenModulesServiceProvider.php new file mode 100755 index 0000000..2fba87d --- /dev/null +++ b/src/LumenModulesServiceProvider.php @@ -0,0 +1,59 @@ +setupStubPath(); + } + + /** + * Register all modules. + */ + public function register() + { + $this->registerNamespaces(); + $this->registerServices(); + $this->registerModules(); + $this->registerProviders(); + } + + /** + * Setup stub path. + */ + public function setupStubPath() + { + Stub::setBasePath(__DIR__.'/Commands/stubs'); + + if (app('modules')->config('stubs.enabled') === true) { + Stub::setBasePath(app('modules')->config('stubs.path')); + } + } + + /** + * {@inheritdoc} + */ + protected function registerServices() + { + $this->app->singleton(RepositoryInterface::class, function ($app) { + $path = $app['config']->get('modules.paths.modules'); + + return new Lumen\LumenFileRepository($app, $path); + }); + $this->app->singleton(Contracts\ActivatorInterface::class, function ($app) { + $activator = $app['config']->get('modules.activator'); + $class = $app['config']->get('modules.activators.'.$activator)['class']; + + return new $class($app); + }); + $this->app->alias(RepositoryInterface::class, 'modules'); + } +} diff --git a/src/Migrations/Migrator.php b/src/Migrations/Migrator.php new file mode 100755 index 0000000..182f476 --- /dev/null +++ b/src/Migrations/Migrator.php @@ -0,0 +1,306 @@ +module = $module; + $this->laravel = $application; + } + + /** + * Set the database connection to be used + * + * + * @return $this + */ + public function setDatabase($database) + { + if (is_string($database) && $database) { + $this->database = $database; + } + + return $this; + } + + /** + * @return Module + */ + public function getModule() + { + return $this->module; + } + + /** + * Get migration path. + * + * @return string + */ + public function getPath() + { + $config = $this->module->get('migration'); + + $migrationPath = GenerateConfigReader::read('migration'); + $path = (is_array($config) && array_key_exists('path', $config)) ? $config['path'] : $migrationPath->getPath(); + + return $this->module->getExtraPath($path); + } + + /** + * Get migration files. + * + * @param bool $reverse + * @return array + */ + public function getMigrations($reverse = false) + { + $files = $this->laravel['files']->glob($this->getPath().'/*_*.php'); + + // Once we have the array of files in the directory we will just remove the + // extension and take the basename of the file which is all we need when + // finding the migrations that haven't been run against the databases. + if ($files === false) { + return []; + } + + $files = array_map(function ($file) { + return str_replace('.php', '', basename($file)); + }, $files); + + // Once we have all of the formatted file names we will sort them and since + // they all start with a timestamp this should give us the migrations in + // the order they were actually created by the application developers. + sort($files); + + if ($reverse) { + return array_reverse($files); + } + + return $files; + } + + /** + * Rollback migration. + * + * @return array + */ + public function rollback() + { + $migrations = $this->getLast($this->getMigrations(true)); + + $this->requireFiles($migrations->toArray()); + + $migrated = []; + + foreach ($migrations as $migration) { + $data = $this->find($migration); + + if ($data->count()) { + $migrated[] = $migration; + + $this->down($migration); + + $data->delete(); + } + } + + return $migrated; + } + + /** + * Reset migration. + * + * @return array + */ + public function reset() + { + $migrations = $this->getMigrations(true); + + $this->requireFiles($migrations); + + $migrated = []; + + foreach ($migrations as $migration) { + $data = $this->find($migration); + + if ($data->count()) { + $migrated[] = $migration; + + $this->down($migration); + + $data->delete(); + } + } + + return $migrated; + } + + /** + * Run down schema from the given migration name. + * + * @param string $migration + */ + public function down($migration) + { + $this->resolve($migration)->down(); + } + + /** + * Run up schema from the given migration name. + * + * @param string $migration + */ + public function up($migration) + { + $this->resolve($migration)->up(); + } + + /** + * Resolve a migration instance from a file. + * + * @param string $file + * @return object + */ + public function resolve($file) + { + $file = implode('_', array_slice(explode('_', $file), 4)); + + $class = Str::studly($file); + + return new $class; + } + + /** + * Require in all the migration files in a given path. + */ + public function requireFiles(array $files) + { + $path = $this->getPath(); + foreach ($files as $file) { + $this->laravel['files']->requireOnce($path.'/'.$file.'.php'); + } + } + + /** + * Get table instance. + * + * @return \Illuminate\Database\Query\Builder + */ + public function table() + { + return $this->laravel['db']->connection($this->database ?: null)->table(config('database.migrations')); + } + + /** + * Find migration data from database by given migration name. + * + * @param string $migration + * @return object + */ + public function find($migration) + { + return $this->table()->whereMigration($migration); + } + + /** + * Save new migration to database. + * + * @param string $migration + * @return mixed + */ + public function log($migration) + { + return $this->table()->insert([ + 'migration' => $migration, + 'batch' => $this->getNextBatchNumber(), + ]); + } + + /** + * Get the next migration batch number. + * + * @return int + */ + public function getNextBatchNumber() + { + return $this->getLastBatchNumber() + 1; + } + + /** + * Get the last migration batch number. + * + * @param array|null $migrations + * @return int + */ + public function getLastBatchNumber($migrations = null) + { + $table = $this->table(); + + if (is_array($migrations)) { + $table = $table->whereIn('migration', $migrations); + } + + return $table->max('batch'); + } + + /** + * Get the last migration batch. + * + * @param array $migrations + * @return Collection + */ + public function getLast($migrations) + { + $query = $this->table() + ->where('batch', $this->getLastBatchNumber($migrations)) + ->whereIn('migration', $migrations); + + $result = $query->orderBy('migration', 'desc')->get(); + + return collect($result)->map(function ($item) { + return (array) $item; + })->pluck('migration'); + } + + /** + * Get the ran migrations. + * + * @return Collection + */ + public function getRan() + { + return $this->table()->pluck('migration'); + } +} diff --git a/src/Module.php b/src/Module.php new file mode 100755 index 0000000..69aaf6e --- /dev/null +++ b/src/Module.php @@ -0,0 +1,390 @@ +name = $name; + $this->path = $path; + $this->cache = $app['cache']; + $this->files = $app['files']; + $this->translator = $app['translator']; + $this->activator = $app[ActivatorInterface::class]; + $this->app = $app; + } + + /** + * Get name. + */ + public function getName(): string + { + return $this->name; + } + + /** + * Get name in lower case. + */ + public function getLowerName(): string + { + return strtolower($this->name); + } + + /** + * Get name in studly case. + */ + public function getStudlyName(): string + { + return Str::studly($this->name); + } + + /** + * Get name in snake case. + */ + public function getSnakeName(): string + { + return Str::snake($this->name); + } + + /** + * Get description. + */ + public function getDescription(): string + { + return $this->get('description'); + } + + /** + * Get alias. + */ + public function getAlias(): string + { + return $this->get('alias'); + } + + /** + * Get priority. + */ + public function getPriority(): string + { + return $this->get('priority'); + } + + /** + * Get module requirements. + */ + public function getRequires(): array + { + return $this->get('requires'); + } + + /** + * Get path. + */ + public function getPath(): string + { + return $this->path; + } + + /** + * Set path. + * + * @param string $path + * @return $this + */ + public function setPath($path): Module + { + $this->path = $path; + + return $this; + } + + /** + * Bootstrap the application events. + */ + public function boot(): void + { + if (config('modules.register.translations', true) === true) { + $this->registerTranslation(); + } + + if ($this->isLoadFilesOnBoot()) { + $this->registerFiles(); + } + + $this->fireEvent('boot'); + } + + /** + * Register module's translation. + */ + protected function registerTranslation(): void + { + $lowerName = $this->getLowerName(); + + $langPath = $this->getPath().'/Resources/lang'; + + if (is_dir($langPath)) { + $this->loadTranslationsFrom($langPath, $lowerName); + } + } + + /** + * Get json contents from the cache, setting as needed. + * + * @param string $file + */ + public function json($file = null): Json + { + if ($file === null) { + $file = 'module.json'; + } + + return Arr::get($this->moduleJson, $file, function () use ($file) { + return $this->moduleJson[$file] = new Json($this->getPath().'/'.$file, $this->files); + }); + } + + /** + * Get a specific data from json file by given the key. + * + * @param null $default + * @return mixed + */ + public function get(string $key, $default = null) + { + return $this->json()->get($key, $default); + } + + /** + * Get a specific data from composer.json file by given the key. + * + * @param null $default + * @return mixed + */ + public function getComposerAttr($key, $default = null) + { + return $this->json('composer.json')->get($key, $default); + } + + /** + * Register the module. + */ + public function register(): void + { + $this->registerAliases(); + + $this->registerProviders(); + + if ($this->isLoadFilesOnBoot() === false) { + $this->registerFiles(); + } + + $this->fireEvent('register'); + } + + /** + * Register the module event. + * + * @param string $event + */ + protected function fireEvent($event): void + { + $this->app['events']->dispatch(sprintf('modules.%s.'.$event, $this->getLowerName()), [$this]); + } + + /** + * Register the aliases from this module. + */ + abstract public function registerAliases(): void; + + /** + * Register the service providers from this module. + */ + abstract public function registerProviders(): void; + + /** + * Get the path to the cached *_module.php file. + */ + abstract public function getCachedServicesPath(): string; + + /** + * Register the files from this module. + */ + protected function registerFiles(): void + { + foreach ($this->get('files', []) as $file) { + include $this->path.'/'.$file; + } + } + + /** + * Handle call __toString. + * + * @return string + */ + public function __toString() + { + return $this->getStudlyName(); + } + + /** + * Determine whether the given status same with the current module status. + */ + public function isStatus(bool $status): bool + { + return $this->activator->hasStatus($this, $status); + } + + /** + * Determine whether the current module activated. + */ + public function isEnabled(): bool + { + return $this->activator->hasStatus($this, true); + } + + /** + * Determine whether the current module not disabled. + */ + public function isDisabled(): bool + { + return ! $this->isEnabled(); + } + + /** + * Set active state for current module. + */ + public function setActive(bool $active): void + { + $this->activator->setActive($this, $active); + } + + /** + * Disable the current module. + */ + public function disable(): void + { + $this->fireEvent('disabling'); + + $this->activator->disable($this); + $this->flushCache(); + + $this->fireEvent('disabled'); + } + + /** + * Enable the current module. + */ + public function enable(): void + { + $this->fireEvent('enabling'); + + $this->activator->enable($this); + $this->flushCache(); + + $this->fireEvent('enabled'); + } + + /** + * Delete the current module. + */ + public function delete(): bool + { + $this->activator->delete($this); + + return $this->json()->getFilesystem()->deleteDirectory($this->getPath()); + } + + /** + * Get extra path. + */ + public function getExtraPath(string $path): string + { + return $this->getPath().'/'.$path; + } + + /** + * Check if can load files of module on boot method. + */ + protected function isLoadFilesOnBoot(): bool + { + return config('modules.register.files', 'register') === 'boot' && + // force register method if option == boot && app is MPBA CMS + ! class_exists('\Modules\Core\Foundation\MPBACms'); + } + + private function flushCache(): void + { + if (config('modules.cache.enabled')) { + $this->cache->store()->flush(); + } + } + + /** + * Register a translation file namespace. + */ + private function loadTranslationsFrom(string $path, string $namespace): void + { + $this->translator->addNamespace($namespace, $path); + } +} diff --git a/src/ModulesServiceProvider.php b/src/ModulesServiceProvider.php new file mode 100755 index 0000000..b6b7a01 --- /dev/null +++ b/src/ModulesServiceProvider.php @@ -0,0 +1,67 @@ +app->register(BootstrapServiceProvider::class); + } + + /** + * Register package's namespaces. + */ + protected function registerNamespaces(): void + { + $configPath = __DIR__.'/../config/config.php'; + + $this->mergeConfigFrom($configPath, 'modules'); + $this->publishes([ + $configPath => config_path('modules.php'), + ], 'config'); + } + + /** + * Register the service provider. + */ + abstract protected function registerServices(); + + /** + * Get the services provided by the provider. + * + * @return array + */ + public function provides(): array + { + return [RepositoryInterface::class, 'modules']; + } + + /** + * Register providers. + */ + protected function registerProviders() + { + $this->app->register(ConsoleServiceProvider::class); + $this->app->register(ContractsServiceProvider::class); + } +} diff --git a/src/Process/Installer.php b/src/Process/Installer.php new file mode 100755 index 0000000..2ec6141 --- /dev/null +++ b/src/Process/Installer.php @@ -0,0 +1,305 @@ +name = $name; + $this->version = $version; + $this->type = $type; + $this->tree = $tree; + } + + /** + * Set destination path. + * + * @param string $path + * @return $this + */ + public function setPath($path) + { + $this->path = $path; + + return $this; + } + + /** + * Set the module repository instance. + * + * @return $this + */ + public function setRepository(RepositoryInterface $repository) + { + $this->repository = $repository; + + return $this; + } + + /** + * Set console command instance. + * + * + * @return $this + */ + public function setConsole(Command $console) + { + $this->console = $console; + + return $this; + } + + /** + * Set process timeout. + * + * @param int $timeout + * @return $this + */ + public function setTimeout($timeout) + { + $this->timeout = $timeout; + + return $this; + } + + /** + * Run the installation process. + * + * @return \Symfony\Component\Process\Process + */ + public function run() + { + $process = $this->getProcess(); + + $process->setTimeout($this->timeout); + + if ($this->console instanceof Command) { + $process->run(function ($type, $line) { + $this->console->line($line); + }); + } + + return $process; + } + + /** + * Get process instance. + * + * @return \Symfony\Component\Process\Process + */ + public function getProcess() + { + if ($this->type) { + if ($this->tree) { + return $this->installViaSubtree(); + } + + return $this->installViaGit(); + } + + return $this->installViaComposer(); + } + + /** + * Get destination path. + * + * @return string + */ + public function getDestinationPath() + { + if ($this->path) { + return $this->path; + } + + return $this->repository->getModulePath($this->getModuleName()); + } + + /** + * Get git repo url. + * + * @return string|null + */ + public function getRepoUrl() + { + switch ($this->type) { + case 'github': + return "git@github.com:{$this->name}.git"; + + case 'github-https': + return "https://github.com/{$this->name}.git"; + + case 'gitlab': + return "git@gitlab.com:{$this->name}.git"; + break; + + case 'bitbucket': + return "git@bitbucket.org:{$this->name}.git"; + + default: + + // Check of type 'scheme://host/path' + if (filter_var($this->type, FILTER_VALIDATE_URL)) { + return $this->type; + } + + // Check of type 'user@host' + if (filter_var($this->type, FILTER_VALIDATE_EMAIL)) { + return "{$this->type}:{$this->name}.git"; + } + + return; + break; + } + } + + /** + * Get branch name. + * + * @return string + */ + public function getBranch() + { + return is_null($this->version) ? 'master' : $this->version; + } + + /** + * Get module name. + * + * @return string + */ + public function getModuleName() + { + $parts = explode('/', $this->name); + + return Str::studly(end($parts)); + } + + /** + * Get composer package name. + * + * @return string + */ + public function getPackageName() + { + if (is_null($this->version)) { + return $this->name.':dev-master'; + } + + return $this->name.':'.$this->version; + } + + /** + * Install the module via git. + * + * @return \Symfony\Component\Process\Process + */ + public function installViaGit() + { + return Process::fromShellCommandline(sprintf( + 'cd %s && git clone %s %s && cd %s && git checkout %s', + base_path(), + $this->getRepoUrl(), + $this->getDestinationPath(), + $this->getDestinationPath(), + $this->getBranch() + )); + } + + /** + * Install the module via git subtree. + * + * @return \Symfony\Component\Process\Process + */ + public function installViaSubtree() + { + return Process::fromShellCommandline(sprintf( + 'cd %s && git remote add %s %s && git subtree add --prefix=%s --squash %s %s', + base_path(), + $this->getModuleName(), + $this->getRepoUrl(), + $this->getDestinationPath(), + $this->getModuleName(), + $this->getBranch() + )); + } + + /** + * Install the module via composer. + * + * @return \Symfony\Component\Process\Process + */ + public function installViaComposer() + { + return Process::fromShellCommandline(sprintf( + 'cd %s && composer require %s', + base_path(), + $this->getPackageName() + )); + } +} diff --git a/src/Process/Runner.php b/src/Process/Runner.php new file mode 100755 index 0000000..d8b81d5 --- /dev/null +++ b/src/Process/Runner.php @@ -0,0 +1,27 @@ +module = $module; + } + + /** + * Run the given command. + * + * @param string $command + */ + public function run($command) + { + passthru($command); + } +} diff --git a/src/Process/Updater.php b/src/Process/Updater.php new file mode 100755 index 0000000..bef16ae --- /dev/null +++ b/src/Process/Updater.php @@ -0,0 +1,70 @@ +module->findOrFail($module); + + chdir(base_path()); + + $this->installRequires($module); + $this->installDevRequires($module); + $this->copyScriptsToMainComposerJson($module); + } + + private function installRequires(Module $module) + { + $packages = $module->getComposerAttr('require', []); + + $concatenatedPackages = ''; + foreach ($packages as $name => $version) { + $concatenatedPackages .= "\"{$name}:{$version}\" "; + } + + if (! empty($concatenatedPackages)) { + $this->run("composer require {$concatenatedPackages}"); + } + } + + private function installDevRequires(Module $module) + { + $devPackages = $module->getComposerAttr('require-dev', []); + + $concatenatedPackages = ''; + foreach ($devPackages as $name => $version) { + $concatenatedPackages .= "\"{$name}:{$version}\" "; + } + + if (! empty($concatenatedPackages)) { + $this->run("composer require --dev {$concatenatedPackages}"); + } + } + + private function copyScriptsToMainComposerJson(Module $module) + { + $scripts = $module->getComposerAttr('scripts', []); + + $composer = json_decode(file_get_contents(base_path('composer.json')), true); + + foreach ($scripts as $key => $script) { + if (array_key_exists($key, $composer['scripts'])) { + $composer['scripts'][$key] = array_unique(array_merge($composer['scripts'][$key], $script)); + + continue; + } + $composer['scripts'] = array_merge($composer['scripts'], [$key => $script]); + } + + file_put_contents(base_path('composer.json'), json_encode($composer, JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT)); + } +} diff --git a/src/Providers/BootstrapServiceProvider.php b/src/Providers/BootstrapServiceProvider.php new file mode 100755 index 0000000..c11f41c --- /dev/null +++ b/src/Providers/BootstrapServiceProvider.php @@ -0,0 +1,25 @@ +app[RepositoryInterface::class]->boot(); + } + + /** + * Register the provider. + */ + public function register(): void + { + $this->app[RepositoryInterface::class]->register(); + } +} diff --git a/src/Providers/ConsoleServiceProvider.php b/src/Providers/ConsoleServiceProvider.php new file mode 100755 index 0000000..5f10f3b --- /dev/null +++ b/src/Providers/ConsoleServiceProvider.php @@ -0,0 +1,122 @@ +commands($this->commands); + } + + /** + * @return array + */ + public function provides() + { + $provides = $this->commands; + + return $provides; + } +} diff --git a/src/Providers/ContractsServiceProvider.php b/src/Providers/ContractsServiceProvider.php new file mode 100755 index 0000000..2fcbdae --- /dev/null +++ b/src/Providers/ContractsServiceProvider.php @@ -0,0 +1,18 @@ +app->bind(RepositoryInterface::class, LaravelFileRepository::class); + } +} diff --git a/src/Publishing/AssetPublisher.php b/src/Publishing/AssetPublisher.php new file mode 100755 index 0000000..de165f0 --- /dev/null +++ b/src/Publishing/AssetPublisher.php @@ -0,0 +1,37 @@ +repository->assetPath($this->module->getLowerName()); + } + + /** + * Get source path. + * + * @return string + */ + public function getSourcePath() + { + return $this->getModule()->getExtraPath( + GenerateConfigReader::read('assets')->getPath() + ); + } +} diff --git a/src/Publishing/LangPublisher.php b/src/Publishing/LangPublisher.php new file mode 100755 index 0000000..a8f7301 --- /dev/null +++ b/src/Publishing/LangPublisher.php @@ -0,0 +1,39 @@ +module->getLowerName(); + + return base_path("resources/lang/{$name}"); + } + + /** + * Get source path. + * + * @return string + */ + public function getSourcePath() + { + return $this->getModule()->getExtraPath( + GenerateConfigReader::read('lang')->getPath() + ); + } +} diff --git a/src/Publishing/MigrationPublisher.php b/src/Publishing/MigrationPublisher.php new file mode 100755 index 0000000..822993d --- /dev/null +++ b/src/Publishing/MigrationPublisher.php @@ -0,0 +1,42 @@ +migrator = $migrator; + parent::__construct($migrator->getModule()); + } + + /** + * Get destination path. + * + * @return string + */ + public function getDestinationPath() + { + return $this->repository->config('paths.migration'); + } + + /** + * Get source path. + * + * @return string + */ + public function getSourcePath() + { + return $this->migrator->getPath(); + } +} diff --git a/src/Publishing/Publisher.php b/src/Publishing/Publisher.php new file mode 100755 index 0000000..24384eb --- /dev/null +++ b/src/Publishing/Publisher.php @@ -0,0 +1,192 @@ +module = $module; + } + + /** + * Show the result message. + * + * @return self + */ + public function showMessage() + { + $this->showMessage = true; + + return $this; + } + + /** + * Hide the result message. + * + * @return self + */ + public function hideMessage() + { + $this->showMessage = false; + + return $this; + } + + /** + * Get module instance. + * + * @return \mpba\Modules\Module + */ + public function getModule() + { + return $this->module; + } + + /** + * Set modules repository instance. + * + * @return $this + */ + public function setRepository(RepositoryInterface $repository) + { + $this->repository = $repository; + + return $this; + } + + /** + * Get modules repository instance. + * + * @return mpba\Modules\Contracts\RepositoryInterface + */ + public function getRepository() + { + return $this->repository; + } + + /** + * Set console instance. + * + * + * @return $this + */ + public function setConsole(Command $console) + { + $this->console = $console; + + return $this; + } + + /** + * Get console instance. + * + * @return \Illuminate\Console\Command + */ + public function getConsole() + { + return $this->console; + } + + /** + * Get laravel filesystem instance. + * + * @return \Illuminate\Filesystem\Filesystem + */ + public function getFilesystem() + { + return $this->repository->getFiles(); + } + + /** + * Get destination path. + * + * @return string + */ + abstract public function getDestinationPath(); + + /** + * Get source path. + * + * @return string + */ + abstract public function getSourcePath(); + + /** + * Publish something. + */ + public function publish() + { + if (! $this->console instanceof Command) { + $message = "The 'console' property must instance of \\Illuminate\\Console\\Command."; + + throw new \RuntimeException($message); + } + + if (! $this->getFilesystem()->isDirectory($sourcePath = $this->getSourcePath())) { + return; + } + + if (! $this->getFilesystem()->isDirectory($destinationPath = $this->getDestinationPath())) { + $this->getFilesystem()->makeDirectory($destinationPath, 0775, true); + } + + if ($this->getFilesystem()->copyDirectory($sourcePath, $destinationPath)) { + if ($this->showMessage === true) { + $this->console->line("Published: {$this->module->getStudlyName()}"); + } + } else { + $this->console->error($this->error); + } + } +} diff --git a/src/Routing/Controller.php b/src/Routing/Controller.php new file mode 100755 index 0000000..80dfae1 --- /dev/null +++ b/src/Routing/Controller.php @@ -0,0 +1,13 @@ +path = $config['path']; + $this->generate = $config['generate']; + $this->namespace = $config['namespace'] ?? $this->convertPathToNamespace($config['path']); + + return; + } + $this->path = $config; + $this->generate = (bool) $config; + $this->namespace = $config; + } + + public function getPath() + { + return $this->path; + } + + public function generate(): bool + { + return $this->generate; + } + + public function getNamespace() + { + return $this->namespace; + } + + private function convertPathToNamespace($path) + { + return str_replace('/', '\\', $path); + } +} diff --git a/src/Support/Migrations/NameParser.php b/src/Support/Migrations/NameParser.php new file mode 100755 index 0000000..bb078f7 --- /dev/null +++ b/src/Support/Migrations/NameParser.php @@ -0,0 +1,199 @@ + [ + 'create', + 'make', + ], + 'delete' => [ + 'delete', + 'remove', + ], + 'add' => [ + 'add', + 'update', + 'append', + 'insert', + ], + 'drop' => [ + 'destroy', + 'drop', + ], + ]; + + /** + * The constructor. + * + * @param string $name + */ + public function __construct($name) + { + $this->name = $name; + $this->data = $this->fetchData(); + } + + /** + * Get original migration name. + * + * @return string + */ + public function getOriginalName() + { + return $this->name; + } + + /** + * Get schema type or action. + * + * @return string + */ + public function getAction() + { + return head($this->data); + } + + /** + * Get the table will be used. + * + * @return string + */ + public function getTableName() + { + $matches = array_reverse($this->getMatches()); + + return array_shift($matches); + } + + /** + * Get matches data from regex. + * + * @return array + */ + public function getMatches() + { + preg_match($this->getPattern(), $this->name, $matches); + + return $matches; + } + + /** + * Get name pattern. + * + * @return string + */ + public function getPattern() + { + switch ($action = $this->getAction()) { + case 'add': + case 'append': + case 'update': + case 'insert': + return "/{$action}_(.*)_to_(.*)_table/"; + break; + + case 'delete': + case 'remove': + case 'alter': + return "/{$action}_(.*)_from_(.*)_table/"; + break; + + default: + return "/{$action}_(.*)_table/"; + break; + } + } + + /** + * Fetch the migration name to an array data. + * + * @return array + */ + protected function fetchData() + { + return explode('_', $this->name); + } + + /** + * Get the array data. + * + * @return array + */ + public function getData() + { + return $this->data; + } + + /** + * Determine whether the given type is same with the current schema action or type. + * + * + * @return bool + */ + public function is($type) + { + return $type === $this->getAction(); + } + + /** + * Determine whether the current schema action is a adding action. + * + * @return bool + */ + public function isAdd() + { + return in_array($this->getAction(), $this->actions['add']); + } + + /** + * Determine whether the current schema action is a deleting action. + * + * @return bool + */ + public function isDelete() + { + return in_array($this->getAction(), $this->actions['delete']); + } + + /** + * Determine whether the current schema action is a creating action. + * + * @return bool + */ + public function isCreate() + { + return in_array($this->getAction(), $this->actions['create']); + } + + /** + * Determine whether the current schema action is a dropping action. + * + * @return bool + */ + public function isDrop() + { + return in_array($this->getAction(), $this->actions['drop']); + } +} diff --git a/src/Support/Migrations/SchemaParser.php b/src/Support/Migrations/SchemaParser.php new file mode 100755 index 0000000..0f156f6 --- /dev/null +++ b/src/Support/Migrations/SchemaParser.php @@ -0,0 +1,276 @@ + 'rememberToken()', + 'soft_delete' => 'softDeletes()', + ]; + + /** + * The migration schema. + * + * @var string + */ + protected $schema; + + /** + * The relationship keys. + * + * @var array + */ + protected $relationshipKeys = [ + 'belongsTo', + ]; + + /** + * Create new instance. + * + * @param string|null $schema + */ + public function __construct($schema = null) + { + $this->schema = $schema; + } + + /** + * Parse a string to array of formatted schema. + * + * @param string $schema + * @return array + */ + public function parse($schema) + { + $this->schema = $schema; + + $parsed = []; + + foreach ($this->getSchemas() as $schemaArray) { + $column = $this->getColumn($schemaArray); + + $attributes = $this->getAttributes($column, $schemaArray); + + $parsed[$column] = $attributes; + } + + return $parsed; + } + + /** + * Get array of schema. + * + * @return array + */ + public function getSchemas() + { + if (is_null($this->schema)) { + return []; + } + + return explode(',', str_replace(' ', '', $this->schema)); + } + + /** + * Convert string migration to array. + * + * @return array + */ + public function toArray() + { + return $this->parse($this->schema); + } + + /** + * Render the migration to formatted script. + * + * @return string + */ + public function render() + { + $results = ''; + + foreach ($this->toArray() as $column => $attributes) { + $results .= $this->createField($column, $attributes); + } + + return $results; + } + + /** + * Render up migration fields. + * + * @return string + */ + public function up() + { + return $this->render(); + } + + /** + * Render down migration fields. + * + * @return string + */ + public function down() + { + $results = ''; + + foreach ($this->toArray() as $column => $attributes) { + $attributes = [head($attributes)]; + $results .= $this->createField($column, $attributes, 'remove'); + } + + return $results; + } + + /** + * Create field. + * + * @param string $column + * @param array $attributes + * @param string $type + * @return string + */ + public function createField($column, $attributes, $type = 'add') + { + $results = "\t\t\t".'$table'; + + foreach ($attributes as $key => $field) { + if (in_array($column, $this->relationshipKeys)) { + $results .= $this->addRelationColumn($key, $field, $column); + } else { + $results .= $this->{"{$type}Column"}($key, $field, $column); + } + } + + return $results.';'.PHP_EOL; + } + + /** + * Add relation column. + * + * @param int $key + * @param string $field + * @param string $column + * @return string + */ + protected function addRelationColumn($key, $field, $column) + { + if ($key === 0) { + $relatedColumn = Str::snake(class_basename($field)).'_id'; + + return "->integer('{$relatedColumn}')->unsigned();".PHP_EOL."\t\t\t"."\$table->foreign('{$relatedColumn}')"; + } + if ($key === 1) { + return "->references('{$field}')"; + } + if ($key === 2) { + return "->on('{$field}')"; + } + if (Str::contains($field, '(')) { + return '->'.$field; + } + + return '->'.$field.'()'; + } + + /** + * Format field to script. + * + * @param int $key + * @param string $field + * @param string $column + * @return string + */ + protected function addColumn($key, $field, $column) + { + if ($this->hasCustomAttribute($column)) { + return '->'.$field; + } + + if ($key == 0) { + return '->'.$field."('".$column."')"; + } + + if (Str::contains($field, '(')) { + return '->'.$field; + } + + return '->'.$field.'()'; + } + + /** + * Format field to script. + * + * @param int $key + * @param string $field + * @param string $column + * @return string + */ + protected function removeColumn($key, $field, $column) + { + if ($this->hasCustomAttribute($column)) { + return '->'.$field; + } + + return '->dropColumn('."'".$column."')"; + } + + /** + * Get column name from schema. + * + * @param string $schema + * @return string + */ + public function getColumn($schema) + { + return Arr::get(explode(':', $schema), 0); + } + + /** + * Get column attributes. + * + * @param string $column + * @param string $schema + * @return array + */ + public function getAttributes($column, $schema) + { + $fields = str_replace($column.':', '', $schema); + + return $this->hasCustomAttribute($column) ? $this->getCustomAttribute($column) : explode(':', $fields); + } + + /** + * Determine whether the given column is exist in customAttributes array. + * + * @param string $column + * @return bool + */ + public function hasCustomAttribute($column) + { + return array_key_exists($column, $this->customAttributes); + } + + /** + * Get custom attributes value. + * + * @param string $column + * @return array + */ + public function getCustomAttribute($column) + { + return (array) $this->customAttributes[$column]; + } +} diff --git a/src/Support/Stub.php b/src/Support/Stub.php new file mode 100755 index 0000000..02a50ba --- /dev/null +++ b/src/Support/Stub.php @@ -0,0 +1,165 @@ +path = $path; + $this->replaces = $replaces; + } + + /** + * Create new self instance. + * + * @param string $path + * @return self + */ + public static function create($path, array $replaces = []) + { + return new static($path, $replaces); + } + + /** + * Set stub path. + * + * @param string $path + * @return self + */ + public function setPath($path) + { + $this->path = $path; + + return $this; + } + + /** + * Get stub path. + * + * @return string + */ + public function getPath() + { + $path = static::getBasePath().$this->path; + + return file_exists($path) ? $path : __DIR__.'/../Commands/stubs'.$this->path; + } + + /** + * Set base path. + * + * @param string $path + */ + public static function setBasePath($path) + { + static::$basePath = $path; + } + + /** + * Get base path. + * + * @return string|null + */ + public static function getBasePath() + { + return static::$basePath; + } + + /** + * Get stub contents. + * + * @return mixed|string + */ + public function getContents() + { + $contents = file_get_contents($this->getPath()); + + foreach ($this->replaces as $search => $replace) { + $contents = str_replace('$'.strtoupper($search).'$', $replace, $contents); + } + + return $contents; + } + + /** + * Get stub contents. + * + * @return string + */ + public function render() + { + return $this->getContents(); + } + + /** + * Save stub to specific path. + * + * @param string $path + * @param string $filename + * @return bool + */ + public function saveTo($path, $filename) + { + return file_put_contents($path.'/'.$filename, $this->getContents()); + } + + /** + * Set replacements array. + * + * + * @return $this + */ + public function replace(array $replaces = []) + { + $this->replaces = $replaces; + + return $this; + } + + /** + * Get replacements. + * + * @return array + */ + public function getReplaces() + { + return $this->replaces; + } + + /** + * Handle magic method __toString. + * + * @return string + */ + public function __toString() + { + return $this->render(); + } +} diff --git a/src/Traits/CanClearModulesCache.php b/src/Traits/CanClearModulesCache.php new file mode 100755 index 0000000..b569ff7 --- /dev/null +++ b/src/Traits/CanClearModulesCache.php @@ -0,0 +1,16 @@ +forget(config('modules.cache.key')); + } + } +} diff --git a/src/Traits/MigrationLoaderTrait.php b/src/Traits/MigrationLoaderTrait.php new file mode 100755 index 0000000..3ba8712 --- /dev/null +++ b/src/Traits/MigrationLoaderTrait.php @@ -0,0 +1,32 @@ +laravel['modules']->getModulePath($module).$this->getMigrationGeneratorPath(); + + $files = $this->laravel['files']->glob($path.'/*_*.php'); + + foreach ($files as $file) { + $this->laravel['files']->requireOnce($file); + } + } + + /** + * Get migration generator path. + * + * @return string + */ + protected function getMigrationGeneratorPath() + { + return $this->laravel['modules']->config('paths.generator.migration'); + } +} diff --git a/src/Traits/ModuleCommandTrait.php b/src/Traits/ModuleCommandTrait.php new file mode 100755 index 0000000..f483d2a --- /dev/null +++ b/src/Traits/ModuleCommandTrait.php @@ -0,0 +1,20 @@ +argument('module') ?: app('modules')->getUsedNow(); + + $module = app('modules')->findOrFail($module); + + return $module->getStudlyName(); + } +} diff --git a/src/database/migrations/2026_04_20_000000_create_modules_table.php b/src/database/migrations/2026_04_20_000000_create_modules_table.php new file mode 100644 index 0000000..52c131b --- /dev/null +++ b/src/database/migrations/2026_04_20_000000_create_modules_table.php @@ -0,0 +1,33 @@ +id(); + $table->string('module')->unique(); + $table->boolean('enabled')->default(true); + $table->timestamps(); + }); + } + + /** + * Reverse the migrations. + * + * @return void + */ + public function down(): void + { + Schema::dropIfExists('module_statuses'); + } +}; diff --git a/src/database/migrations/ModuleMigrator.php b/src/database/migrations/ModuleMigrator.php new file mode 100644 index 0000000..5bca510 --- /dev/null +++ b/src/database/migrations/ModuleMigrator.php @@ -0,0 +1,33 @@ +id(); + $table->string('module')->unique(); + $table->boolean('enabled')->default(true); + $table->timestamps(); + }); + } + + /** + * Reverse the migrations. + * + * @return void + */ + public function down(): void + { + Schema::dropIfExists('module_statuses'); + } +}; diff --git a/src/helpers.php b/src/helpers.php new file mode 100755 index 0000000..0c59549 --- /dev/null +++ b/src/helpers.php @@ -0,0 +1,36 @@ +find($name); + + return $module->getPath().($path ? DIRECTORY_SEPARATOR.$path : $path); + } +} + +if (! function_exists('config_path')) { + /** + * Get the configuration path. + * + * @param string $path + * @return string + */ + function config_path($path = '') + { + return app()->basePath().'/config'.($path ? DIRECTORY_SEPARATOR.$path : $path); + } +} + +if (! function_exists('public_path')) { + /** + * Get the path to the public folder. + * + * @param string $path + * @return string + */ + function public_path($path = '') + { + return app()->make('path.public').($path ? DIRECTORY_SEPARATOR.ltrim($path, DIRECTORY_SEPARATOR) : $path); + } +}