From 178cb89ce6e80bf91c4aa155cd4cb907ab5f595a Mon Sep 17 00:00:00 2001 From: Sam Maosa Date: Sat, 6 Apr 2024 12:37:59 +0300 Subject: [PATCH 1/2] Finished the basic architecture of Module Generation and Registration - Package can install itself and make all the necessary configurations to register modules - Package can generate the basic skeleton of a module - Package can activate a module by registering it as a local composer package - Package can deactivate a module uninstalling it using composer --- .github/FUNDING.yml | 2 +- .github/ISSUE_TEMPLATE/config.yml | 6 +- CHANGELOG.md | 2 +- LICENSE.md | 2 +- README.md | 39 +- composer.json | 29 +- config/modular.php | 38 ++ config/skeleton.php | 6 - configure.php | 366 ------------------ database/factories/ModelFactory.php | 2 +- ...php.stub => create_modular_table.php.stub} | 2 +- phpunit.xml.dist | 2 +- src/Commands/ActivateModuleCommand.php | 31 ++ src/Commands/DeactivateModuleCommand.php | 30 ++ src/Commands/MakeModuleCommand.php | 131 +++++++ src/Commands/SkeletonCommand.php | 19 - src/Facades/Modular.php | 16 + src/Facades/Skeleton.php | 16 - src/Modular.php | 14 + src/ModularServiceProvider.php | 161 ++++++++ src/Skeleton.php | 7 - src/SkeletonServiceProvider.php | 25 -- src/Support/Concerns/CanManipulateFiles.php | 92 +++++ stubs/cast.inbound.stub | 19 + stubs/cast.stub | 29 ++ stubs/class.invokable.stub | 22 ++ stubs/class.stub | 14 + stubs/console.stub | 30 ++ stubs/controller.api.stub | 49 +++ stubs/controller.invokable.stub | 17 + stubs/controller.model.api.stub | 50 +++ stubs/controller.model.stub | 66 ++++ stubs/controller.nested.api.stub | 51 +++ stubs/controller.nested.singleton.api.stub | 43 ++ stubs/controller.nested.singleton.stub | 59 +++ stubs/controller.nested.stub | 67 ++++ stubs/controller.plain.stub | 11 + stubs/controller.singleton.api.stub | 41 ++ stubs/controller.singleton.stub | 57 +++ stubs/controller.stub | 65 ++++ stubs/enum.backed.stub | 8 + stubs/enum.stub | 8 + stubs/event.stub | 36 ++ stubs/factory.stub | 23 ++ stubs/job.queued.stub | 30 ++ stubs/job.stub | 26 ++ stubs/listener.queued.stub | 27 ++ stubs/listener.stub | 25 ++ stubs/listener.typed.queued.stub | 28 ++ stubs/listener.typed.stub | 26 ++ stubs/mail.stub | 53 +++ stubs/markdown-mail.stub | 53 +++ stubs/markdown-notification.stub | 51 +++ stubs/middleware.stub | 20 + stubs/migration.create.stub | 27 ++ stubs/migration.stub | 24 ++ stubs/migration.update.stub | 28 ++ stubs/model.pivot.stub | 10 + stubs/model.stub | 11 + stubs/module.provider.stub | 89 +++++ stubs/notification.stub | 54 +++ stubs/observer.plain.stub | 8 + stubs/observer.stub | 48 +++ stubs/policy.plain.stub | 16 + stubs/policy.stub | 66 ++++ stubs/provider.stub | 24 ++ stubs/request.stub | 28 ++ stubs/resource-collection.stub | 19 + stubs/resource.stub | 19 + stubs/rule.stub | 19 + stubs/scope.stub | 18 + stubs/seeder.stub | 17 + stubs/test.stub | 20 + stubs/test.unit.stub | 16 + stubs/trait.stub | 8 + stubs/view-component.stub | 26 ++ tests/Pest.php | 2 +- tests/TestCase.php | 10 +- 78 files changed, 2257 insertions(+), 492 deletions(-) create mode 100644 config/modular.php delete mode 100644 config/skeleton.php delete mode 100644 configure.php rename database/migrations/{create_skeleton_table.php.stub => create_modular_table.php.stub} (78%) create mode 100644 src/Commands/ActivateModuleCommand.php create mode 100644 src/Commands/DeactivateModuleCommand.php create mode 100644 src/Commands/MakeModuleCommand.php delete mode 100644 src/Commands/SkeletonCommand.php create mode 100644 src/Facades/Modular.php delete mode 100644 src/Facades/Skeleton.php create mode 100755 src/Modular.php create mode 100644 src/ModularServiceProvider.php delete mode 100755 src/Skeleton.php delete mode 100644 src/SkeletonServiceProvider.php create mode 100644 src/Support/Concerns/CanManipulateFiles.php create mode 100644 stubs/cast.inbound.stub create mode 100644 stubs/cast.stub create mode 100644 stubs/class.invokable.stub create mode 100644 stubs/class.stub create mode 100644 stubs/console.stub create mode 100644 stubs/controller.api.stub create mode 100644 stubs/controller.invokable.stub create mode 100644 stubs/controller.model.api.stub create mode 100644 stubs/controller.model.stub create mode 100644 stubs/controller.nested.api.stub create mode 100644 stubs/controller.nested.singleton.api.stub create mode 100644 stubs/controller.nested.singleton.stub create mode 100644 stubs/controller.nested.stub create mode 100644 stubs/controller.plain.stub create mode 100644 stubs/controller.singleton.api.stub create mode 100644 stubs/controller.singleton.stub create mode 100644 stubs/controller.stub create mode 100644 stubs/enum.backed.stub create mode 100644 stubs/enum.stub create mode 100644 stubs/event.stub create mode 100644 stubs/factory.stub create mode 100644 stubs/job.queued.stub create mode 100644 stubs/job.stub create mode 100644 stubs/listener.queued.stub create mode 100644 stubs/listener.stub create mode 100644 stubs/listener.typed.queued.stub create mode 100644 stubs/listener.typed.stub create mode 100644 stubs/mail.stub create mode 100644 stubs/markdown-mail.stub create mode 100644 stubs/markdown-notification.stub create mode 100644 stubs/middleware.stub create mode 100644 stubs/migration.create.stub create mode 100644 stubs/migration.stub create mode 100644 stubs/migration.update.stub create mode 100644 stubs/model.pivot.stub create mode 100644 stubs/model.stub create mode 100644 stubs/module.provider.stub create mode 100644 stubs/notification.stub create mode 100644 stubs/observer.plain.stub create mode 100644 stubs/observer.stub create mode 100644 stubs/policy.plain.stub create mode 100644 stubs/policy.stub create mode 100644 stubs/provider.stub create mode 100644 stubs/request.stub create mode 100644 stubs/resource-collection.stub create mode 100644 stubs/resource.stub create mode 100644 stubs/rule.stub create mode 100644 stubs/scope.stub create mode 100644 stubs/seeder.stub create mode 100644 stubs/test.stub create mode 100644 stubs/test.unit.stub create mode 100644 stubs/trait.stub create mode 100644 stubs/view-component.stub diff --git a/.github/FUNDING.yml b/.github/FUNDING.yml index c68765b..ad5d720 100644 --- a/.github/FUNDING.yml +++ b/.github/FUNDING.yml @@ -1 +1 @@ -github: :vendor_name +github: Savannabits diff --git a/.github/ISSUE_TEMPLATE/config.yml b/.github/ISSUE_TEMPLATE/config.yml index 96701be..19aad58 100644 --- a/.github/ISSUE_TEMPLATE/config.yml +++ b/.github/ISSUE_TEMPLATE/config.yml @@ -1,11 +1,11 @@ blank_issues_enabled: false contact_links: - name: Ask a question - url: https://github.com/:vendor_name/:package_name/discussions/new?category=q-a + url: https://github.com/Savannabits/modular/discussions/new?category=q-a about: Ask the community for help - name: Request a feature - url: https://github.com/:vendor_name/:package_name/discussions/new?category=ideas + url: https://github.com/Savannabits/modular/discussions/new?category=ideas about: Share ideas for new features - name: Report a security issue - url: https://github.com/:vendor_name/:package_name/security/policy + url: https://github.com/Savannabits/modular/security/policy about: Learn how to notify us for sensitive bugs diff --git a/CHANGELOG.md b/CHANGELOG.md index 87b3242..f53b50e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,3 @@ # Changelog -All notable changes to `:package_name` will be documented in this file. +All notable changes to `modular` will be documented in this file. diff --git a/LICENSE.md b/LICENSE.md index 58c9ad4..d40570e 100644 --- a/LICENSE.md +++ b/LICENSE.md @@ -1,6 +1,6 @@ The MIT License (MIT) -Copyright (c) :vendor_name +Copyright (c) Savannabits Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal diff --git a/README.md b/README.md index 375da96..d3ad5b2 100644 --- a/README.md +++ b/README.md @@ -1,24 +1,15 @@ -# :package_description - -[![Latest Version on Packagist](https://img.shields.io/packagist/v/:vendor_slug/:package_slug.svg?style=flat-square)](https://packagist.org/packages/:vendor_slug/:package_slug) -[![GitHub Tests Action Status](https://img.shields.io/github/actions/workflow/status/:vendor_slug/:package_slug/run-tests.yml?branch=main&label=tests&style=flat-square)](https://github.com/:vendor_slug/:package_slug/actions?query=workflow%3Arun-tests+branch%3Amain) -[![GitHub Code Style Action Status](https://img.shields.io/github/actions/workflow/status/:vendor_slug/:package_slug/fix-php-code-style-issues.yml?branch=main&label=code%20style&style=flat-square)](https://github.com/:vendor_slug/:package_slug/actions?query=workflow%3A"Fix+PHP+code+style+issues"+branch%3Amain) -[![Total Downloads](https://img.shields.io/packagist/dt/:vendor_slug/:package_slug.svg?style=flat-square)](https://packagist.org/packages/:vendor_slug/:package_slug) - ---- -This repo can be used to scaffold a Laravel package. Follow these steps to get started: - -1. Press the "Use this template" button at the top of this repo to create a new repo with the contents of this skeleton. -2. Run "php ./configure.php" to run a script that will replace all placeholders throughout all the files. -3. Have fun creating your package. -4. If you need help creating a package, consider picking up our Laravel Package Training video course. ---- - +# Organize your Laravel code into Modules + +[![Latest Version on Packagist](https://img.shields.io/packagist/v/savannabits/modular.svg?style=flat-square)](https://packagist.org/packages/savannabits/modular) +[![GitHub Tests Action Status](https://img.shields.io/github/actions/workflow/status/savannabits/modular/run-tests.yml?branch=main&label=tests&style=flat-square)](https://github.com/savannabits/modular/actions?query=workflow%3Arun-tests+branch%3Amain) +[![GitHub Code Style Action Status](https://img.shields.io/github/actions/workflow/status/savannabits/modular/fix-php-code-style-issues.yml?branch=main&label=code%20style&style=flat-square)](https://github.com/savannabits/modular/actions?query=workflow%3A"Fix+PHP+code+style+issues"+branch%3Amain) +[![Total Downloads](https://img.shields.io/packagist/dt/savannabits/modular.svg?style=flat-square)](https://packagist.org/packages/savannabits/modular) + This is where your description should go. Limit it to a paragraph or two. Consider adding a small example. ## Support us -[](https://spatie.be/github-ad-click/:package_name) +[](https://spatie.be/github-ad-click/modular) We invest a lot of resources into creating [best in class open source packages](https://spatie.be/open-source). You can support us by [buying one of our paid products](https://spatie.be/open-source/support-us). @@ -29,20 +20,20 @@ We highly appreciate you sending us a postcard from your hometown, mentioning wh You can install the package via composer: ```bash -composer require :vendor_slug/:package_slug +composer require savannabits/modular ``` You can publish and run the migrations with: ```bash -php artisan vendor:publish --tag=":package_slug-migrations" +php artisan vendor:publish --tag="modular-migrations" php artisan migrate ``` You can publish the config file with: ```bash -php artisan vendor:publish --tag=":package_slug-config" +php artisan vendor:publish --tag="modular-config" ``` This is the contents of the published config file: @@ -55,14 +46,14 @@ return [ Optionally, you can publish the views using ```bash -php artisan vendor:publish --tag=":package_slug-views" +php artisan vendor:publish --tag="modular-views" ``` ## Usage ```php -$variable = new VendorName\Skeleton(); -echo $variable->echoPhrase('Hello, VendorName!'); +$modular = new Savannabits\Modular(); +echo $modular->echoPhrase('Hello, Savannabits!'); ``` ## Testing @@ -85,7 +76,7 @@ Please review [our security policy](../../security/policy) on how to report secu ## Credits -- [:author_name](https://github.com/:author_username) +- [Sam Maosa](https://github.com/coolsam726) - [All Contributors](../../contributors) ## License diff --git a/composer.json b/composer.json index 65e9908..8b52e6b 100644 --- a/composer.json +++ b/composer.json @@ -1,24 +1,25 @@ { - "name": ":vendor_slug/:package_slug", - "description": ":package_description", + "name": "savannabits/modular", + "description": "Organize your Laravel code into Modules", "keywords": [ - ":vendor_name", + "Savannabits", "laravel", - ":package_slug" + "modular" ], - "homepage": "https://github.com/:vendor_slug/:package_slug", + "homepage": "https://github.com/savannabits/modular", "license": "MIT", "authors": [ { - "name": ":author_name", - "email": "author@domain.com", + "name": "Sam Maosa", + "email": "maosa.sam@gmail.com", "role": "Developer" } ], "require": { "php": "^8.2", "spatie/laravel-package-tools": "^1.16", - "illuminate/contracts": "^10.0||^11.0" + "illuminate/contracts": "^10.0||^11.0", + "wikimedia/composer-merge-plugin": "^2.1" }, "require-dev": { "laravel/pint": "^1.14", @@ -35,19 +36,19 @@ }, "autoload": { "psr-4": { - "VendorName\\Skeleton\\": "src/", - "VendorName\\Skeleton\\Database\\Factories\\": "database/factories/" + "Savannabits\\Modular\\": "src/", + "Savannabits\\Modular\\Database\\Factories\\": "database/factories/" } }, "autoload-dev": { "psr-4": { - "VendorName\\Skeleton\\Tests\\": "tests/", + "Savannabits\\Modular\\Tests\\": "tests/", "Workbench\\App\\": "workbench/app/" } }, "scripts": { "post-autoload-dump": "@composer run prepare", - "clear": "@php vendor/bin/testbench package:purge-skeleton --ansi", + "clear": "@php vendor/bin/testbench package:purge-modular --ansi", "prepare": "@php vendor/bin/testbench package:discover --ansi", "build": [ "@composer run prepare", @@ -73,10 +74,10 @@ "extra": { "laravel": { "providers": [ - "VendorName\\Skeleton\\SkeletonServiceProvider" + "Savannabits\\Modular\\ModularServiceProvider" ], "aliases": { - "Skeleton": "VendorName\\Skeleton\\Facades\\Skeleton" + "Modular": "Savannabits\\Modular\\Facades\\Modular" } } }, diff --git a/config/modular.php b/config/modular.php new file mode 100644 index 0000000..69e005b --- /dev/null +++ b/config/modular.php @@ -0,0 +1,38 @@ + 'modules', + 'namespace' => 'Modules', + 'vendor' => 'modular', + 'directory_tree' => [ + 'bootstrap', + 'bootstrap/cache', + 'config', + 'database', + 'database/migrations', + 'database/seeders', + 'database/factories', + 'public', + 'resources', + 'resources/lang', + 'resources/views', + 'resources/js', + 'resources/css', + 'routes', + 'src', + 'src/Console', + 'src/Console/Commands', + 'src/Exceptions', + 'src/Facades', + 'src/Http', + 'src/Http/Controllers', + 'src/Models', + 'src/Policies', + 'src/Providers', + 'src/Support/Concerns', + 'src/Support/Contracts', + 'storage', + 'tests', + ], +]; diff --git a/config/skeleton.php b/config/skeleton.php deleted file mode 100644 index 7e74186..0000000 --- a/config/skeleton.php +++ /dev/null @@ -1,6 +0,0 @@ - $version) { - if (in_array($name, $names, true)) { - unset($data['require-dev'][$name]); - } - } - - file_put_contents(__DIR__.'/composer.json', json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE)); -} - -function remove_composer_script($scriptName) -{ - $data = json_decode(file_get_contents(__DIR__.'/composer.json'), true); - - foreach ($data['scripts'] as $name => $script) { - if ($scriptName === $name) { - unset($data['scripts'][$name]); - break; - } - } - - file_put_contents(__DIR__.'/composer.json', json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE)); -} - -function remove_readme_paragraphs(string $file): void -{ - $contents = file_get_contents($file); - - file_put_contents( - $file, - preg_replace('/.*/s', '', $contents) ?: $contents - ); -} - -function safeUnlink(string $filename) -{ - if (file_exists($filename) && is_file($filename)) { - unlink($filename); - } -} - -function determineSeparator(string $path): string -{ - return str_replace('/', DIRECTORY_SEPARATOR, $path); -} - -function replaceForWindows(): array -{ - return preg_split('/\\r\\n|\\r|\\n/', run('dir /S /B * | findstr /v /i .git\ | findstr /v /i vendor | findstr /v /i '.basename(__FILE__).' | findstr /r /i /M /F:/ ":author :vendor :package VendorName skeleton migration_table_name vendor_name vendor_slug author@domain.com"')); -} - -function replaceForAllOtherOSes(): array -{ - return explode(PHP_EOL, run('grep -E -r -l -i ":author|:vendor|:package|VendorName|skeleton|migration_table_name|vendor_name|vendor_slug|author@domain.com" --exclude-dir=vendor ./* ./.github/* | grep -v '.basename(__FILE__))); -} - -function getGitHubApiEndpoint(string $endpoint): ?stdClass -{ - try { - $curl = curl_init("https://api.github.com/{$endpoint}"); - curl_setopt_array($curl, [ - CURLOPT_RETURNTRANSFER => true, - CURLOPT_FOLLOWLOCATION => true, - CURLOPT_HTTPGET => true, - CURLOPT_HTTPHEADER => [ - 'User-Agent: spatie-configure-script/1.0', - ], - ]); - - $response = curl_exec($curl); - $statusCode = curl_getinfo($curl, CURLINFO_HTTP_CODE); - - curl_close($curl); - - if ($statusCode === 200) { - return json_decode($response); - } - } catch (Exception $e) { - // ignore - } - - return null; -} - -function searchCommitsForGitHubUsername(): string -{ - $authorName = strtolower(trim(shell_exec('git config user.name'))); - - $committersRaw = shell_exec("git log --author='@users.noreply.github.com' --pretty='%an:%ae' --reverse"); - $committersLines = explode("\n", $committersRaw ?? ''); - $committers = array_filter(array_map(function ($line) use ($authorName) { - $line = trim($line); - [$name, $email] = explode(':', $line) + [null, null]; - - return [ - 'name' => $name, - 'email' => $email, - 'isMatch' => strtolower($name) === $authorName && ! str_contains($name, '[bot]'), - ]; - }, $committersLines), fn ($item) => $item['isMatch']); - - if (empty($committers)) { - return ''; - } - - $firstCommitter = reset($committers); - - return explode('@', $firstCommitter['email'])[0] ?? ''; -} - -function guessGitHubUsernameUsingCli() -{ - try { - if (preg_match('/ogged in to github\.com as ([a-zA-Z-_]+).+/', shell_exec('gh auth status -h github.com 2>&1'), $matches)) { - return $matches[1]; - } - } catch (Exception $e) { - // ignore - } - - return ''; -} - -function guessGitHubUsername(): string -{ - $username = searchCommitsForGitHubUsername(); - if (! empty($username)) { - return $username; - } - - $username = guessGitHubUsernameUsingCli(); - if (! empty($username)) { - return $username; - } - - // fall back to using the username from the git remote - $remoteUrl = shell_exec('git config remote.origin.url'); - $remoteUrlParts = explode('/', str_replace(':', '/', trim($remoteUrl))); - - return $remoteUrlParts[1] ?? ''; -} - -function guessGitHubVendorInfo($authorName, $username): array -{ - $remoteUrl = shell_exec('git config remote.origin.url'); - $remoteUrlParts = explode('/', str_replace(':', '/', trim($remoteUrl))); - - $response = getGitHubApiEndpoint("orgs/{$remoteUrlParts[1]}"); - - if ($response === null) { - return [$authorName, $username]; - } - - return [$response->name ?? $authorName, $response->login ?? $username]; -} - -$gitName = run('git config user.name'); -$authorName = ask('Author name', $gitName); - -$gitEmail = run('git config user.email'); -$authorEmail = ask('Author email', $gitEmail); -$authorUsername = ask('Author username', guessGitHubUsername()); - -$guessGitHubVendorInfo = guessGitHubVendorInfo($authorName, $authorUsername); - -$vendorName = ask('Vendor name', $guessGitHubVendorInfo[0]); -$vendorUsername = ask('Vendor username', $guessGitHubVendorInfo[1] ?? slugify($vendorName)); -$vendorSlug = slugify($vendorUsername); - -$vendorNamespace = str_replace('-', '', ucwords($vendorName)); -$vendorNamespace = ask('Vendor namespace', $vendorNamespace); - -$currentDirectory = getcwd(); -$folderName = basename($currentDirectory); - -$packageName = ask('Package name', $folderName); -$packageSlug = slugify($packageName); -$packageSlugWithoutPrefix = remove_prefix('laravel-', $packageSlug); - -$className = title_case($packageName); -$className = ask('Class name', $className); -$variableName = lcfirst($className); -$description = ask('Package description', "This is my package {$packageSlug}"); - -$usePhpStan = confirm('Enable PhpStan?', true); -$useLaravelPint = confirm('Enable Laravel Pint?', true); -$useDependabot = confirm('Enable Dependabot?', true); -$useLaravelRay = confirm('Use Ray for debugging?', true); -$useUpdateChangelogWorkflow = confirm('Use automatic changelog updater workflow?', true); - -writeln('------'); -writeln("Author : {$authorName} ({$authorUsername}, {$authorEmail})"); -writeln("Vendor : {$vendorName} ({$vendorSlug})"); -writeln("Package : {$packageSlug} <{$description}>"); -writeln("Namespace : {$vendorNamespace}\\{$className}"); -writeln("Class name : {$className}"); -writeln('---'); -writeln('Packages & Utilities'); -writeln('Use Laravel/Pint : '.($useLaravelPint ? 'yes' : 'no')); -writeln('Use Larastan/PhpStan : '.($usePhpStan ? 'yes' : 'no')); -writeln('Use Dependabot : '.($useDependabot ? 'yes' : 'no')); -writeln('Use Ray App : '.($useLaravelRay ? 'yes' : 'no')); -writeln('Use Auto-Changelog : '.($useUpdateChangelogWorkflow ? 'yes' : 'no')); -writeln('------'); - -writeln('This script will replace the above values in all relevant files in the project directory.'); - -if (! confirm('Modify files?', true)) { - exit(1); -} - -$files = (str_starts_with(strtoupper(PHP_OS), 'WIN') ? replaceForWindows() : replaceForAllOtherOSes()); - -foreach ($files as $file) { - replace_in_file($file, [ - ':author_name' => $authorName, - ':author_username' => $authorUsername, - 'author@domain.com' => $authorEmail, - ':vendor_name' => $vendorName, - ':vendor_slug' => $vendorSlug, - 'VendorName' => $vendorNamespace, - ':package_name' => $packageName, - ':package_slug' => $packageSlug, - ':package_slug_without_prefix' => $packageSlugWithoutPrefix, - 'Skeleton' => $className, - 'skeleton' => $packageSlug, - 'migration_table_name' => title_snake($packageSlug), - 'variable' => $variableName, - ':package_description' => $description, - ]); - - match (true) { - str_contains($file, determineSeparator('src/Skeleton.php')) => rename($file, determineSeparator('./src/'.$className.'.php')), - str_contains($file, determineSeparator('src/SkeletonServiceProvider.php')) => rename($file, determineSeparator('./src/'.$className.'ServiceProvider.php')), - str_contains($file, determineSeparator('src/Facades/Skeleton.php')) => rename($file, determineSeparator('./src/Facades/'.$className.'.php')), - str_contains($file, determineSeparator('src/Commands/SkeletonCommand.php')) => rename($file, determineSeparator('./src/Commands/'.$className.'Command.php')), - str_contains($file, determineSeparator('database/migrations/create_skeleton_table.php.stub')) => rename($file, determineSeparator('./database/migrations/create_'.title_snake($packageSlugWithoutPrefix).'_table.php.stub')), - str_contains($file, determineSeparator('config/skeleton.php')) => rename($file, determineSeparator('./config/'.$packageSlugWithoutPrefix.'.php')), - str_contains($file, 'README.md') => remove_readme_paragraphs($file), - default => [], - }; -} - -if (! $useLaravelPint) { - safeUnlink(__DIR__.'/.github/workflows/fix-php-code-style-issues.yml'); - safeUnlink(__DIR__.'/pint.json'); -} - -if (! $usePhpStan) { - safeUnlink(__DIR__.'/phpstan.neon.dist'); - safeUnlink(__DIR__.'/phpstan-baseline.neon'); - safeUnlink(__DIR__.'/.github/workflows/phpstan.yml'); - - remove_composer_deps([ - 'phpstan/extension-installer', - 'phpstan/phpstan-deprecation-rules', - 'phpstan/phpstan-phpunit', - 'larastan/larastan', - ]); - - remove_composer_script('phpstan'); -} - -if (! $useDependabot) { - safeUnlink(__DIR__.'/.github/dependabot.yml'); - safeUnlink(__DIR__.'/.github/workflows/dependabot-auto-merge.yml'); -} - -if (! $useLaravelRay) { - remove_composer_deps(['spatie/laravel-ray']); -} - -if (! $useUpdateChangelogWorkflow) { - safeUnlink(__DIR__.'/.github/workflows/update-changelog.yml'); -} - -confirm('Execute `composer install` and run tests?') && run('composer install && composer test'); - -confirm('Let this script delete itself?', true) && unlink(__FILE__); diff --git a/database/factories/ModelFactory.php b/database/factories/ModelFactory.php index c51604f..87dd0d3 100644 --- a/database/factories/ModelFactory.php +++ b/database/factories/ModelFactory.php @@ -1,6 +1,6 @@ id(); // add fields diff --git a/phpunit.xml.dist b/phpunit.xml.dist index 4c61042..8a3f2c4 100644 --- a/phpunit.xml.dist +++ b/phpunit.xml.dist @@ -16,7 +16,7 @@ backupStaticProperties="false" > - + tests diff --git a/src/Commands/ActivateModuleCommand.php b/src/Commands/ActivateModuleCommand.php new file mode 100644 index 0000000..c52903c --- /dev/null +++ b/src/Commands/ActivateModuleCommand.php @@ -0,0 +1,31 @@ +moduleName = Str::kebab($this->argument('name') ?? text('Enter the module name', 'e.g My Blog MyBlog, my-blog')); + $this->info("Activating module: $this->moduleName"); + $this->activateModule(); + } + + private function activateModule(): void + { + $moduleName = $this->moduleName; + $repoName = config('modular.vendor','modular').'/'.$moduleName; + Modular::execCommand('composer require '.$repoName.':@dev'); + Modular::execCommand("php artisan $moduleName:install"); + } +} diff --git a/src/Commands/DeactivateModuleCommand.php b/src/Commands/DeactivateModuleCommand.php new file mode 100644 index 0000000..7e85782 --- /dev/null +++ b/src/Commands/DeactivateModuleCommand.php @@ -0,0 +1,30 @@ +moduleName = Str::kebab($this->argument('name') ?? text('Enter the module name', 'e.g My Blog MyBlog, my-blog')); + $this->info("Activating module: $this->moduleName"); + $this->deactivateModule(); + } + + private function deactivateModule(): void + { + $moduleName = $this->moduleName; + $repoName = config('modular.vendor','modular').'/'.$moduleName; + Modular::execCommand("composer remove $repoName"); + } +} diff --git a/src/Commands/MakeModuleCommand.php b/src/Commands/MakeModuleCommand.php new file mode 100644 index 0000000..a026c7c --- /dev/null +++ b/src/Commands/MakeModuleCommand.php @@ -0,0 +1,131 @@ +argument('name') ?: text('Enter the module name', 'e.g My Blog MyBlog, my-blog'); + $this->moduleName = Str::of($name)->kebab()->toString(); + $this->moduleStudlyName = Str::of($name)->studly()->toString(); + $this->moduleTitle = Str::of($name)->kebab()->title()->replace('-', ' ')->toString(); + $this->moduleNamespace = config('modular.namespace') . '\\' . Str::of($name)->studly()->toString(); + $this->modulePath = config('modular.path') . '/' . $this->moduleName; + $this->info("Creating module: $this->moduleName in $this->modulePath"); + + $this->generateModuleDirectories(); + $this->generateModuleFiles(); + $this->installModule(); + } + + private function generateModuleDirectories(): bool + { + $directories = config('modular.directory_tree'); + if (!count($directories)) { + $this->error('No directories found in the configuration file'); + return false; + } + foreach ($directories as $directory) { + $path = $this->modulePath . '/' . ltrim($directory,'/'); + if (!is_dir($path)) { + mkdir($path, 0775, true); + $this->info("Created directory: $path"); + } + } + $this->info('Module directories created successfully'); + return true; + } + + private function generateModuleFiles(): void + { + $this->generateModuleComposerFile(); + try { + $this->generateModuleServiceProvider(); + } catch (FileNotFoundException|NotFoundExceptionInterface|ContainerExceptionInterface $e) { + $this->error($e->getMessage()); + } +// $this->generateModuleFacade(); + } + + private function generateModuleComposerFile(): void + { + $composerJson = [ + 'name' => config('modular.vendor') . '/' . $this->moduleName, + 'type' => 'library', + 'description' => $this->moduleTitle . ' module', + 'require' => [ + 'php' => '^8.2', + ], + 'autoload' => [ + 'psr-4' => [ + $this->moduleNamespace . '\\' => 'src/', + $this->moduleNamespace . '\\Database\\Factories\\' => 'database/factories/', + $this->moduleNamespace . '\\Database\\Seeders\\' => 'database/seeders/', + ], + ], + 'autoload-dev' => [ + 'psr-4' => [ + $this->moduleNamespace . '\\Tests\\' => 'tests/', + ], + ], + 'config' => [ + 'sort-packages' => true, + 'allow-plugins' => [ + 'pestphp/pest-plugin' => true, + 'phpstan/extension-installer' => true, + ], + ], + 'extra' => [ + 'laravel' => [ + 'providers' => [ + $this->moduleNamespace . '\\' . $this->moduleStudlyName . 'ServiceProvider', + ], + ], + ], + ]; + $composerJsonPath = $this->modulePath . '/composer.json'; + file_put_contents($composerJsonPath, json_encode($composerJson, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES)); + $this->info("Created composer.json file: $composerJsonPath"); + } + + /** + * @throws ContainerExceptionInterface + * @throws FileNotFoundException + * @throws NotFoundExceptionInterface + */ + private function generateModuleServiceProvider(): void + { + $path = $this->modulePath . '/src/' . $this->moduleStudlyName . 'ServiceProvider.php'; + $namespace = $this->moduleNamespace; + $class = $this->moduleStudlyName . 'ServiceProvider'; + $this->copyStubToApp('module.provider', $path, [ + 'class' => $class, + 'namespace' => $namespace, + 'name' => $this->moduleName, + ]); + } + + private function installModule(): void + { + $this->comment('Activating the new Module'); + $this->call('modular:activate', ['name' => $this->moduleName]); + } +} diff --git a/src/Commands/SkeletonCommand.php b/src/Commands/SkeletonCommand.php deleted file mode 100644 index 3e5f628..0000000 --- a/src/Commands/SkeletonCommand.php +++ /dev/null @@ -1,19 +0,0 @@ -comment('All done'); - - return self::SUCCESS; - } -} diff --git a/src/Facades/Modular.php b/src/Facades/Modular.php new file mode 100644 index 0000000..c106865 --- /dev/null +++ b/src/Facades/Modular.php @@ -0,0 +1,16 @@ +name(static::$name) + ->hasConfigFile('modular') + ->hasViews(static::$viewNamespace) + ->hasCommands($this->getCommands()) + ->hasInstallCommand(function (InstallCommand $command) { + // get repo name from composer.json + $name = json_decode(file_get_contents(base_path('composer.json')))?->name; + $command + ->askToStarRepoOnGitHub($name) + ->startWith(fn (InstallCommand $command) => $this->installationSteps($command)); + }) + ; + $this->mergeConfigFrom($this->package->basePath('/../config/modular.php'), 'modular'); + } + + private function configureComposerMerge(InstallCommand $command): void + { + $command->comment('Configuring Composer merge plugin:'); + $composerJson = json_decode(file_get_contents(base_path('composer.json')), true); + // Add the modules repositories into compose if they don't exist + if (!isset($composerJson['repositories'])){ + $composerJson['repositories'] = []; + } + if (!collect($composerJson['repositories'])->contains(fn ($repo) => $repo['type'] === 'path' && $repo['url'] === config('modular.path').'/*')) { + $composerJson['repositories'][] = [ + 'type' => 'path', + 'url' => config('modular.path').'/*', + 'options' => [ + 'symlink' => true, + ], + ]; + } + if (!isset($composerJson['extra']['merge-plugin'])) { + $composerJson['extra']['merge-plugin'] = [ + 'include' => [ + 'modules/*/composer.json', + ], + 'replace' => true, + 'merge-extra' => true, + 'merge-extra-deep' => true, + 'merge-scripts' => true, + + ]; + + // Ensure the composer-merge-plugin is in the list of allowed plugins + if (!isset($composerJson['config']['allow-plugins'])) { + $composerJson['config']['allow-plugins'] = []; + } + // If allowed-plugins is set to true, disregard + if ($composerJson['config']['allow-plugins'] === true) { + $command->warn('Composer merge plugin already configured. skipping...'); + } else { + $composerJson['config']['allow-plugins']['wikimedia/composer-merge-plugin'] = true; + } + } + file_put_contents(base_path('composer.json'), json_encode($composerJson, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES)); + $command->info('Composer file configured successfully'); + } + + private function installationSteps(InstallCommand $command): void + { + $this->ensureModularPathExists($command); + $this->configureComposerMerge($command); + // Run composer dump-autoload and pipe the output realtime + $command->comment('Running composer dump-autoload:'); + \Savannabits\Modular\Facades\Modular::execCommand('composer dump-autoload'); + $command->info('Composer dump-autoload completed successfully'); + } + + private function ensureModularPathExists(InstallCommand $command): void + { + $command->comment('Ensuring modular path exists:'); + $path = config('modular.path'); + if (!is_dir($path)) { + mkdir($path, 0755, true); + $command->info("Directory $path created successfully"); + } else { + $command->warn("Directory $path already exists. skipping..."); + } + } + + private function getMigrationFiles(): array + { + return array_merge($this->discoverMigrations(), [ + // Your other migrations + ]); + } + + private function getCommands(): array + { + return array_merge($this->discoverCommands(), [ + // Your other commands + ]); + } + + private function discoverMigrations(): array + { + // Get an array of file names from the migrations directory + $glob1 = glob($this->package->basePath('/../database/migrations/*.php')); + $glob2 = glob($this->package->basePath('/../database/migrations/*.php.stub')); + + return collect($glob1) + ->merge($glob2) + ->map(fn ($filename) => Str::of($filename) + ->afterLast('/') + ->rtrim('.php.stub') + ->rtrim('.php')->toString() + ) + ->toArray(); + } + + private function discoverCommands(): array + { + // automatically include all namespace classes in the Console directory + // use glob to return full paths to all files in the Console directory + + $paths = glob($this->package->basePath('/Commands/*.php')); + + return collect($paths) + ->map(fn ($filename) => $this->getNamespaceFromFile($filename)->toString()) + ->toArray(); + } + + private function getNamespaceFromFile($path): Stringable + { + return $this->getFullNamespace(Str::of($path)->afterLast('src/') + ->replace('/', '\\') + ->studly()->rtrim('.php')); + } + + private function getFullNamespace(string $relativeNamespace = ''): Stringable + { + return Str::of(static::$vendor)->studly() + ->append('\\') + ->append(Str::studly(static::$name)) + ->append('\\') + ->append(Str::studly($relativeNamespace)); + } +} diff --git a/src/Skeleton.php b/src/Skeleton.php deleted file mode 100755 index 66fab60..0000000 --- a/src/Skeleton.php +++ /dev/null @@ -1,7 +0,0 @@ -name('skeleton') - ->hasConfigFile() - ->hasViews() - ->hasMigration('create_skeleton_table') - ->hasCommand(SkeletonCommand::class); - } -} diff --git a/src/Support/Concerns/CanManipulateFiles.php b/src/Support/Concerns/CanManipulateFiles.php new file mode 100644 index 0000000..c6eb0aa --- /dev/null +++ b/src/Support/Concerns/CanManipulateFiles.php @@ -0,0 +1,92 @@ + $paths + */ + protected function checkForCollision(array $paths): bool + { + foreach ($paths as $path) { + if (!$this->fileExists($path)) { + continue; + } + + if (!confirm(basename($path) . ' already exists, do you want to overwrite it?')) { + $this->components->error("{$path} already exists, aborting."); + + return true; + } + + unlink($path); + } + + return false; + } + + /** + * @param array $replacements + * + * @throws FileNotFoundException + * @throws ContainerExceptionInterface + * @throws NotFoundExceptionInterface + */ + protected function copyStubToApp(string $stub, string $targetPath, array $replacements = []): void + { + $filesystem = app(Filesystem::class); + + // Get the correct stub path whether published or not + $stubPath = $this->getDefaultStubPath() . "/{$stub}.stub"; + + $stub = str($filesystem->get($stubPath)); + + foreach ($replacements as $key => $replacement) { + $stub = $stub->replace("{{ {$key} }}", $replacement); + } + + $stub = (string)$stub; + + $this->writeFile($targetPath, $stub); + } + + protected function fileExists(string $path): bool + { + $filesystem = app(Filesystem::class); + + return $filesystem->exists($path); + } + + protected function writeFile(string $path, string $contents): void + { + $filesystem = app(Filesystem::class); + + $filesystem->ensureDirectoryExists( + pathinfo($path, PATHINFO_DIRNAME), + ); + + $filesystem->put($path, $contents); + } + + protected function getDefaultStubPath(): string + { + $reflectionClass = new ReflectionClass($this); + + return (string)str($reflectionClass->getFileName()) + ->beforeLast('Commands') + ->append('../stubs'); + } +} diff --git a/stubs/cast.inbound.stub b/stubs/cast.inbound.stub new file mode 100644 index 0000000..e74edf8 --- /dev/null +++ b/stubs/cast.inbound.stub @@ -0,0 +1,19 @@ + $attributes + */ + public function set(Model $model, string $key, mixed $value, array $attributes): mixed + { + return $value; + } +} diff --git a/stubs/cast.stub b/stubs/cast.stub new file mode 100644 index 0000000..35ddc47 --- /dev/null +++ b/stubs/cast.stub @@ -0,0 +1,29 @@ + $attributes + */ + public function get(Model $model, string $key, mixed $value, array $attributes): mixed + { + return $value; + } + + /** + * Prepare the given value for storage. + * + * @param array $attributes + */ + public function set(Model $model, string $key, mixed $value, array $attributes): mixed + { + return $value; + } +} diff --git a/stubs/class.invokable.stub b/stubs/class.invokable.stub new file mode 100644 index 0000000..c55610c --- /dev/null +++ b/stubs/class.invokable.stub @@ -0,0 +1,22 @@ + + */ + public function broadcastOn(): array + { + return [ + new PrivateChannel('channel-name'), + ]; + } +} diff --git a/stubs/factory.stub b/stubs/factory.stub new file mode 100644 index 0000000..f931493 --- /dev/null +++ b/stubs/factory.stub @@ -0,0 +1,23 @@ + + */ +class {{ factory }}Factory extends Factory +{ + /** + * Define the model's default state. + * + * @return array + */ + public function definition(): array + { + return [ + // + ]; + } +} diff --git a/stubs/job.queued.stub b/stubs/job.queued.stub new file mode 100644 index 0000000..9a7cec5 --- /dev/null +++ b/stubs/job.queued.stub @@ -0,0 +1,30 @@ + + */ + public function attachments(): array + { + return []; + } +} diff --git a/stubs/markdown-mail.stub b/stubs/markdown-mail.stub new file mode 100644 index 0000000..191b46f --- /dev/null +++ b/stubs/markdown-mail.stub @@ -0,0 +1,53 @@ + + */ + public function attachments(): array + { + return []; + } +} diff --git a/stubs/markdown-notification.stub b/stubs/markdown-notification.stub new file mode 100644 index 0000000..cc99eac --- /dev/null +++ b/stubs/markdown-notification.stub @@ -0,0 +1,51 @@ + + */ + public function via(object $notifiable): array + { + return ['mail']; + } + + /** + * Get the mail representation of the notification. + */ + public function toMail(object $notifiable): MailMessage + { + return (new MailMessage)->markdown('{{ view }}'); + } + + /** + * Get the array representation of the notification. + * + * @return array + */ + public function toArray(object $notifiable): array + { + return [ + // + ]; + } +} diff --git a/stubs/middleware.stub b/stubs/middleware.stub new file mode 100644 index 0000000..323c213 --- /dev/null +++ b/stubs/middleware.stub @@ -0,0 +1,20 @@ +id(); + $table->timestamps(); + }); + } + + /** + * Reverse the migrations. + */ + public function down(): void + { + Schema::dropIfExists('{{ table }}'); + } +}; diff --git a/stubs/migration.stub b/stubs/migration.stub new file mode 100644 index 0000000..88fa2f3 --- /dev/null +++ b/stubs/migration.stub @@ -0,0 +1,24 @@ +name(static::$name) + ->hasViews(static::$viewNamespace) + ->hasConsoleCommands($this->getCommands()) + ->hasInstallCommand(function (InstallCommand $command) { + $command + ->askToRunMigrations() + ->endWith(fn (InstallCommand $command) => $this->furtherInstallationSteps($command)); + }); + $this->loadMigrationsFrom($this->package->basePath('/../database/migrations')); + } + + private function furtherInstallationSteps(InstallCommand $command) + { + // + } + + private function getMigrationFiles(): array + { + return array_merge($this->discoverMigrations(), [ + // Your other migrations + ]); + } + + private function getCommands(): array + { + return array_merge($this->discoverCommands(), [ + // Your other commands + ]); + } + + private function discoverMigrations(): array + { + // Get an array of file names from the migrations directory + $glob1 = glob($this->package->basePath('/../database/migrations/*.php')); + $glob2 = glob($this->package->basePath('/../database/migrations/*.php.stub')); + + return collect($glob1) + ->merge($glob2) + ->map(fn ($filename) => Str::of($filename) + ->afterLast('/') + ->rtrim('.php.stub') + ->rtrim('.php')->toString() + ) + ->toArray(); + } + + private function discoverCommands(): array + { + // automatically include all namespace classes in the Console directory + // use glob to return full paths to all files in the Console directory + + $paths = glob($this->package->basePath('/Console/*.php')); + + return collect($paths) + ->map(fn ($filename) => $this->getNamespaceFromFile($filename)->toString()) + ->toArray(); + } + + private function getNamespaceFromFile($path): Stringable + { + return $this->getFullNamespace(Str::of($path)->afterLast('src/') + ->replace('/', '\\') + ->studly()->rtrim('.php')); + } + + private function getFullNamespace(string $relativeNamespace = ''): Stringable + { + return Str::of(static::$name)->studly() + ->prepend('Vanadi\\') + ->append('\\') + ->append(Str::studly($relativeNamespace)); + } +} diff --git a/stubs/notification.stub b/stubs/notification.stub new file mode 100644 index 0000000..e573dcd --- /dev/null +++ b/stubs/notification.stub @@ -0,0 +1,54 @@ + + */ + public function via(object $notifiable): array + { + return ['mail']; + } + + /** + * Get the mail representation of the notification. + */ + public function toMail(object $notifiable): MailMessage + { + return (new MailMessage) + ->line('The introduction to the notification.') + ->action('Notification Action', url('/')) + ->line('Thank you for using our application!'); + } + + /** + * Get the array representation of the notification. + * + * @return array + */ + public function toArray(object $notifiable): array + { + return [ + // + ]; + } +} diff --git a/stubs/observer.plain.stub b/stubs/observer.plain.stub new file mode 100644 index 0000000..e2506b7 --- /dev/null +++ b/stubs/observer.plain.stub @@ -0,0 +1,8 @@ +|string> + */ + public function rules(): array + { + return [ + // + ]; + } +} diff --git a/stubs/resource-collection.stub b/stubs/resource-collection.stub new file mode 100644 index 0000000..f75e481 --- /dev/null +++ b/stubs/resource-collection.stub @@ -0,0 +1,19 @@ + + */ + public function toArray(Request $request): array + { + return parent::toArray($request); + } +} diff --git a/stubs/resource.stub b/stubs/resource.stub new file mode 100644 index 0000000..ce8ece4 --- /dev/null +++ b/stubs/resource.stub @@ -0,0 +1,19 @@ + + */ + public function toArray(Request $request): array + { + return parent::toArray($request); + } +} diff --git a/stubs/rule.stub b/stubs/rule.stub new file mode 100644 index 0000000..e54d7ef --- /dev/null +++ b/stubs/rule.stub @@ -0,0 +1,19 @@ +get('/'); + + $response->assertStatus(200); + } +} diff --git a/stubs/test.unit.stub b/stubs/test.unit.stub new file mode 100644 index 0000000..7accf88 --- /dev/null +++ b/stubs/test.unit.stub @@ -0,0 +1,16 @@ +assertTrue(true); + } +} diff --git a/stubs/trait.stub b/stubs/trait.stub new file mode 100644 index 0000000..e409847 --- /dev/null +++ b/stubs/trait.stub @@ -0,0 +1,8 @@ +in(__DIR__); diff --git a/tests/TestCase.php b/tests/TestCase.php index d04fb0c..5152ec7 100644 --- a/tests/TestCase.php +++ b/tests/TestCase.php @@ -1,10 +1,10 @@ 'VendorName\\Skeleton\\Database\\Factories\\'.class_basename($modelName).'Factory' + fn (string $modelName) => 'Savannabits\\Modular\\Database\\Factories\\'.class_basename($modelName).'Factory' ); } protected function getPackageProviders($app) { return [ - SkeletonServiceProvider::class, + ModularServiceProvider::class, ]; } @@ -29,7 +29,7 @@ public function getEnvironmentSetUp($app) config()->set('database.default', 'testing'); /* - $migration = include __DIR__.'/../database/migrations/create_skeleton_table.php.stub'; + $migration = include __DIR__.'/../database/migrations/create_modular_table.php.stub'; $migration->up(); */ } From 22e7c41a4dfec0944c3963796924f9e68002e80c Mon Sep 17 00:00:00 2001 From: coolsam726 Date: Sat, 6 Apr 2024 09:40:55 +0000 Subject: [PATCH 2/2] Fix styling --- src/Commands/ActivateModuleCommand.php | 6 ++- src/Commands/DeactivateModuleCommand.php | 6 ++- src/Commands/MakeModuleCommand.php | 42 +++++++++++++-------- src/ModularServiceProvider.php | 17 +++++---- src/Support/Concerns/CanManipulateFiles.php | 14 +++---- 5 files changed, 51 insertions(+), 34 deletions(-) diff --git a/src/Commands/ActivateModuleCommand.php b/src/Commands/ActivateModuleCommand.php index c52903c..ceed144 100644 --- a/src/Commands/ActivateModuleCommand.php +++ b/src/Commands/ActivateModuleCommand.php @@ -5,13 +5,15 @@ use Illuminate\Console\Command; use Illuminate\Support\Str; use Savannabits\Modular\Facades\Modular; + use function Laravel\Prompts\text; class ActivateModuleCommand extends Command { - public $signature = 'modular:activate {name?}'; + public $description = 'Activate a module'; + private string $moduleName; public function handle(): void @@ -24,7 +26,7 @@ public function handle(): void private function activateModule(): void { $moduleName = $this->moduleName; - $repoName = config('modular.vendor','modular').'/'.$moduleName; + $repoName = config('modular.vendor', 'modular').'/'.$moduleName; Modular::execCommand('composer require '.$repoName.':@dev'); Modular::execCommand("php artisan $moduleName:install"); } diff --git a/src/Commands/DeactivateModuleCommand.php b/src/Commands/DeactivateModuleCommand.php index 7e85782..11fd989 100644 --- a/src/Commands/DeactivateModuleCommand.php +++ b/src/Commands/DeactivateModuleCommand.php @@ -5,13 +5,15 @@ use Illuminate\Console\Command; use Illuminate\Support\Str; use Savannabits\Modular\Facades\Modular; + use function Laravel\Prompts\text; class DeactivateModuleCommand extends Command { - public $signature = 'modular:deactivate {name?}'; + public $description = 'Deactivate a module'; + private string $moduleName; public function handle(): void @@ -24,7 +26,7 @@ public function handle(): void private function deactivateModule(): void { $moduleName = $this->moduleName; - $repoName = config('modular.vendor','modular').'/'.$moduleName; + $repoName = config('modular.vendor', 'modular').'/'.$moduleName; Modular::execCommand("composer remove $repoName"); } } diff --git a/src/Commands/MakeModuleCommand.php b/src/Commands/MakeModuleCommand.php index a026c7c..ecd04e0 100644 --- a/src/Commands/MakeModuleCommand.php +++ b/src/Commands/MakeModuleCommand.php @@ -8,17 +8,25 @@ use Psr\Container\ContainerExceptionInterface; use Psr\Container\NotFoundExceptionInterface; use Savannabits\Modular\Support\Concerns\CanManipulateFiles; + use function Laravel\Prompts\text; class MakeModuleCommand extends Command { use CanManipulateFiles; + public $signature = 'modular:make {name?} {--F|force}'; + public $description = 'Create a new module'; + private string $moduleName; + private string $moduleTitle; + private string $moduleNamespace; + private string $modulePath; + private string $moduleStudlyName; public function handle() @@ -27,8 +35,8 @@ public function handle() $this->moduleName = Str::of($name)->kebab()->toString(); $this->moduleStudlyName = Str::of($name)->studly()->toString(); $this->moduleTitle = Str::of($name)->kebab()->title()->replace('-', ' ')->toString(); - $this->moduleNamespace = config('modular.namespace') . '\\' . Str::of($name)->studly()->toString(); - $this->modulePath = config('modular.path') . '/' . $this->moduleName; + $this->moduleNamespace = config('modular.namespace').'\\'.Str::of($name)->studly()->toString(); + $this->modulePath = config('modular.path').'/'.$this->moduleName; $this->info("Creating module: $this->moduleName in $this->modulePath"); $this->generateModuleDirectories(); @@ -39,18 +47,20 @@ public function handle() private function generateModuleDirectories(): bool { $directories = config('modular.directory_tree'); - if (!count($directories)) { + if (! count($directories)) { $this->error('No directories found in the configuration file'); + return false; } foreach ($directories as $directory) { - $path = $this->modulePath . '/' . ltrim($directory,'/'); - if (!is_dir($path)) { + $path = $this->modulePath.'/'.ltrim($directory, '/'); + if (! is_dir($path)) { mkdir($path, 0775, true); $this->info("Created directory: $path"); } } $this->info('Module directories created successfully'); + return true; } @@ -62,28 +72,28 @@ private function generateModuleFiles(): void } catch (FileNotFoundException|NotFoundExceptionInterface|ContainerExceptionInterface $e) { $this->error($e->getMessage()); } -// $this->generateModuleFacade(); + // $this->generateModuleFacade(); } private function generateModuleComposerFile(): void { $composerJson = [ - 'name' => config('modular.vendor') . '/' . $this->moduleName, + 'name' => config('modular.vendor').'/'.$this->moduleName, 'type' => 'library', - 'description' => $this->moduleTitle . ' module', + 'description' => $this->moduleTitle.' module', 'require' => [ 'php' => '^8.2', ], 'autoload' => [ 'psr-4' => [ - $this->moduleNamespace . '\\' => 'src/', - $this->moduleNamespace . '\\Database\\Factories\\' => 'database/factories/', - $this->moduleNamespace . '\\Database\\Seeders\\' => 'database/seeders/', + $this->moduleNamespace.'\\' => 'src/', + $this->moduleNamespace.'\\Database\\Factories\\' => 'database/factories/', + $this->moduleNamespace.'\\Database\\Seeders\\' => 'database/seeders/', ], ], 'autoload-dev' => [ 'psr-4' => [ - $this->moduleNamespace . '\\Tests\\' => 'tests/', + $this->moduleNamespace.'\\Tests\\' => 'tests/', ], ], 'config' => [ @@ -96,12 +106,12 @@ private function generateModuleComposerFile(): void 'extra' => [ 'laravel' => [ 'providers' => [ - $this->moduleNamespace . '\\' . $this->moduleStudlyName . 'ServiceProvider', + $this->moduleNamespace.'\\'.$this->moduleStudlyName.'ServiceProvider', ], ], ], ]; - $composerJsonPath = $this->modulePath . '/composer.json'; + $composerJsonPath = $this->modulePath.'/composer.json'; file_put_contents($composerJsonPath, json_encode($composerJson, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES)); $this->info("Created composer.json file: $composerJsonPath"); } @@ -113,9 +123,9 @@ private function generateModuleComposerFile(): void */ private function generateModuleServiceProvider(): void { - $path = $this->modulePath . '/src/' . $this->moduleStudlyName . 'ServiceProvider.php'; + $path = $this->modulePath.'/src/'.$this->moduleStudlyName.'ServiceProvider.php'; $namespace = $this->moduleNamespace; - $class = $this->moduleStudlyName . 'ServiceProvider'; + $class = $this->moduleStudlyName.'ServiceProvider'; $this->copyStubToApp('module.provider', $path, [ 'class' => $class, 'namespace' => $namespace, diff --git a/src/ModularServiceProvider.php b/src/ModularServiceProvider.php index a0a5c44..dfb110c 100644 --- a/src/ModularServiceProvider.php +++ b/src/ModularServiceProvider.php @@ -7,11 +7,15 @@ use Spatie\LaravelPackageTools\Commands\InstallCommand; use Spatie\LaravelPackageTools\Package; use Spatie\LaravelPackageTools\PackageServiceProvider; + class ModularServiceProvider extends PackageServiceProvider { public static string $name = 'modular'; + public static string $vendor = 'savannabits'; + public static string $viewNamespace = 'modular'; + public function configurePackage(Package $package): void { /* @@ -30,8 +34,7 @@ public function configurePackage(Package $package): void $command ->askToStarRepoOnGitHub($name) ->startWith(fn (InstallCommand $command) => $this->installationSteps($command)); - }) - ; + }); $this->mergeConfigFrom($this->package->basePath('/../config/modular.php'), 'modular'); } @@ -40,10 +43,10 @@ private function configureComposerMerge(InstallCommand $command): void $command->comment('Configuring Composer merge plugin:'); $composerJson = json_decode(file_get_contents(base_path('composer.json')), true); // Add the modules repositories into compose if they don't exist - if (!isset($composerJson['repositories'])){ + if (! isset($composerJson['repositories'])) { $composerJson['repositories'] = []; } - if (!collect($composerJson['repositories'])->contains(fn ($repo) => $repo['type'] === 'path' && $repo['url'] === config('modular.path').'/*')) { + if (! collect($composerJson['repositories'])->contains(fn ($repo) => $repo['type'] === 'path' && $repo['url'] === config('modular.path').'/*')) { $composerJson['repositories'][] = [ 'type' => 'path', 'url' => config('modular.path').'/*', @@ -52,7 +55,7 @@ private function configureComposerMerge(InstallCommand $command): void ], ]; } - if (!isset($composerJson['extra']['merge-plugin'])) { + if (! isset($composerJson['extra']['merge-plugin'])) { $composerJson['extra']['merge-plugin'] = [ 'include' => [ 'modules/*/composer.json', @@ -65,7 +68,7 @@ private function configureComposerMerge(InstallCommand $command): void ]; // Ensure the composer-merge-plugin is in the list of allowed plugins - if (!isset($composerJson['config']['allow-plugins'])) { + if (! isset($composerJson['config']['allow-plugins'])) { $composerJson['config']['allow-plugins'] = []; } // If allowed-plugins is set to true, disregard @@ -93,7 +96,7 @@ private function ensureModularPathExists(InstallCommand $command): void { $command->comment('Ensuring modular path exists:'); $path = config('modular.path'); - if (!is_dir($path)) { + if (! is_dir($path)) { mkdir($path, 0755, true); $command->info("Directory $path created successfully"); } else { diff --git a/src/Support/Concerns/CanManipulateFiles.php b/src/Support/Concerns/CanManipulateFiles.php index c6eb0aa..fe9f04f 100644 --- a/src/Support/Concerns/CanManipulateFiles.php +++ b/src/Support/Concerns/CanManipulateFiles.php @@ -17,16 +17,16 @@ trait CanManipulateFiles { /** - * @param array $paths + * @param array $paths */ protected function checkForCollision(array $paths): bool { foreach ($paths as $path) { - if (!$this->fileExists($path)) { + if (! $this->fileExists($path)) { continue; } - if (!confirm(basename($path) . ' already exists, do you want to overwrite it?')) { + if (! confirm(basename($path).' already exists, do you want to overwrite it?')) { $this->components->error("{$path} already exists, aborting."); return true; @@ -39,7 +39,7 @@ protected function checkForCollision(array $paths): bool } /** - * @param array $replacements + * @param array $replacements * * @throws FileNotFoundException * @throws ContainerExceptionInterface @@ -50,7 +50,7 @@ protected function copyStubToApp(string $stub, string $targetPath, array $replac $filesystem = app(Filesystem::class); // Get the correct stub path whether published or not - $stubPath = $this->getDefaultStubPath() . "/{$stub}.stub"; + $stubPath = $this->getDefaultStubPath()."/{$stub}.stub"; $stub = str($filesystem->get($stubPath)); @@ -58,7 +58,7 @@ protected function copyStubToApp(string $stub, string $targetPath, array $replac $stub = $stub->replace("{{ {$key} }}", $replacement); } - $stub = (string)$stub; + $stub = (string) $stub; $this->writeFile($targetPath, $stub); } @@ -85,7 +85,7 @@ protected function getDefaultStubPath(): string { $reflectionClass = new ReflectionClass($this); - return (string)str($reflectionClass->getFileName()) + return (string) str($reflectionClass->getFileName()) ->beforeLast('Commands') ->append('../stubs'); }