From 3593cb2b8a73e72d2cec575b1bf571b2ce17031d Mon Sep 17 00:00:00 2001 From: Mohammad Zulfahmi Date: Thu, 21 Dec 2023 18:34:07 +0700 Subject: [PATCH 001/105] add seeder generator --- src/Generators/SeederGenerator.php | 48 +++++++++++++++++++ src/Generators/Services/GeneratorService.php | 5 ++ src/Http/Requests/StoreGeneratorRequest.php | 2 + .../views/generators/include/form.blade.php | 23 +++++++-- .../generators/include/js/create-js.blade.php | 2 +- stubs/generators/seeder.stub | 32 +++++++++++++ 6 files changed, 108 insertions(+), 4 deletions(-) create mode 100644 src/Generators/SeederGenerator.php create mode 100644 stubs/generators/seeder.stub diff --git a/src/Generators/SeederGenerator.php b/src/Generators/SeederGenerator.php new file mode 100644 index 00000000..9a131a39 --- /dev/null +++ b/src/Generators/SeederGenerator.php @@ -0,0 +1,48 @@ + $field) { + $fields .= "'" . $field ."' => "; + $fields .= $request['requireds'][$i] == 'yes' ? "''" : "null"; + + if($i + 1 != $totalField) { + $fields .= ",\r\n\t\t\t"; + } + } + + $modelPath = $path ? $path . "\\" : ""; + + $template = str_replace( + [ + '{{modelPath}}', + '{{fields}}', + '{{modelNameSingularPascalCase}}', + '{{modelNameSingularCamelCase}}', + '{{modelNamePluralCamelCase}}' + ], + [ + "App\Models\\" . $modelPath . $modelNameSingularPascalCase, + $fields, + $modelNameSingularPascalCase, + GeneratorUtils::singularCamelCase($model), + GeneratorUtils::pluralCamelCase($model) + ], + GeneratorUtils::getTemplate('seeder') + ); + + file_put_contents(app_path("../database/seeders/" . $modelNameSingularPascalCase . "Seeder.php"), $template); + } +} diff --git a/src/Generators/Services/GeneratorService.php b/src/Generators/Services/GeneratorService.php index 288b6fd5..d9f380a7 100644 --- a/src/Generators/Services/GeneratorService.php +++ b/src/Generators/Services/GeneratorService.php @@ -14,6 +14,7 @@ PermissionGenerator, RequestGenerator, RouteGenerator, + SeederGenerator, ViewComposerGenerator }; use EvdigiIna\Generator\Generators\Views\{ @@ -54,6 +55,10 @@ public function generateAll(array $request): void Artisan::call('migrate'); + if(isset($request['generate_seeder']) && $request['generate_seeder'] != null) { + (new SeederGenerator)->generate($request); + } + $this->checkSidebarType(); } diff --git a/src/Http/Requests/StoreGeneratorRequest.php b/src/Http/Requests/StoreGeneratorRequest.php index 919ce8a1..0934878d 100644 --- a/src/Http/Requests/StoreGeneratorRequest.php +++ b/src/Http/Requests/StoreGeneratorRequest.php @@ -69,6 +69,8 @@ public function rules(): array 'new_header' => ['required_if:header,new'], 'new_icon' => ['required_if:header,new'], 'new_menu' => ['required_if:header,new'], + 'generate_seeder' => ['nullable'], + 'generate_factory' => ['nullable'], // 'new_route' => ['required_if:header,new'], 'new_submenu' => ['nullable'], ]; diff --git a/src/Resources/views/generators/include/form.blade.php b/src/Resources/views/generators/include/form.blade.php index 5716a2fb..eba58997 100644 --- a/src/Resources/views/generators/include/form.blade.php +++ b/src/Resources/views/generators/include/form.blade.php @@ -1,6 +1,6 @@
{{-- model name --}} -
+
-

Generate Type

+
+

{{ __('Generate Type') }}

@@ -36,6 +36,23 @@
{{-- end of generate type --}} +
+

{{ __('Ads on') }}

+ +
+
+ + +
+
+
+
+ + +
+
+
+
{{ __('Table Fields') }}
diff --git a/src/Resources/views/generators/include/js/create-js.blade.php b/src/Resources/views/generators/include/js/create-js.blade.php index c60fe59d..d7e88564 100644 --- a/src/Resources/views/generators/include/js/create-js.blade.php +++ b/src/Resources/views/generators/include/js/create-js.blade.php @@ -1,6 +1,6 @@ + + + @include('generator::include.js.api-create-js') + + @include('generator::include.js.function-js') +@endpush + diff --git a/src/Resources/views/generators/include/api-form.blade.php b/src/Resources/views/generators/include/api-form.blade.php new file mode 100644 index 00000000..722ed5bc --- /dev/null +++ b/src/Resources/views/generators/include/api-form.blade.php @@ -0,0 +1,157 @@ +
+ {{-- model name --}} +
+
+ + + {{ __("Use '/' for generate a sub folder. e.g.: Main/Product.") }} + @error('model') +
+ {{ $message }} +
+ @enderror +
+
+ {{-- end of model name --}} + + + + {{-- generate type --}} +
+

{{ __('Generate Type') }}

+
+ + +
+ +
+ + +
+
+ {{-- end of generate type --}} + +
+

{{ __('Add-ons') }}

+ +
+
+ + +
+
+
+
+ + +
+
+
+ +
+
{{ __('Table Fields') }}
+
+ +
+ +
+ + {{-- table fields --}} +
+ + + + + + + + + + + + + + + + + + + + + + + +
#{{ __('Field name') }}{{ __('Column Type') }}{{ __('Length') }} + {{ __('Input Type') }} +
+ {{ __('Used for validation request') }} +
{{ __('Required') }}{{ __('Action') }}
1 +
+ +
+
+
+ + + + +
+
+
+
+
+ +
+
+
+
+ +
+
+
+
+
+ +
+ + + + +
+
+ +
+ +
+ +
+
+ {{-- end of table fields --}} + + +
diff --git a/src/Resources/views/generators/include/form.blade.php b/src/Resources/views/generators/include/form.blade.php index aaeb75c9..f6c109f0 100644 --- a/src/Resources/views/generators/include/form.blade.php +++ b/src/Resources/views/generators/include/form.blade.php @@ -16,7 +16,7 @@ {{-- end of model name --}} {{-- generate type --}} -
+

{{ __('Generate Type') }}

{{-- end of generate type --}} - {{-- generate type --}} -
-

{{ __('Variant') }}

-
- - -
+ -
- - -
-
- {{-- end of generate type --}} - -
-

{{ __('Ads on') }}

+
+

{{ __('Add-ons') }}

diff --git a/src/Resources/views/generators/include/js/api-create-js.blade.php b/src/Resources/views/generators/include/js/api-create-js.blade.php new file mode 100644 index 00000000..c36dc96c --- /dev/null +++ b/src/Resources/views/generators/include/js/api-create-js.blade.php @@ -0,0 +1,545 @@ + diff --git a/src/Resources/views/generators/simple-create.blade.php b/src/Resources/views/generators/simple-create.blade.php index ad7d7089..f0d7e4f2 100644 --- a/src/Resources/views/generators/simple-create.blade.php +++ b/src/Resources/views/generators/simple-create.blade.php @@ -87,7 +87,7 @@ class="text-secondary">{{ __("Use '/' for generate a sub folder. e.g.: Main/Prod {{-- end of generate type --}}
-

{{ __('Ads on') }}

+

{{ __('Add-ons') }}

@@ -125,7 +125,11 @@ class="text-secondary">{{ __("Use '/' for generate a sub folder. e.g.: Main/Prod {{ __('Field name') }} {{ __('Column Type') }} {{ __('Length') }} - {{ __('Input Type') }} + + {{ __('Input Type') }} +
+ {{ __('Used for validation request') }} + {{ __('Required') }} {{ __('Action') }} diff --git a/src/Routes/generator.php b/src/Routes/generator.php index 4a633f96..47e48848 100644 --- a/src/Routes/generator.php +++ b/src/Routes/generator.php @@ -14,6 +14,9 @@ Route::resource('simple-generators', SimpleGeneratorController::class) ->only('create', 'store'); + Route::get('/api-generators/create', [GeneratorController::class, 'apiCreate']); + Route::post('/api-generators', [GeneratorController::class, 'store']); + Route::resource('generators', GeneratorController::class) ->only('create', 'store') ->middleware(OnlyAvailableInTheFullVersion::class); diff --git a/stubs/generators/publish/views/layouts/sidebar.blade.php b/stubs/generators/publish/views/layouts/sidebar.blade.php index d00f0166..36db9b84 100644 --- a/stubs/generators/publish/views/layouts/sidebar.blade.php +++ b/stubs/generators/publish/views/layouts/sidebar.blade.php @@ -102,10 +102,24 @@ + + + + @endif From b91886562bf9567dcf9d5e9449e61469b175868a Mon Sep 17 00:00:00 2001 From: Mohammad Zulfahmi Date: Thu, 28 Dec 2023 15:39:07 +0700 Subject: [PATCH 011/105] change getTemplate to getStub in GeneratorUtils --- src/Commands/PublishAllFiles.php | 2 +- src/Commands/SetSidebarType.php | 4 +-- src/Generators/ControllerGenerator.php | 12 ++++----- src/Generators/FactoryGenerator.php | 2 +- src/Generators/GeneratorUtils.php | 2 +- .../Interfaces/GeneratorUtilsInterface.php | 2 +- src/Generators/MigrationGenerator.php | 2 +- src/Generators/ModelGenerator.php | 2 +- src/Generators/RequestGenerator.php | 4 +-- src/Generators/ResourceApiGenerator.php | 4 +-- src/Generators/SeederGenerator.php | 2 +- src/Generators/ViewComposerGenerator.php | 2 +- src/Generators/Views/ActionViewGenerator.php | 2 +- src/Generators/Views/CreateViewGenerator.php | 2 +- src/Generators/Views/EditViewGenerator.php | 2 +- src/Generators/Views/FormViewGenerator.php | 26 +++++++++---------- src/Generators/Views/IndexViewGenerator.php | 2 +- src/Generators/Views/ShowViewGenerator.php | 2 +- .../publish/utils/GeneratorUtils.php | 2 +- .../Interfaces/GeneratorUtilsInterface.php | 2 +- tests/GeneratorUtilsTest.php | 2 +- 21 files changed, 41 insertions(+), 41 deletions(-) diff --git a/src/Commands/PublishAllFiles.php b/src/Commands/PublishAllFiles.php index 599a4d73..54c604ab 100644 --- a/src/Commands/PublishAllFiles.php +++ b/src/Commands/PublishAllFiles.php @@ -210,7 +210,7 @@ public function runPublishAll(): void Artisan::call('vendor:publish --provider="Intervention\Image\ImageServiceProviderLaravelRecent"'); Artisan::call('vendor:publish --tag=datatables --force'); - $template = GeneratorUtils::getTemplate('route'); + $template = GeneratorUtils::getStub('route'); File::append(base_path('routes/web.php'), $template); diff --git a/src/Commands/SetSidebarType.php b/src/Commands/SetSidebarType.php index c5823ff8..550f06cd 100644 --- a/src/Commands/SetSidebarType.php +++ b/src/Commands/SetSidebarType.php @@ -109,7 +109,7 @@ public function handle(): void "']", $sidebarCode ), - GeneratorUtils::getTemplate('sidebar-static') + GeneratorUtils::getStub('sidebar-static') ); file_put_contents(resource_path('views/layouts/sidebar.blade.php'), $template); @@ -119,7 +119,7 @@ public function handle(): void case 'dynamic': $this->checkGeneratorVariant(); - file_put_contents(resource_path('views/layouts/sidebar.blade.php'), GeneratorUtils::getTemplate('sidebar-dynamic')); + file_put_contents(resource_path('views/layouts/sidebar.blade.php'), GeneratorUtils::getStub('sidebar-dynamic')); $this->info('The sidebar used a dynamic list from config.'); break; diff --git a/src/Generators/ControllerGenerator.php b/src/Generators/ControllerGenerator.php index 81e9c94d..ce4c3452 100644 --- a/src/Generators/ControllerGenerator.php +++ b/src/Generators/ControllerGenerator.php @@ -291,9 +291,9 @@ public function generate(array $request): void $updateDataAction = "\$" . $modelNameSingularCamelCase . "->update(\$validated);"; if ($request['generate_variant'] == 'api') { - $getTemplate = GeneratorUtils::getTemplate('controllers/controller-api-with-upload-file'); + $getTemplate = GeneratorUtils::getStub('controllers/controller-api-with-upload-file'); } else { - $getTemplate = GeneratorUtils::getTemplate('controllers/controller-with-upload-file'); + $getTemplate = GeneratorUtils::getStub('controllers/controller-with-upload-file'); } /** @@ -357,9 +357,9 @@ public function generate(array $request): void break; default: if ($request['generate_variant'] == 'api') { - $getTemplate = GeneratorUtils::getTemplate('controllers/controller-api'); + $getTemplate = GeneratorUtils::getStub('controllers/controller-api'); } else { - $getTemplate = GeneratorUtils::getTemplate('controllers/controller'); + $getTemplate = GeneratorUtils::getStub('controllers/controller'); } /** @@ -481,14 +481,14 @@ protected function generateUploadFileCode(string $field, string $path, string $m return str_replace( $replaceString, $replaceWith, - GeneratorUtils::getTemplate("controllers/upload-files/with-crop/$path") + GeneratorUtils::getStub("controllers/upload-files/with-crop/$path") ); break; default: return str_replace( $replaceString, $replaceWith, - GeneratorUtils::getTemplate("controllers/upload-files/$path") + GeneratorUtils::getStub("controllers/upload-files/$path") ); break; } diff --git a/src/Generators/FactoryGenerator.php b/src/Generators/FactoryGenerator.php index 7d281b7b..83b50de9 100644 --- a/src/Generators/FactoryGenerator.php +++ b/src/Generators/FactoryGenerator.php @@ -34,7 +34,7 @@ public function generate(array $request) $fields, $modelNameSingularPascalCase, ], - GeneratorUtils::getTemplate('factory') + GeneratorUtils::getStub('factory') ); file_put_contents(app_path("../database/factories/" . $modelNameSingularPascalCase . "Factory.php"), $template); diff --git a/src/Generators/GeneratorUtils.php b/src/Generators/GeneratorUtils.php index 8667c74a..985980f8 100644 --- a/src/Generators/GeneratorUtils.php +++ b/src/Generators/GeneratorUtils.php @@ -10,7 +10,7 @@ class GeneratorUtils implements GeneratorUtilsInterface /** * Get template/stub file. */ - public static function getTemplate(string $path): string + public static function getStub(string $path): string { return file_get_contents(__DIR__ . "/../../stubs/generators/$path.stub"); } diff --git a/src/Generators/Interfaces/GeneratorUtilsInterface.php b/src/Generators/Interfaces/GeneratorUtilsInterface.php index 9d63f2d4..e867915a 100644 --- a/src/Generators/Interfaces/GeneratorUtilsInterface.php +++ b/src/Generators/Interfaces/GeneratorUtilsInterface.php @@ -7,7 +7,7 @@ interface GeneratorUtilsInterface /** * Get template/stub file. */ - public static function getTemplate(string $path): string; + public static function getStub(string $path): string; /** * Get published files. diff --git a/src/Generators/MigrationGenerator.php b/src/Generators/MigrationGenerator.php index 94a160ab..0614151f 100644 --- a/src/Generators/MigrationGenerator.php +++ b/src/Generators/MigrationGenerator.php @@ -199,7 +199,7 @@ public function generate(array $request): void $tableNamePluralLowercase, $setFields ], - GeneratorUtils::getTemplate('migration') + GeneratorUtils::getStub('migration') ); $migrationName = date('Y') . '_' . date('m') . '_' . date('d') . '_' . date('h') . date('i') . date('s') . '_create_' . $tableNamePluralLowercase . '_table.php'; diff --git a/src/Generators/ModelGenerator.php b/src/Generators/ModelGenerator.php index f36313c1..a0aeb7b7 100644 --- a/src/Generators/ModelGenerator.php +++ b/src/Generators/ModelGenerator.php @@ -160,7 +160,7 @@ public function generate(array $request): void $protectedHidden, GeneratorUtils::pluralSnakeCase($model), ], - GeneratorUtils::getTemplate('model') + GeneratorUtils::getStub('model') ); if (!$path) { diff --git a/src/Generators/RequestGenerator.php b/src/Generators/RequestGenerator.php index 294960af..71f6e048 100644 --- a/src/Generators/RequestGenerator.php +++ b/src/Generators/RequestGenerator.php @@ -222,7 +222,7 @@ public function generate(array $request): void $validations, $namespace ], - GeneratorUtils::getTemplate('request') + GeneratorUtils::getStub('request') ); /** @@ -276,7 +276,7 @@ public function generate(array $request): void $updateValidations, $namespace ], - GeneratorUtils::getTemplate('request') + GeneratorUtils::getStub('request') ); /** diff --git a/src/Generators/ResourceApiGenerator.php b/src/Generators/ResourceApiGenerator.php index e95ca5dd..89ff717c 100644 --- a/src/Generators/ResourceApiGenerator.php +++ b/src/Generators/ResourceApiGenerator.php @@ -26,7 +26,7 @@ public function generate(array $request): void $modelNameSingularPascalCase, GeneratorUtils::singularSnakeCase($model) ], - GeneratorUtils::getTemplate('resource') + GeneratorUtils::getStub('resource') ); $collectionTemplate = str_replace( @@ -40,7 +40,7 @@ public function generate(array $request): void $modelNameSingularPascalCase, GeneratorUtils::pluralSnakeCase($model), ], - GeneratorUtils::getTemplate('resource-collection') + GeneratorUtils::getStub('resource-collection') ); GeneratorUtils::checkFolder(app_path("/Http/Resources/$modelNamePluralPascalCase")); diff --git a/src/Generators/SeederGenerator.php b/src/Generators/SeederGenerator.php index 9a131a39..be056a1e 100644 --- a/src/Generators/SeederGenerator.php +++ b/src/Generators/SeederGenerator.php @@ -40,7 +40,7 @@ public function generate(array $request) GeneratorUtils::singularCamelCase($model), GeneratorUtils::pluralCamelCase($model) ], - GeneratorUtils::getTemplate('seeder') + GeneratorUtils::getStub('seeder') ); file_put_contents(app_path("../database/seeders/" . $modelNameSingularPascalCase . "Seeder.php"), $template); diff --git a/src/Generators/ViewComposerGenerator.php b/src/Generators/ViewComposerGenerator.php index 2d7931f0..a7c67a90 100644 --- a/src/Generators/ViewComposerGenerator.php +++ b/src/Generators/ViewComposerGenerator.php @@ -59,7 +59,7 @@ public function generate(array $request): void $relatedModelPath, $viewPath != '' ? str_replace('\\', '.', strtolower($viewPath)) . "." : '', ], - GeneratorUtils::getTemplate('view-composer') + GeneratorUtils::getStub('view-composer') ); } } diff --git a/src/Generators/Views/ActionViewGenerator.php b/src/Generators/Views/ActionViewGenerator.php index 19d657dc..8185596a 100644 --- a/src/Generators/Views/ActionViewGenerator.php +++ b/src/Generators/Views/ActionViewGenerator.php @@ -26,7 +26,7 @@ public function generate(array $request): void $modelNameSingularLowercase, $modelNamePluralKebabCase ], - empty($request['is_simple_generator']) ? GeneratorUtils::getTemplate('views/action') : GeneratorUtils::getTemplate('views/simple/action') + empty($request['is_simple_generator']) ? GeneratorUtils::getStub('views/action') : GeneratorUtils::getStub('views/simple/action') ); if ($path != '') { diff --git a/src/Generators/Views/CreateViewGenerator.php b/src/Generators/Views/CreateViewGenerator.php index 143fee3c..b1a36cff 100644 --- a/src/Generators/Views/CreateViewGenerator.php +++ b/src/Generators/Views/CreateViewGenerator.php @@ -33,7 +33,7 @@ public function generate(array $request): void in_array('file', $request['input_types']) ? ' enctype="multipart/form-data"' : '', $path != '' ? str_replace('\\', '.', strtolower($path)) . "." : '', ], - empty($request['is_simple_generator']) ? GeneratorUtils::getTemplate('views/create') : GeneratorUtils::getTemplate('views/simple/create') + empty($request['is_simple_generator']) ? GeneratorUtils::getStub('views/create') : GeneratorUtils::getStub('views/simple/create') ); diff --git a/src/Generators/Views/EditViewGenerator.php b/src/Generators/Views/EditViewGenerator.php index 1de394df..25238202 100644 --- a/src/Generators/Views/EditViewGenerator.php +++ b/src/Generators/Views/EditViewGenerator.php @@ -36,7 +36,7 @@ public function generate(array $request): void in_array('file', $request['input_types']) ? ' enctype="multipart/form-data"' : '', $path != '' ? str_replace('\\', '.', strtolower($path)) . "." : '', ], - empty($request['is_simple_generator']) ? GeneratorUtils::getTemplate('views/edit') : GeneratorUtils::getTemplate('views/simple/edit'), + empty($request['is_simple_generator']) ? GeneratorUtils::getStub('views/edit') : GeneratorUtils::getStub('views/simple/edit'), ); if (!$path) { diff --git a/src/Generators/Views/FormViewGenerator.php b/src/Generators/Views/FormViewGenerator.php index 48bac76d..13cf8ae0 100644 --- a/src/Generators/Views/FormViewGenerator.php +++ b/src/Generators/Views/FormViewGenerator.php @@ -65,7 +65,7 @@ public function generate(array $request): void $options, $request['requireds'][$i] == 'yes' ? ' required' : '', ], - GeneratorUtils::getTemplate('views/forms/select') + GeneratorUtils::getStub('views/forms/select') ); break; case 'datalist': @@ -98,7 +98,7 @@ public function generate(array $request): void $request['requireds'][$i] == 'yes' ? ' required' : '', "{{ isset($" . $modelNameSingularCamelCase . ") && $" . $modelNameSingularCamelCase . "->" . $fieldSnakeCase . " ? $" . $modelNameSingularCamelCase . "->" . $fieldSnakeCase . " : old('" . $fieldSnakeCase . "') }}" ], - GeneratorUtils::getTemplate('views/forms/datalist') + GeneratorUtils::getStub('views/forms/datalist') ); break; default: @@ -123,7 +123,7 @@ public function generate(array $request): void "{{ isset($" . $modelNameSingularCamelCase . ") && $" . $modelNameSingularCamelCase . "->$field == '$value' ? 'checked' : (old('$field') == '$value' ? 'checked' : '') }}", $request['requireds'][$i] == 'yes' ? ' required' : '', ], - GeneratorUtils::getTemplate('views/forms/radio') + GeneratorUtils::getStub('views/forms/radio') ); } @@ -169,7 +169,7 @@ public function generate(array $request): void $request['requireds'][$i] == 'yes' ? ' required' : '', "{{ isset($" . $modelNameSingularCamelCase . ") && $" . $modelNameSingularCamelCase . "->" . $fieldSnakeCase . " ? $" . $modelNameSingularCamelCase . "->" . $fieldSnakeCase . " : old('" . $fieldSnakeCase . "') }}" ], - GeneratorUtils::getTemplate('views/forms/datalist') + GeneratorUtils::getStub('views/forms/datalist') ); break; default: @@ -191,7 +191,7 @@ public function generate(array $request): void $request['requireds'][$i] == 'yes' ? ' required' : '', $fieldSnakeCase ], - GeneratorUtils::getTemplate('views/forms/select') + GeneratorUtils::getStub('views/forms/select') ); break; } @@ -240,7 +240,7 @@ public function generate(array $request): void $request['requireds'][$i] == 'yes' ? ' required' : '', "{{ isset($" . $modelNameSingularCamelCase . ") && $" . $modelNameSingularCamelCase . "->" . $fieldSnakeCase . " ? $" . $modelNameSingularCamelCase . "->" . $fieldSnakeCase . " : old('" . $fieldSnakeCase . "') }}" ], - GeneratorUtils::getTemplate('views/forms/datalist') + GeneratorUtils::getStub('views/forms/datalist') ); break; default: @@ -261,7 +261,7 @@ public function generate(array $request): void $options, $request['requireds'][$i] == 'yes' ? ' required' : '', ], - GeneratorUtils::getTemplate('views/forms/select') + GeneratorUtils::getStub('views/forms/select') ); break; } @@ -289,7 +289,7 @@ public function generate(array $request): void $options, $request['requireds'][$i] == 'yes' ? ' required' : '', ], - GeneratorUtils::getTemplate('views/forms/select') + GeneratorUtils::getStub('views/forms/select') ); break; @@ -438,7 +438,7 @@ public function generate(array $request): void $request['requireds'][$i] == 'yes' ? ' required' : '', $fieldSnakeCase ], - GeneratorUtils::getTemplate('views/forms/textarea') + GeneratorUtils::getStub('views/forms/textarea') ); break; case 'file': @@ -473,7 +473,7 @@ public function generate(array $request): void $default['image'], $default['form_code'] ], - GeneratorUtils::getTemplate('views/forms/image') + GeneratorUtils::getStub('views/forms/image') ); break; case 'range': @@ -496,7 +496,7 @@ public function generate(array $request): void $request['max_lengths'][$i], $request['steps'][$i] ? 'step="' . $request['steps'][$i] . '"' : '', ], - GeneratorUtils::getTemplate('views/forms/range') + GeneratorUtils::getStub('views/forms/range') ); break; case 'hidden': @@ -516,7 +516,7 @@ public function generate(array $request): void GeneratorUtils::singularKebabCase($field), $modelNameSingularCamelCase ], - GeneratorUtils::getTemplate('views/forms/input-password') + GeneratorUtils::getStub('views/forms/input-password') ); break; default: @@ -573,7 +573,7 @@ public function setInputTypeTemplate(string $field, array $request, string $form $formatValue, $request['requireds'] == 'yes' ? ' required' : '', ], - GeneratorUtils::getTemplate('views/forms/input') + GeneratorUtils::getStub('views/forms/input') ); } } diff --git a/src/Generators/Views/IndexViewGenerator.php b/src/Generators/Views/IndexViewGenerator.php index cc88de83..c329ed3e 100644 --- a/src/Generators/Views/IndexViewGenerator.php +++ b/src/Generators/Views/IndexViewGenerator.php @@ -121,7 +121,7 @@ public function generate(array $request): void $thColumns, $tdColumns, ], - empty($request['is_simple_generator']) ? GeneratorUtils::getTemplate('views/index') : GeneratorUtils::getTemplate('views/simple/index') + empty($request['is_simple_generator']) ? GeneratorUtils::getStub('views/index') : GeneratorUtils::getStub('views/simple/index') ); switch ($path) { diff --git a/src/Generators/Views/ShowViewGenerator.php b/src/Generators/Views/ShowViewGenerator.php index 245c70de..6f2e115c 100644 --- a/src/Generators/Views/ShowViewGenerator.php +++ b/src/Generators/Views/ShowViewGenerator.php @@ -126,7 +126,7 @@ public function generate(array $request): void $trs, $dateTimeFormat, ], - empty($request['is_simple_generator']) ? GeneratorUtils::getTemplate('views/show') : GeneratorUtils::getTemplate('views/simple/show') + empty($request['is_simple_generator']) ? GeneratorUtils::getStub('views/show') : GeneratorUtils::getStub('views/simple/show') ); switch ($path) { diff --git a/stubs/generators/publish/utils/GeneratorUtils.php b/stubs/generators/publish/utils/GeneratorUtils.php index 8667c74a..985980f8 100644 --- a/stubs/generators/publish/utils/GeneratorUtils.php +++ b/stubs/generators/publish/utils/GeneratorUtils.php @@ -10,7 +10,7 @@ class GeneratorUtils implements GeneratorUtilsInterface /** * Get template/stub file. */ - public static function getTemplate(string $path): string + public static function getStub(string $path): string { return file_get_contents(__DIR__ . "/../../stubs/generators/$path.stub"); } diff --git a/stubs/generators/publish/utils/Interfaces/GeneratorUtilsInterface.php b/stubs/generators/publish/utils/Interfaces/GeneratorUtilsInterface.php index 9d63f2d4..e867915a 100644 --- a/stubs/generators/publish/utils/Interfaces/GeneratorUtilsInterface.php +++ b/stubs/generators/publish/utils/Interfaces/GeneratorUtilsInterface.php @@ -7,7 +7,7 @@ interface GeneratorUtilsInterface /** * Get template/stub file. */ - public static function getTemplate(string $path): string; + public static function getStub(string $path): string; /** * Get published files. diff --git a/tests/GeneratorUtilsTest.php b/tests/GeneratorUtilsTest.php index a80c2e98..59a2c0c3 100644 --- a/tests/GeneratorUtilsTest.php +++ b/tests/GeneratorUtilsTest.php @@ -9,7 +9,7 @@ class GeneratorUtilsTest extends BaseTestCase /** @test */ public function it_has_get_template_method() { - $this->assertTrue(method_exists(GeneratorUtils::class, 'getTemplate')); + $this->assertTrue(method_exists(GeneratorUtils::class, 'getStub')); } /** @test */ From 331745065d04054271c3568be1b99a23e373e0a8 Mon Sep 17 00:00:00 2001 From: Mohammad Zulfahmi Date: Sat, 30 Dec 2023 08:52:35 +0700 Subject: [PATCH 012/105] wip --- src/Generators/ControllerGenerator.php | 49 +++++++++--- src/Generators/Services/GeneratorService.php | 76 +++++++++---------- .../controller-api-with-upload-file.stub | 20 ++++- .../upload-files/cast-image-index.stub | 10 +++ .../upload-files/cast-image-show.stub | 5 ++ 5 files changed, 110 insertions(+), 50 deletions(-) create mode 100644 stubs/generators/controllers/upload-files/cast-image-index.stub create mode 100644 stubs/generators/controllers/upload-files/cast-image-show.stub diff --git a/src/Generators/ControllerGenerator.php b/src/Generators/ControllerGenerator.php index ce4c3452..3365de9f 100644 --- a/src/Generators/ControllerGenerator.php +++ b/src/Generators/ControllerGenerator.php @@ -252,32 +252,40 @@ public function generate(array $request): void $updateCode = ""; $deleteCode = ""; + $castImageIndex = ""; + foreach ($request['input_types'] as $i => $input) { if ($input == 'file') { - $indexCode .= $this->generateUploadFileCode( + $indexCode .= $this->generateUploadImageCode( field: $request['fields'][$i], path: 'index', defaultValue: $request['default_values'][$i], model: $modelNameSingularCamelCase ); - $storeCode .= $this->generateUploadFileCode( + $storeCode .= $this->generateUploadImageCode( field: $request['fields'][$i], path: 'store', model: $modelNameSingularCamelCase ); - $updateCode .= $this->generateUploadFileCode( + $updateCode .= $this->generateUploadImageCode( field: $request['fields'][$i], path: 'update', model: $modelNameSingularCamelCase ); - $deleteCode .= $this->generateUploadFileCode( + $deleteCode .= $this->generateUploadImageCode( field: $request['fields'][$i], path: 'delete', model: $modelNameSingularCamelCase ); + + $castImageIndex .= $this->generateCastImageCode( + field: $request['fields'][$i], + path: 'index', + model: $modelNameSingularCamelCase, + ); } } @@ -290,7 +298,7 @@ public function generate(array $request): void $inputMonths = str_replace('$validated = $request->validated();', '', $inputMonths); $updateDataAction = "\$" . $modelNameSingularCamelCase . "->update(\$validated);"; - if ($request['generate_variant'] == 'api') { + if (GeneratorUtils::isGenerateApi()) { $getTemplate = GeneratorUtils::getStub('controllers/controller-api-with-upload-file'); } else { $getTemplate = GeneratorUtils::getStub('controllers/controller-with-upload-file'); @@ -324,7 +332,8 @@ public function generate(array $request): void '{{resourceApiPath}}', '{{modelNameCleanSingular}}', '{{modelNameCleanPlural}}', - '{{relations}}' + '{{relations}}', + '{{castImageIndex}}', ], [ $modelNameSingularPascalCase, @@ -350,13 +359,13 @@ public function generate(array $request): void $path != '' ? "App\Http\Resources\\$path\\$modelNamePluralPascalCase" : "App\Http\Resources\\$modelNamePluralPascalCase", $modelNameCleanSingular, $modelNameCleanPlural, - $relations + $castImageIndex ], $getTemplate ); break; default: - if ($request['generate_variant'] == 'api') { + if (GeneratorUtils::isGenerateApi()) { $getTemplate = GeneratorUtils::getStub('controllers/controller-api'); } else { $getTemplate = GeneratorUtils::getStub('controllers/controller'); @@ -443,7 +452,7 @@ public function generate(array $request): void /** * Generate an upload file code. */ - protected function generateUploadFileCode(string $field, string $path, string $model, ?string $defaultValue = null): string + protected function generateUploadImageCode(string $field, string $path, string $model, ?string $defaultValue = null): string { $replaceString = [ '{{fieldSnakeCase}}', @@ -493,4 +502,26 @@ protected function generateUploadFileCode(string $field, string $path, string $m break; } } + + public function generateCastImageCode(string $field, string $path, string $model, ?string $defaultValue = null): string + { + $stub = str_replace([ + '{{modelNamePluralCamelCase}}', + '{{modelNameSingularCamelCase}}', + '{{field}}', + '{{defaultImage}}', + '{{publicOrStorage}}', + '{{fieldPluralKebabCase}}' + ], [ + GeneratorUtils::pluralCamelCase($model), + GeneratorUtils::singularCamelCase($model), + $field, + config('generator.image.default', 'https://via.placeholder.com/350?text=No+Image+Avaiable'), + config('generator.image.path') == 'storage' ? "storage_path('app/public/uploads/' " : "public_path('uploads/' ", + GeneratorUtils::pluralKebabCase($field), + + ], GeneratorUtils::getStub('/controllers/upload-files/cast-image-' . $path)); + + return $stub; + } } diff --git a/src/Generators/Services/GeneratorService.php b/src/Generators/Services/GeneratorService.php index 3ba9543f..577d0f6d 100644 --- a/src/Generators/Services/GeneratorService.php +++ b/src/Generators/Services/GeneratorService.php @@ -35,52 +35,52 @@ class GeneratorService implements GeneratorServiceInterface */ public function generate(array $request): void { - if (empty($request['is_simple_generator'])) { - (new PermissionGenerator)->generate($request); - } + // if (empty($request['is_simple_generator'])) { + // (new PermissionGenerator)->generate($request); + // } - (new ModelGenerator)->generate($request); - (new MigrationGenerator)->generate($request); + // (new ModelGenerator)->generate($request); + // (new MigrationGenerator)->generate($request); (new ControllerGenerator)->generate($request); - (new RequestGenerator)->generate($request); - - // api - if (empty($request['generate_variant']) || $request['generate_variant'] != 'api') { - (new IndexViewGenerator)->generate($request); - (new CreateViewGenerator)->generate($request); - (new ShowViewGenerator)->generate($request); - (new EditViewGenerator)->generate($request); - (new ActionViewGenerator)->generate($request); - (new FormViewGenerator)->generate($request); - - if(empty($request['is_simple_generator'])){ - (new MenuGenerator)->generate($request); - } - - if (in_array('foreignId', $request['column_types'])) { - (new ViewComposerGenerator)->generate($request); - } - } + // (new RequestGenerator)->generate($request); + + // // api + // if (empty($request['generate_variant']) || $request['generate_variant'] != 'api') { + // (new IndexViewGenerator)->generate($request); + // (new CreateViewGenerator)->generate($request); + // (new ShowViewGenerator)->generate($request); + // (new EditViewGenerator)->generate($request); + // (new ActionViewGenerator)->generate($request); + // (new FormViewGenerator)->generate($request); + + // if(empty($request['is_simple_generator'])){ + // (new MenuGenerator)->generate($request); + // } - (new RouteGenerator)->generate($request); + // if (in_array('foreignId', $request['column_types'])) { + // (new ViewComposerGenerator)->generate($request); + // } + // } - if(isset($request['generate_seeder']) && $request['generate_seeder'] != null) { - (new SeederGenerator)->generate($request); - } + // (new RouteGenerator)->generate($request); - if(isset($request['generate_factory']) && $request['generate_factory'] != null) { - (new FactoryGenerator)->generate($request); - } + // if(isset($request['generate_seeder']) && $request['generate_seeder'] != null) { + // (new SeederGenerator)->generate($request); + // } - if (GeneratorUtils::isGenerateApi()) { - (new ResourceApiGenerator)->generate($request); - } + // if(isset($request['generate_factory']) && $request['generate_factory'] != null) { + // (new FactoryGenerator)->generate($request); + // } - if (empty($request['generate_variant']) && $request['generate_variant'] != 'api' || empty($request['is_simple_generator'])) { - $this->checkSidebarType(); - } + // if (GeneratorUtils::isGenerateApi()) { + // (new ResourceApiGenerator)->generate($request); + // } + + // if (empty($request['generate_variant']) && $request['generate_variant'] != 'api' || empty($request['is_simple_generator'])) { + // $this->checkSidebarType(); + // } - Artisan::call('migrate'); + // Artisan::call('migrate'); } /** diff --git a/stubs/generators/controllers/controller-api-with-upload-file.stub b/stubs/generators/controllers/controller-api-with-upload-file.stub index 27138a2d..4754897f 100644 --- a/stubs/generators/controllers/controller-api-with-upload-file.stub +++ b/stubs/generators/controllers/controller-api-with-upload-file.stub @@ -11,6 +11,9 @@ use Intervention\Image\Facades\Image; class {{modelNameSingularPascalCase}}Controller extends Controller { + // const ASSET_PATH = '{{assetPath}}'; + // const UPLOAD_PATH = '{{uploadPath}}'; + // TODO: uncomment this code if you are using spatie permission // public function __construct() // { @@ -25,7 +28,11 @@ class {{modelNameSingularPascalCase}}Controller extends Controller */ public function index(): {{modelNameSingularPascalCase}}Collection|{{modelNameSingularPascalCase}}Resource { - return (new {{modelNameSingularPascalCase}}Collection({{modelNameSingularPascalCase}}::{{relations}}paginate()))->additional([ + ${{modelNamePluralCamelCase}} = {{modelNameSingularPascalCase}}::{{relations}}paginate(); + + {{castImageIndex}} + + return (new {{modelNameSingularPascalCase}}Collection(${{modelNamePluralCamelCase}}))->additional([ 'message' => 'The {{modelNameCleanPlural}} was received successfully.', 'success' => true, 'code' => Response::HTTP_OK @@ -57,7 +64,10 @@ class {{modelNameSingularPascalCase}}Controller extends Controller */ public function show(string $id): {{modelNameSingularPascalCase}}Resource { - return (new {{modelNameSingularPascalCase}}Resource({{modelNameSingularPascalCase}}::{{relations}}findOrFail($id)))->additional([ + ${{modelNameSingularCamelCase}} = {{modelNameSingularPascalCase}}::{{relations}}findOrFail($id); + {{castImageShow}} + + return (new {{modelNameSingularPascalCase}}Resource(${{modelNameSingularCamelCase}}))->additional([ 'message' => 'The {{modelNameCleanSingular}} was received successfully.', 'success' => true, 'code' => Response::HTTP_OK @@ -88,7 +98,11 @@ class {{modelNameSingularPascalCase}}Controller extends Controller public function destroy(string $id): {{modelNameSingularPascalCase}}Resource|JsonResponse { try { - {{modelNameSingularPascalCase}}::destroy($id); + ${{modelNameSingularCamelCase}} = {{modelNameSingularPascalCase}}::{{relations}}findOrFail($id); + + {{deleteCode}} + + ${{modelNameSingularCamelCase}}->delete(); return (new {{modelNameSingularPascalCase}}Resource(null)) ->additional([ diff --git a/stubs/generators/controllers/upload-files/cast-image-index.stub b/stubs/generators/controllers/upload-files/cast-image-index.stub new file mode 100644 index 00000000..3e4f2d5c --- /dev/null +++ b/stubs/generators/controllers/upload-files/cast-image-index.stub @@ -0,0 +1,10 @@ + ${{modelNamePluralCamelCase}}->through(function (${{modelNameSingularCamelCase}}) { + if (!${{modelNameSingularCamelCase}}->{{field}}) { + ${{modelNameSingularCamelCase}}->{{field}} = '{{defaultImage}}'; + } else { + ${{modelNameSingularCamelCase}}->{{field}} = {{publicOrStorage}} . {{fieldPluralKebabCase}} . '/' . ${{modelNameSingularCamelCase}}->{{field}}); + } + + return ${{modelNameSingularCamelCase}}; + }); + diff --git a/stubs/generators/controllers/upload-files/cast-image-show.stub b/stubs/generators/controllers/upload-files/cast-image-show.stub new file mode 100644 index 00000000..af42f5d4 --- /dev/null +++ b/stubs/generators/controllers/upload-files/cast-image-show.stub @@ -0,0 +1,5 @@ + if (!${{modelNameSingularCamelCase}}->{{field}}) { + ${{modelNameSingularCamelCase}}->{{field}} = {{defaultImage}}; + } else { + ${{modelNameSingularCamelCase}}->{{field}} = asset(self::ASSET_PATH . ${{modelNameSingularCamelCase}}->{{field}}); + } From cca9b1dcb9786b9aa9a42203de93bc694689433a Mon Sep 17 00:00:00 2001 From: Mohammad Zulfahmi Date: Wed, 10 Jan 2024 19:31:41 +0700 Subject: [PATCH 013/105] wip api generator --- src/Generators/ControllerGenerator.php | 15 +++++++++++++-- .../controller-api-with-upload-file.stub | 3 --- .../upload-files/cast-image-index.stub | 5 ++--- .../controllers/upload-files/cast-image-show.stub | 6 +++--- 4 files changed, 18 insertions(+), 11 deletions(-) diff --git a/src/Generators/ControllerGenerator.php b/src/Generators/ControllerGenerator.php index 3365de9f..73a096af 100644 --- a/src/Generators/ControllerGenerator.php +++ b/src/Generators/ControllerGenerator.php @@ -252,7 +252,10 @@ public function generate(array $request): void $updateCode = ""; $deleteCode = ""; + //cast image in index method $castImageIndex = ""; + // cast image in show method + $castImageShow = ""; foreach ($request['input_types'] as $i => $input) { if ($input == 'file') { @@ -286,6 +289,12 @@ public function generate(array $request): void path: 'index', model: $modelNameSingularCamelCase, ); + + $castImageShow .= $this->generateCastImageCode( + field: $request['fields'][$i], + path: 'show', + model: $modelNameSingularCamelCase, + ); } } @@ -334,6 +343,7 @@ public function generate(array $request): void '{{modelNameCleanPlural}}', '{{relations}}', '{{castImageIndex}}', + '{{castImageShow}}', ], [ $modelNameSingularPascalCase, @@ -359,7 +369,9 @@ public function generate(array $request): void $path != '' ? "App\Http\Resources\\$path\\$modelNamePluralPascalCase" : "App\Http\Resources\\$modelNamePluralPascalCase", $modelNameCleanSingular, $modelNameCleanPlural, - $castImageIndex + $relations, + $castImageIndex, + $castImageShow, ], $getTemplate ); @@ -519,7 +531,6 @@ public function generateCastImageCode(string $field, string $path, string $model config('generator.image.default', 'https://via.placeholder.com/350?text=No+Image+Avaiable'), config('generator.image.path') == 'storage' ? "storage_path('app/public/uploads/' " : "public_path('uploads/' ", GeneratorUtils::pluralKebabCase($field), - ], GeneratorUtils::getStub('/controllers/upload-files/cast-image-' . $path)); return $stub; diff --git a/stubs/generators/controllers/controller-api-with-upload-file.stub b/stubs/generators/controllers/controller-api-with-upload-file.stub index 4754897f..d088ecf2 100644 --- a/stubs/generators/controllers/controller-api-with-upload-file.stub +++ b/stubs/generators/controllers/controller-api-with-upload-file.stub @@ -29,9 +29,7 @@ class {{modelNameSingularPascalCase}}Controller extends Controller public function index(): {{modelNameSingularPascalCase}}Collection|{{modelNameSingularPascalCase}}Resource { ${{modelNamePluralCamelCase}} = {{modelNameSingularPascalCase}}::{{relations}}paginate(); - {{castImageIndex}} - return (new {{modelNameSingularPascalCase}}Collection(${{modelNamePluralCamelCase}}))->additional([ 'message' => 'The {{modelNameCleanPlural}} was received successfully.', 'success' => true, @@ -66,7 +64,6 @@ class {{modelNameSingularPascalCase}}Controller extends Controller { ${{modelNameSingularCamelCase}} = {{modelNameSingularPascalCase}}::{{relations}}findOrFail($id); {{castImageShow}} - return (new {{modelNameSingularPascalCase}}Resource(${{modelNameSingularCamelCase}}))->additional([ 'message' => 'The {{modelNameCleanSingular}} was received successfully.', 'success' => true, diff --git a/stubs/generators/controllers/upload-files/cast-image-index.stub b/stubs/generators/controllers/upload-files/cast-image-index.stub index 3e4f2d5c..40622d08 100644 --- a/stubs/generators/controllers/upload-files/cast-image-index.stub +++ b/stubs/generators/controllers/upload-files/cast-image-index.stub @@ -1,10 +1,9 @@ - ${{modelNamePluralCamelCase}}->through(function (${{modelNameSingularCamelCase}}) { +${{modelNamePluralCamelCase}}->through(function (${{modelNameSingularCamelCase}}) { if (!${{modelNameSingularCamelCase}}->{{field}}) { ${{modelNameSingularCamelCase}}->{{field}} = '{{defaultImage}}'; } else { - ${{modelNameSingularCamelCase}}->{{field}} = {{publicOrStorage}} . {{fieldPluralKebabCase}} . '/' . ${{modelNameSingularCamelCase}}->{{field}}); + ${{modelNameSingularCamelCase}}->{{field}} = {{publicOrStorage}} . '{{fieldPluralKebabCase}}/' . ${{modelNameSingularCamelCase}}->{{field}}); } return ${{modelNameSingularCamelCase}}; }); - diff --git a/stubs/generators/controllers/upload-files/cast-image-show.stub b/stubs/generators/controllers/upload-files/cast-image-show.stub index af42f5d4..840d183b 100644 --- a/stubs/generators/controllers/upload-files/cast-image-show.stub +++ b/stubs/generators/controllers/upload-files/cast-image-show.stub @@ -1,5 +1,5 @@ - if (!${{modelNameSingularCamelCase}}->{{field}}) { - ${{modelNameSingularCamelCase}}->{{field}} = {{defaultImage}}; +if (!${{modelNameSingularCamelCase}}->{{field}}) { + ${{modelNameSingularCamelCase}}->{{field}} = '{{defaultImage}}'; } else { - ${{modelNameSingularCamelCase}}->{{field}} = asset(self::ASSET_PATH . ${{modelNameSingularCamelCase}}->{{field}}); + ${{modelNameSingularCamelCase}}->{{field}} = {{publicOrStorage}} . '{{fieldPluralKebabCase}}/' . ${{modelNameSingularCamelCase}}->{{field}}); } From 6038996d111f581f8e4a83e50237b0dd96472efe Mon Sep 17 00:00:00 2001 From: Mohammad Zulfahmi Date: Thu, 25 Jan 2024 21:52:58 +0700 Subject: [PATCH 014/105] fix cast uploaded image in controller --- src/Generators/ControllerGenerator.php | 6 +- src/Generators/Services/GeneratorService.php | 64 +++++++------------ .../controller-api-with-upload-file.stub | 6 +- .../upload-files/cast-image-index.stub | 2 +- .../upload-files/cast-image-show.stub | 2 +- .../controllers/upload-files/delete.stub | 6 +- .../controllers/upload-files/store.stub | 5 +- .../controllers/upload-files/update.stub | 9 +-- .../upload-files/with-crop/delete.stub | 6 +- .../upload-files/with-crop/store.stub | 5 +- .../upload-files/with-crop/update.stub | 9 +-- 11 files changed, 40 insertions(+), 80 deletions(-) diff --git a/src/Generators/ControllerGenerator.php b/src/Generators/ControllerGenerator.php index 73a096af..dc2ca02a 100644 --- a/src/Generators/ControllerGenerator.php +++ b/src/Generators/ControllerGenerator.php @@ -225,7 +225,7 @@ public function generate(array $request): void if (in_array('month', $request['input_types'])) { if (!in_array('password', $request['input_types'])) { /** - * don't concat string if any input type password, cause already concating ahead. + * don't concat string if any input type password, cause already concat ahead. */ $inputMonths .= $requestValidatedAttr; } @@ -515,7 +515,7 @@ protected function generateUploadImageCode(string $field, string $path, string $ } } - public function generateCastImageCode(string $field, string $path, string $model, ?string $defaultValue = null): string + public function generateCastImageCode(string $field, string $path, string $model): string { $stub = str_replace([ '{{modelNamePluralCamelCase}}', @@ -529,7 +529,7 @@ public function generateCastImageCode(string $field, string $path, string $model GeneratorUtils::singularCamelCase($model), $field, config('generator.image.default', 'https://via.placeholder.com/350?text=No+Image+Avaiable'), - config('generator.image.path') == 'storage' ? "storage_path('app/public/uploads/' " : "public_path('uploads/' ", + config('generator.image.path') == 'storage' ? "storage" : "", GeneratorUtils::pluralKebabCase($field), ], GeneratorUtils::getStub('/controllers/upload-files/cast-image-' . $path)); diff --git a/src/Generators/Services/GeneratorService.php b/src/Generators/Services/GeneratorService.php index 577d0f6d..e20169c6 100644 --- a/src/Generators/Services/GeneratorService.php +++ b/src/Generators/Services/GeneratorService.php @@ -35,52 +35,38 @@ class GeneratorService implements GeneratorServiceInterface */ public function generate(array $request): void { - // if (empty($request['is_simple_generator'])) { - // (new PermissionGenerator)->generate($request); - // } + if (empty($request['is_simple_generator'])) (new PermissionGenerator)->generate($request); - // (new ModelGenerator)->generate($request); - // (new MigrationGenerator)->generate($request); + (new ModelGenerator)->generate($request); + (new MigrationGenerator)->generate($request); (new ControllerGenerator)->generate($request); - // (new RequestGenerator)->generate($request); - - // // api - // if (empty($request['generate_variant']) || $request['generate_variant'] != 'api') { - // (new IndexViewGenerator)->generate($request); - // (new CreateViewGenerator)->generate($request); - // (new ShowViewGenerator)->generate($request); - // (new EditViewGenerator)->generate($request); - // (new ActionViewGenerator)->generate($request); - // (new FormViewGenerator)->generate($request); - - // if(empty($request['is_simple_generator'])){ - // (new MenuGenerator)->generate($request); - // } + (new RequestGenerator)->generate($request); - // if (in_array('foreignId', $request['column_types'])) { - // (new ViewComposerGenerator)->generate($request); - // } - // } + // api + if (empty($request['generate_variant']) || $request['generate_variant'] != 'api') { + (new IndexViewGenerator)->generate($request); + (new CreateViewGenerator)->generate($request); + (new ShowViewGenerator)->generate($request); + (new EditViewGenerator)->generate($request); + (new ActionViewGenerator)->generate($request); + (new FormViewGenerator)->generate($request); - // (new RouteGenerator)->generate($request); + if (empty($request['is_simple_generator'])) (new MenuGenerator)->generate($request); - // if(isset($request['generate_seeder']) && $request['generate_seeder'] != null) { - // (new SeederGenerator)->generate($request); - // } + if (in_array('foreignId', $request['column_types'])) (new ViewComposerGenerator)->generate($request); + } - // if(isset($request['generate_factory']) && $request['generate_factory'] != null) { - // (new FactoryGenerator)->generate($request); - // } + (new RouteGenerator)->generate($request); - // if (GeneratorUtils::isGenerateApi()) { - // (new ResourceApiGenerator)->generate($request); - // } + if (isset($request['generate_seeder']) && $request['generate_seeder'] != null) (new SeederGenerator)->generate($request); - // if (empty($request['generate_variant']) && $request['generate_variant'] != 'api' || empty($request['is_simple_generator'])) { - // $this->checkSidebarType(); - // } + if (isset($request['generate_factory']) && $request['generate_factory'] != null) (new FactoryGenerator)->generate($request); - // Artisan::call('migrate'); + if (GeneratorUtils::isGenerateApi()) (new ResourceApiGenerator)->generate($request); + + if (empty($request['generate_variant']) && $request['generate_variant'] != 'api' || empty($request['is_simple_generator'])) $this->checkSidebarType(); + + Artisan::call('migrate'); } /** @@ -111,9 +97,7 @@ public function checkSidebarType(): void $sidebar = file_get_contents(resource_path('views/layouts/sidebar.blade.php')); /** if the sidebar is static, then must be regenerated to update new menus */ - if (!str($sidebar)->contains("\$permissions = empty(\$menu['permission'])")) { - Artisan::call('generator:sidebar dynamic'); - } + if (!str($sidebar)->contains("\$permissions = empty(\$menu['permission'])")) Artisan::call('generator:sidebar dynamic'); } /** diff --git a/stubs/generators/controllers/controller-api-with-upload-file.stub b/stubs/generators/controllers/controller-api-with-upload-file.stub index d088ecf2..1deae51f 100644 --- a/stubs/generators/controllers/controller-api-with-upload-file.stub +++ b/stubs/generators/controllers/controller-api-with-upload-file.stub @@ -11,9 +11,6 @@ use Intervention\Image\Facades\Image; class {{modelNameSingularPascalCase}}Controller extends Controller { - // const ASSET_PATH = '{{assetPath}}'; - // const UPLOAD_PATH = '{{uploadPath}}'; - // TODO: uncomment this code if you are using spatie permission // public function __construct() // { @@ -98,8 +95,7 @@ class {{modelNameSingularPascalCase}}Controller extends Controller ${{modelNameSingularCamelCase}} = {{modelNameSingularPascalCase}}::{{relations}}findOrFail($id); {{deleteCode}} - - ${{modelNameSingularCamelCase}}->delete(); + ${{modelNameSingularCamelCase}}->delete(); return (new {{modelNameSingularPascalCase}}Resource(null)) ->additional([ diff --git a/stubs/generators/controllers/upload-files/cast-image-index.stub b/stubs/generators/controllers/upload-files/cast-image-index.stub index 40622d08..6d98c124 100644 --- a/stubs/generators/controllers/upload-files/cast-image-index.stub +++ b/stubs/generators/controllers/upload-files/cast-image-index.stub @@ -2,7 +2,7 @@ ${{modelNamePluralCamelCase}}->through(function (${{modelNameSingularCamelCase}} if (!${{modelNameSingularCamelCase}}->{{field}}) { ${{modelNameSingularCamelCase}}->{{field}} = '{{defaultImage}}'; } else { - ${{modelNameSingularCamelCase}}->{{field}} = {{publicOrStorage}} . '{{fieldPluralKebabCase}}/' . ${{modelNameSingularCamelCase}}->{{field}}); + ${{modelNameSingularCamelCase}}->{{field}} = asset('/{{publicOrStorage}}/uploads/{{fieldPluralKebabCase}}/' . ${{modelNameSingularCamelCase}}->{{field}}); } return ${{modelNameSingularCamelCase}}; diff --git a/stubs/generators/controllers/upload-files/cast-image-show.stub b/stubs/generators/controllers/upload-files/cast-image-show.stub index 840d183b..c1c79d46 100644 --- a/stubs/generators/controllers/upload-files/cast-image-show.stub +++ b/stubs/generators/controllers/upload-files/cast-image-show.stub @@ -1,5 +1,5 @@ if (!${{modelNameSingularCamelCase}}->{{field}}) { ${{modelNameSingularCamelCase}}->{{field}} = '{{defaultImage}}'; } else { - ${{modelNameSingularCamelCase}}->{{field}} = {{publicOrStorage}} . '{{fieldPluralKebabCase}}/' . ${{modelNameSingularCamelCase}}->{{field}}); + ${{modelNameSingularCamelCase}}->{{field}} = asset('/{{publicOrStorage}}/uploads/{{fieldPluralKebabCase}}/' . ${{modelNameSingularCamelCase}}->{{field}}); } diff --git a/stubs/generators/controllers/upload-files/delete.stub b/stubs/generators/controllers/upload-files/delete.stub index 1dba3219..facb8ef7 100644 --- a/stubs/generators/controllers/upload-files/delete.stub +++ b/stubs/generators/controllers/upload-files/delete.stub @@ -1,5 +1,3 @@ - $path = {{uploadPath}}/{{fieldPluralSnakeCase}}/'); +$path = {{uploadPath}}/{{fieldPluralSnakeCase}}/'); - if (${{modelNameSingularCamelCase}}->{{fieldSnakeCase}} != null && file_exists($path . ${{modelNameSingularCamelCase}}->{{fieldSnakeCase}})) { - unlink($path . ${{modelNameSingularCamelCase}}->{{fieldSnakeCase}}); - } + if (${{modelNameSingularCamelCase}}->{{fieldSnakeCase}} != null && file_exists($path . ${{modelNameSingularCamelCase}}->{{fieldSnakeCase}})) unlink($path . ${{modelNameSingularCamelCase}}->{{fieldSnakeCase}}); diff --git a/stubs/generators/controllers/upload-files/store.stub b/stubs/generators/controllers/upload-files/store.stub index 69103815..6346d47a 100644 --- a/stubs/generators/controllers/upload-files/store.stub +++ b/stubs/generators/controllers/upload-files/store.stub @@ -1,11 +1,8 @@ if ($request->file('{{fieldSnakeCase}}') && $request->file('{{fieldSnakeCase}}')->isValid()) { - $path = {{uploadPath}}/{{fieldPluralSnakeCase}}/'); $filename = $request->file('{{fieldSnakeCase}}')->hashName(); - if (!file_exists($path)) { - mkdir($path, 0777, true); - } + if (!file_exists($path)) mkdir($path, 0777, true); $request->file('{{fieldSnakeCase}}')->move($path, $filename); diff --git a/stubs/generators/controllers/upload-files/update.stub b/stubs/generators/controllers/upload-files/update.stub index ffa3514f..e0f66748 100644 --- a/stubs/generators/controllers/upload-files/update.stub +++ b/stubs/generators/controllers/upload-files/update.stub @@ -1,18 +1,13 @@ if ($request->file('{{fieldSnakeCase}}') && $request->file('{{fieldSnakeCase}}')->isValid()) { - $path = {{uploadPath}}/{{fieldPluralSnakeCase}}/'); $filename = $request->file('{{fieldSnakeCase}}')->hashName(); - if (!file_exists($path)) { - mkdir($path, 0777, true); - } + if (!file_exists($path)) mkdir($path, 0777, true); $request->file('{{fieldSnakeCase}}')->move($path, $filename); // delete old {{fieldSnakeCase}} from storage - if (${{modelNameSingularCamelCase}}->{{fieldSnakeCase}} != null && file_exists($path . ${{modelNameSingularCamelCase}}->{{fieldSnakeCase}})) { - unlink($path . ${{modelNameSingularCamelCase}}->{{fieldSnakeCase}}); - } + if (${{modelNameSingularCamelCase}}->{{fieldSnakeCase}} != null && file_exists($path . ${{modelNameSingularCamelCase}}->{{fieldSnakeCase}})) unlink($path . ${{modelNameSingularCamelCase}}->{{fieldSnakeCase}}); $validated['{{fieldSnakeCase}}'] = $filename; } diff --git a/stubs/generators/controllers/upload-files/with-crop/delete.stub b/stubs/generators/controllers/upload-files/with-crop/delete.stub index 1dba3219..facb8ef7 100644 --- a/stubs/generators/controllers/upload-files/with-crop/delete.stub +++ b/stubs/generators/controllers/upload-files/with-crop/delete.stub @@ -1,5 +1,3 @@ - $path = {{uploadPath}}/{{fieldPluralSnakeCase}}/'); +$path = {{uploadPath}}/{{fieldPluralSnakeCase}}/'); - if (${{modelNameSingularCamelCase}}->{{fieldSnakeCase}} != null && file_exists($path . ${{modelNameSingularCamelCase}}->{{fieldSnakeCase}})) { - unlink($path . ${{modelNameSingularCamelCase}}->{{fieldSnakeCase}}); - } + if (${{modelNameSingularCamelCase}}->{{fieldSnakeCase}} != null && file_exists($path . ${{modelNameSingularCamelCase}}->{{fieldSnakeCase}})) unlink($path . ${{modelNameSingularCamelCase}}->{{fieldSnakeCase}}); diff --git a/stubs/generators/controllers/upload-files/with-crop/store.stub b/stubs/generators/controllers/upload-files/with-crop/store.stub index 206c636b..4a50061a 100644 --- a/stubs/generators/controllers/upload-files/with-crop/store.stub +++ b/stubs/generators/controllers/upload-files/with-crop/store.stub @@ -1,11 +1,8 @@ if ($request->file('{{fieldSnakeCase}}') && $request->file('{{fieldSnakeCase}}')->isValid()) { - $path = {{uploadPath}}/{{fieldPluralSnakeCase}}/'); $filename = $request->file('{{fieldSnakeCase}}')->hashName(); - if (!file_exists($path)) { - mkdir($path, 0777, true); - } + if (!file_exists($path)) mkdir($path, 0777, true); Image::make($request->file('{{fieldSnakeCase}}')->getRealPath())->resize({{width}}, {{height}}, function ($constraint) { $constraint->upsize();{{aspectRatio}} diff --git a/stubs/generators/controllers/upload-files/with-crop/update.stub b/stubs/generators/controllers/upload-files/with-crop/update.stub index 361be34d..f5528d08 100644 --- a/stubs/generators/controllers/upload-files/with-crop/update.stub +++ b/stubs/generators/controllers/upload-files/with-crop/update.stub @@ -1,20 +1,15 @@ if ($request->file('{{fieldSnakeCase}}') && $request->file('{{fieldSnakeCase}}')->isValid()) { - $path = {{uploadPath}}/{{fieldPluralSnakeCase}}/'); $filename = $request->file('{{fieldSnakeCase}}')->hashName(); - if (!file_exists($path)) { - mkdir($path, 0777, true); - } + if (!file_exists($path)) mkdir($path, 0777, true); Image::make($request->file('{{fieldSnakeCase}}')->getRealPath())->resize({{width}}, {{height}}, function ($constraint) { $constraint->upsize();{{aspectRatio}} })->save($path . $filename); // delete old {{fieldSnakeCase}} from storage - if (${{modelNameSingularCamelCase}}->{{fieldSnakeCase}} != null && file_exists($path . ${{modelNameSingularCamelCase}}->{{fieldSnakeCase}})) { - unlink($path . ${{modelNameSingularCamelCase}}->{{fieldSnakeCase}}); - } + if (${{modelNameSingularCamelCase}}->{{fieldSnakeCase}} != null && file_exists($path . ${{modelNameSingularCamelCase}}->{{fieldSnakeCase}})) unlink($path . ${{modelNameSingularCamelCase}}->{{fieldSnakeCase}}); $validated['{{fieldSnakeCase}}'] = $filename; } From cde0a7f9f22f1dbf421c5b225d36be853e8af388 Mon Sep 17 00:00:00 2001 From: Mohammad Zulfahmi Date: Thu, 15 Feb 2024 18:30:36 +0700 Subject: [PATCH 015/105] refactor code recommended by phpstorm and fix cast image on public storage :hammer: :bug: --- src/Generators/ControllerGenerator.php | 41 ++++++++------------ src/Generators/FactoryGenerator.php | 2 +- src/Generators/MenuGenerator.php | 32 +++++++-------- src/Generators/MigrationGenerator.php | 20 +++------- src/Generators/ModelGenerator.php | 12 ++---- src/Generators/RequestGenerator.php | 24 ++++-------- src/Generators/SeederGenerator.php | 2 +- src/Generators/Services/GeneratorService.php | 2 +- src/Http/Controllers/GeneratorController.php | 2 +- src/Http/Requests/StoreGeneratorRequest.php | 4 +- src/Providers/GeneratorServiceProvider.php | 12 ++---- src/Routes/generator.php | 2 +- 12 files changed, 57 insertions(+), 98 deletions(-) diff --git a/src/Generators/ControllerGenerator.php b/src/Generators/ControllerGenerator.php index dc2ca02a..0e6e0618 100644 --- a/src/Generators/ControllerGenerator.php +++ b/src/Generators/ControllerGenerator.php @@ -100,7 +100,6 @@ public function generate(array $request): void $constrainSnakeCase = GeneratorUtils::singularSnakeCase($constrainName); $selectedColumns = GeneratorUtils::selectColumnAfterIdAndIdItself($constrainName); - $columnAfterId = GeneratorUtils::getColumnAfterId($constrainName); if ($countForeignId + 1 < $i) { $relations .= "'$constrainSnakeCase:$selectedColumns', "; @@ -262,8 +261,8 @@ public function generate(array $request): void $indexCode .= $this->generateUploadImageCode( field: $request['fields'][$i], path: 'index', - defaultValue: $request['default_values'][$i], - model: $modelNameSingularCamelCase + model: $modelNameSingularCamelCase, + defaultValue: $request['default_values'][$i] ); $storeCode .= $this->generateUploadImageCode( @@ -493,31 +492,27 @@ protected function generateUploadImageCode(string $field, string $path, string $ ]; if ($model != null) { - array_push($replaceString, '{{modelNameSingularCamelCase}}'); - array_push($replaceWith, $model); + $replaceString[] = '{{modelNameSingularCamelCase}}'; + $replaceWith[] = $model; } - switch (config('generator.image.crop')) { - case true: - return str_replace( - $replaceString, - $replaceWith, - GeneratorUtils::getStub("controllers/upload-files/with-crop/$path") - ); - break; - default: - return str_replace( - $replaceString, - $replaceWith, - GeneratorUtils::getStub("controllers/upload-files/$path") - ); - break; - } + return match (config('generator.image.crop')) { + true => str_replace( + $replaceString, + $replaceWith, + GeneratorUtils::getStub("controllers/upload-files/with-crop/$path") + ), + default => str_replace( + $replaceString, + $replaceWith, + GeneratorUtils::getStub("controllers/upload-files/$path") + ), + }; } public function generateCastImageCode(string $field, string $path, string $model): string { - $stub = str_replace([ + return str_replace([ '{{modelNamePluralCamelCase}}', '{{modelNameSingularCamelCase}}', '{{field}}', @@ -532,7 +527,5 @@ public function generateCastImageCode(string $field, string $path, string $model config('generator.image.path') == 'storage' ? "storage" : "", GeneratorUtils::pluralKebabCase($field), ], GeneratorUtils::getStub('/controllers/upload-files/cast-image-' . $path)); - - return $stub; } } diff --git a/src/Generators/FactoryGenerator.php b/src/Generators/FactoryGenerator.php index 83b50de9..79f28a66 100644 --- a/src/Generators/FactoryGenerator.php +++ b/src/Generators/FactoryGenerator.php @@ -4,7 +4,7 @@ class FactoryGenerator { - public function generate(array $request) + public function generate(array $request): void { $model = GeneratorUtils::setModelName($request['model'], 'default'); $path = GeneratorUtils::getModelLocation($request['model']); diff --git a/src/Generators/MenuGenerator.php b/src/Generators/MenuGenerator.php index ee7c07fa..23d869e3 100644 --- a/src/Generators/MenuGenerator.php +++ b/src/Generators/MenuGenerator.php @@ -54,10 +54,10 @@ protected function generateNewAllMenu(array $request, string $model, array $conf ); // push new menu to new config sidebar.menu - array_push($newConfigSidebar['menus'], $newMenu); + $newConfigSidebar['menus'][] = $newMenu; // push new config sidebar to old config sidebar - array_push($configSidebar, $newConfigSidebar); + $configSidebar[] = $newConfigSidebar; $stringCode = $this->convertJsonToArrayString($configSidebar); @@ -70,15 +70,15 @@ protected function generateNewAllMenu(array $request, string $model, array $conf protected function generateNewMenu(array $request, string $model, array $configSidebar): void { // push to permissions on header - array_push($configSidebar[$request['header']]['permissions'], GeneratorUtils::cleanSingularLowerCase($model) . ' view'); + $configSidebar[$request['header']]['permissions'][] = GeneratorUtils::cleanSingularLowerCase($model) . ' view'; // push new menu - array_push($configSidebar[$request['header']]['menus'], $this->setNewMenu( + $configSidebar[$request['header']]['menus'][] = $this->setNewMenu( title: GeneratorUtils::cleanPluralUcWords($model), icon: $request['new_icon'], route: '/' . GeneratorUtils::pluralKebabCase($model), - submenu: isset($request['new_submenu']) ? $request['new_submenu'] : null - )); + submenu: $request['new_submenu'] ?? null + ); $stringCode = $this->convertJsonToArrayString($configSidebar); @@ -98,43 +98,37 @@ protected function generateNewSubMenu(array $menu, string $model, array $configS /** * Push to permissions on header */ - array_push($configSidebar[$indexSidebar]['permissions'], $newPermission); + $configSidebar[$indexSidebar]['permissions'][] = $newPermission; /** * If submenus[] is empty, move menu at this index into the submenus[] and make route and permission to null */ if ($configSidebar[$indexSidebar]['menus'][$indexMenu]['submenus'] == []) { - array_push($configSidebar[$indexSidebar]['menus'][$indexMenu]['submenus'], [ + $configSidebar[$indexSidebar]['menus'][$indexMenu]['submenus'][] = [ 'title' => $configSidebar[$indexSidebar]['menus'][$indexMenu]['title'], 'route' => $configSidebar[$indexSidebar]['menus'][$indexMenu]['route'], 'permission' => $configSidebar[$indexSidebar]['menus'][$indexMenu]['permission'], - ]); + ]; /** * Push to permissions on menus */ - array_push( - $configSidebar[$indexSidebar]['menus'][$indexMenu]['permissions'], - $configSidebar[$indexSidebar]['menus'][$indexMenu]['permission'] . "', '" . $newPermission - ); + $configSidebar[$indexSidebar]['menus'][$indexMenu]['permissions'][] = $configSidebar[$indexSidebar]['menus'][$indexMenu]['permission'] . "', '" . $newPermission; $configSidebar[$indexSidebar]['menus'][$indexMenu]['route'] = null; $configSidebar[$indexSidebar]['menus'][$indexMenu]['permission'] = null; } else { - array_push( - $configSidebar[$indexSidebar]['menus'][$indexMenu]['permissions'], - $newPermission - ); + $configSidebar[$indexSidebar]['menus'][$indexMenu]['permissions'][] = $newPermission; } /** * Push new submenu */ - array_push($configSidebar[$indexSidebar]['menus'][$indexMenu]['submenus'], [ + $configSidebar[$indexSidebar]['menus'][$indexMenu]['submenus'][] = [ 'title' => GeneratorUtils::cleanPluralUcWords($model), 'route' => '/' . GeneratorUtils::pluralKebabCase($model), 'permission' => GeneratorUtils::cleanSingularLowerCase($model) . ' view', - ]); + ]; $stringCode = $this->convertJsonToArrayString($configSidebar); diff --git a/src/Generators/MigrationGenerator.php b/src/Generators/MigrationGenerator.php index 0614151f..6ddc86be 100644 --- a/src/Generators/MigrationGenerator.php +++ b/src/Generators/MigrationGenerator.php @@ -170,20 +170,12 @@ public function generate(array $request): void break; } - switch($request['on_delete_foreign'][$i]) { - case ActionForeign::CASCADE->value: - $setFields .= "->cascadeOnDelete();"; - break; - case ActionForeign::RESTRICT->value: - $setFields .= "->restrictOnDelete();"; - break; - case ActionForeign::NULL->value: - $setFields .= "->nullOnDelete();"; - break; - default: - $setFields .= ";"; - break; - } + $setFields .= match ($request['on_delete_foreign'][$i]) { + ActionForeign::CASCADE->value => "->cascadeOnDelete();", + ActionForeign::RESTRICT->value => "->restrictOnDelete();", + ActionForeign::NULL->value => "->nullOnDelete();", + default => ";", + }; } else { $setFields .= ";"; } diff --git a/src/Generators/ModelGenerator.php b/src/Generators/ModelGenerator.php index a0aeb7b7..109a72a0 100644 --- a/src/Generators/ModelGenerator.php +++ b/src/Generators/ModelGenerator.php @@ -34,14 +34,10 @@ public function generate(array $request): void $namespace = !$path ? "namespace App\\Models;" : "namespace App\\Models\\$path;"; foreach ($request['fields'] as $i => $field) { - switch ($i + 1 != $totalFields) { - case true: - $fields .= "'" . str()->snake($field) . "', "; - break; - default: - $fields .= "'" . str()->snake($field) . "']"; - break; - } + $fields .= match ($i + 1 != $totalFields) { + true => "'" . str()->snake($field) . "', ", + default => "'" . str()->snake($field) . "']", + }; if ($request['input_types'][$i] == 'password') { $protectedHidden .= "'" . str()->snake($field) . "', "; diff --git a/src/Generators/RequestGenerator.php b/src/Generators/RequestGenerator.php index 71f6e048..057ba18c 100644 --- a/src/Generators/RequestGenerator.php +++ b/src/Generators/RequestGenerator.php @@ -16,14 +16,10 @@ public function generate(array $request): void $totalFields = count($request['fields']); $modelNamePluralPascalCase = GeneratorUtils::pluralPascalCase($model); - switch ($path) { - case '': - $namespace = "namespace App\Http\Requests\\$modelNamePluralPascalCase;"; - break; - default: - $namespace = "namespace App\Http\Requests\\$path\\$modelNamePluralPascalCase;"; - break; - } + $namespace = match ($path) { + '' => "namespace App\Http\Requests\\$modelNamePluralPascalCase;", + default => "namespace App\Http\Requests\\$path\\$modelNamePluralPascalCase;", + }; foreach ($request['fields'] as $i => $field) { /** @@ -228,14 +224,10 @@ public function generate(array $request): void /** * on update request if any image validation, then set 'required' to nullable */ - switch (str_contains($storeRequestTemplate, "required|image")) { - case true: - $updateValidations = str_replace("required|image", "nullable|image", $validations); - break; - default: - $updateValidations = $validations; - break; - } + $updateValidations = match (str_contains($storeRequestTemplate, "required|image")) { + true => str_replace("required|image", "nullable|image", $validations), + default => $validations, + }; if (isset($uniqueValidation)) { /** diff --git a/src/Generators/SeederGenerator.php b/src/Generators/SeederGenerator.php index be056a1e..ec79c515 100644 --- a/src/Generators/SeederGenerator.php +++ b/src/Generators/SeederGenerator.php @@ -6,7 +6,7 @@ class SeederGenerator { - public function generate(array $request) + public function generate(array $request): void { $model = GeneratorUtils::setModelName($request['model'], 'default'); $path = GeneratorUtils::getModelLocation($request['model']); diff --git a/src/Generators/Services/GeneratorService.php b/src/Generators/Services/GeneratorService.php index e20169c6..6852af9c 100644 --- a/src/Generators/Services/GeneratorService.php +++ b/src/Generators/Services/GeneratorService.php @@ -42,7 +42,7 @@ public function generate(array $request): void (new ControllerGenerator)->generate($request); (new RequestGenerator)->generate($request); - // api + // blade template if (empty($request['generate_variant']) || $request['generate_variant'] != 'api') { (new IndexViewGenerator)->generate($request); (new CreateViewGenerator)->generate($request); diff --git a/src/Http/Controllers/GeneratorController.php b/src/Http/Controllers/GeneratorController.php index fe1fab3f..7232f8cd 100644 --- a/src/Http/Controllers/GeneratorController.php +++ b/src/Http/Controllers/GeneratorController.php @@ -53,7 +53,7 @@ public function getSidebarMenus(int $index): \Illuminate\Http\JsonResponse return response()->json($sidebar['menus'], Response::HTTP_OK); } - public function apiCreate() + public function apiCreate(): \Illuminate\Contracts\View\View { return view('generator::api-create'); } diff --git a/src/Http/Requests/StoreGeneratorRequest.php b/src/Http/Requests/StoreGeneratorRequest.php index de2337a5..45942595 100644 --- a/src/Http/Requests/StoreGeneratorRequest.php +++ b/src/Http/Requests/StoreGeneratorRequest.php @@ -58,9 +58,7 @@ public function rules(): array 'generate_variant' => ['required'], ]; - if(GeneratorUtils::isGenerateApi()){ - return $validations; - } + if(GeneratorUtils::isGenerateApi()) return $validations; return [...$validations, ...$menuValidations]; } diff --git a/src/Providers/GeneratorServiceProvider.php b/src/Providers/GeneratorServiceProvider.php index e69335e1..13677365 100644 --- a/src/Providers/GeneratorServiceProvider.php +++ b/src/Providers/GeneratorServiceProvider.php @@ -93,14 +93,8 @@ public function boot(): void // Illuminate\Foundation\Console\AboutCommand::add('Generator', fn () => ['Version' => '0.2.0']); - if ($this->app->runningInConsole()) { - $this->commands([ - PublishAllFiles::class - ]); - } - - $this->commands([ - SetSidebarType::class - ]); + if ($this->app->runningInConsole()) $this->commands([PublishAllFiles::class]); + + $this->commands([SetSidebarType::class]); } } diff --git a/src/Routes/generator.php b/src/Routes/generator.php index 47e48848..c3219027 100644 --- a/src/Routes/generator.php +++ b/src/Routes/generator.php @@ -7,7 +7,7 @@ use EvdigiIna\Generator\Http\Middleware\TheGeneratorOnlyWorksInTheLocalEnv; use Illuminate\Support\Facades\Route; -Route::middleware(['web', TheGeneratorOnlyWorksInTheLocalEnv::class])->group(function () { +Route::middleware(['web', 'auth', TheGeneratorOnlyWorksInTheLocalEnv::class])->group(function () { Route::get('/generators/get-sidebar-menus/{index}', [GeneratorController::class, 'getSidebarMenus']) ->name('generators.get-sidebar-menus'); From ef24f3c61b8e646d7e392d2f0ce2d92ae8a9cff2 Mon Sep 17 00:00:00 2001 From: Mohammad Zulfahmi Date: Sat, 24 Feb 2024 08:39:26 +0700 Subject: [PATCH 016/105] wip --- src/Generators/ControllerGenerator.php | 53 +++-- src/Generators/GeneratorUtils.php | 217 ++++++++++-------- .../Interfaces/GeneratorUtilsInterface.php | 15 ++ src/Generators/Services/GeneratorService.php | 62 ++--- src/Generators/Views/FormViewGenerator.php | 2 +- src/Generators/Views/ShowViewGenerator.php | 2 +- .../controller-api-with-upload-file.stub | 19 +- .../controllers/controller-api.stub | 2 +- .../upload-files/cast-image-index.stub | 7 +- .../upload-files/cast-image-show.stub | 8 +- .../controllers/upload-files/store.stub | 11 +- .../controllers/upload-files/update.stub | 14 +- .../upload-files/with-crop/store.stub | 13 +- .../upload-files/with-crop/update.stub | 15 +- stubs/generators/publish/ImageService.php | 101 ++++++++ .../publish/config/full-version/generator.php | 29 ++- .../config/simple-version/generator.php | 102 +++++++- .../publish/utils/GeneratorUtils.php | 188 +++++++-------- .../Interfaces/GeneratorUtilsInterface.php | 15 ++ .../Interfaces/ImageServiceInterface.php | 17 ++ 20 files changed, 563 insertions(+), 329 deletions(-) create mode 100644 stubs/generators/publish/ImageService.php create mode 100644 stubs/generators/publish/utils/Interfaces/ImageServiceInterface.php diff --git a/src/Generators/ControllerGenerator.php b/src/Generators/ControllerGenerator.php index 0e6e0618..83d21fd7 100644 --- a/src/Generators/ControllerGenerator.php +++ b/src/Generators/ControllerGenerator.php @@ -27,9 +27,7 @@ public function generate(array $request): void case '': $namespace = "namespace App\Http\Controllers;\n"; - if (GeneratorUtils::isGenerateApi()) { - $namespace = "namespace App\Http\Controllers\Api;\n\nuse App\Http\Controllers\Controller;"; - } + if (GeneratorUtils::isGenerateApi()) $namespace = "namespace App\Http\Controllers\Api;\n\nuse App\Http\Controllers\Controller;"; /** * will generate something like: @@ -48,9 +46,7 @@ public function generate(array $request): void */ $namespace = "namespace App\Http\Controllers\\$path;\n\nuse App\Http\Controllers\Controller;"; - if (GeneratorUtils::isGenerateApi()) { - $namespace = "namespace App\Http\Controllers\Api\\$path;\n\nuse App\Http\Controllers\Controller;"; - } + if (GeneratorUtils::isGenerateApi()) $namespace = "namespace App\Http\Controllers\Api\\$path;\n\nuse App\Http\Controllers\Controller;"; /** * Will generate something like: @@ -218,7 +214,7 @@ public function generate(array $request): void /** * Generate code for insert input type month with datatype date. - * by default will getting an error, cause invalid format. + * by default will get an error, cause invalid format. */ $inputMonths = ""; if (in_array('month', $request['input_types'])) { @@ -255,9 +251,21 @@ public function generate(array $request): void $castImageIndex = ""; // cast image in show method $castImageShow = ""; + $uploadPaths = ""; + $assignUploadPaths = ""; + + /** + * $generators->through(function ($generator) { + * return $generator; + * }); + */ + $castImageIndex .= "$". $modelNamePluralCamelCase ."->through(function ($". $modelNameSingularCamelCase .") {"; foreach ($request['input_types'] as $i => $input) { if ($input == 'file') { + $uploadPaths .= ", public string $" . str($request['fields'][$i])->snake($request['fields'][$i]) . "Path = ''"; + $assignUploadPaths .= "\$this->" . GeneratorUtils::pluralSnakeCase($request['fields'][$i]) . "Path = " . GeneratorUtils::setDiskCodeForController($request['fields'][$i]) . ";\n\t\t"; + $indexCode .= $this->generateUploadImageCode( field: $request['fields'][$i], path: 'index', @@ -297,6 +305,15 @@ public function generate(array $request): void } } + /** + * if (!$generator->image) { + * $generator->image = 'https://via.placeholder.com/350?text=No+Image+Avaiable'; + * } else { + * $generator->image = asset('/uploads/images/' . $generator->image); + * } + */ + $castImageIndex .= "\n\t\t\treturn $". $modelNameSingularCamelCase .";\n\t\t\t});"; + /** * Remove $validated = $request->validated(); because is already exist in template (.stub) */ @@ -343,6 +360,8 @@ public function generate(array $request): void '{{relations}}', '{{castImageIndex}}', '{{castImageShow}}', + '{{uploadPaths}}', + '{{assignUploadPaths}}' ], [ $modelNameSingularPascalCase, @@ -371,6 +390,8 @@ public function generate(array $request): void $relations, $castImageIndex, $castImageShow, + $uploadPaths, + $assignUploadPaths ], $getTemplate ); @@ -407,7 +428,8 @@ public function generate(array $request): void '{{resourceApiPath}}', '{{modelNameCleanSingular}}', '{{modelNameCleanPlural}}', - '{{relations}}' + '{{relations}}', + '{{publicOrStorage}}', ], [ $modelNameSingularPascalCase, @@ -430,7 +452,8 @@ public function generate(array $request): void $path != '' ? "App\Http\Resources\\$path\\$modelNamePluralPascalCase" : "App\Http\Resources\\$modelNamePluralPascalCase", $modelNameCleanSingular, $modelNameCleanPlural, - $relations + $relations, + config('generator.image.disk', 'storage'), ], $getTemplate ); @@ -475,6 +498,8 @@ protected function generateUploadImageCode(string $field, string $path, string $ '{{height}}', '{{aspectRatio}}', '{{defaultImageCode}}', + '{{fieldUploadPath}}', + '{{defaultImage}}' ]; $default = GeneratorUtils::setDefaultImage(default: $defaultValue, field: $field, model: $model); @@ -483,12 +508,14 @@ protected function generateUploadImageCode(string $field, string $path, string $ str()->snake($field), GeneratorUtils::pluralSnakeCase($field), GeneratorUtils::pluralKebabCase($field), - config('generator.image.path') == 'storage' ? "storage_path('app/public/uploads" : "public_path('uploads", - config('generator.image.path') == 'storage' ? "storage/uploads" : "uploads", + config('generator.image.disk') == 'storage' ? "storage_path('app/public/uploads" : "public_path('uploads", + config('generator.image.disk') == 'storage' ? "storage/uploads" : "uploads", is_int(config('generator.image.width')) ? config('generator.image.width') : 500, is_int(config('generator.image.height')) ? config('generator.image.height') : 500, config('generator.image.aspect_ratio') ? "\n\t\t\t\t\$constraint->aspectRatio();" : '', $default['index_code'], + str($field)->snake(), + "$" . GeneratorUtils::singularCamelCase($field) . "->" . str($field)->snake() ]; if ($model != null) { @@ -517,14 +544,14 @@ public function generateCastImageCode(string $field, string $path, string $model '{{modelNameSingularCamelCase}}', '{{field}}', '{{defaultImage}}', - '{{publicOrStorage}}', + '{{castImage}}', '{{fieldPluralKebabCase}}' ], [ GeneratorUtils::pluralCamelCase($model), GeneratorUtils::singularCamelCase($model), $field, config('generator.image.default', 'https://via.placeholder.com/350?text=No+Image+Avaiable'), - config('generator.image.path') == 'storage' ? "storage" : "", + GeneratorUtils::setDiskCodeForCastImage($model, $field), GeneratorUtils::pluralKebabCase($field), ], GeneratorUtils::getStub('/controllers/upload-files/cast-image-' . $path)); } diff --git a/src/Generators/GeneratorUtils.php b/src/Generators/GeneratorUtils.php index 985980f8..1192c083 100644 --- a/src/Generators/GeneratorUtils.php +++ b/src/Generators/GeneratorUtils.php @@ -28,9 +28,7 @@ public static function getPublishedFiles(string $path): string */ public static function checkFolder(string $path): void { - if (!file_exists($path)) { - mkdir($path, 0777, true); - } + if (!file_exists($path)) mkdir($path, 0777, true); } /** @@ -41,11 +39,9 @@ public static function singularPascalCase(string $string): string /** * check string ended with 'ia' or 'ium' */ - if (substr($string, -2) == 'ia' || substr($string, -3) == 'ium') { - return ucfirst(str(GeneratorUtils::fromCamelCase($string))->camel()); - } + if (str_ends_with($string, 'ia') || str_ends_with($string, 'ium')) return ucfirst(str(self::fromCamelCase($string))->camel()); - return ucfirst(str(GeneratorUtils::fromCamelCase($string))->singular()->camel()); + return ucfirst(str(self::fromCamelCase($string))->singular()->camel()); } /** @@ -53,7 +49,7 @@ public static function singularPascalCase(string $string): string */ public static function pascalCase(string $string): string { - return ucfirst(str(GeneratorUtils::fromCamelCase($string))->camel()); + return ucfirst(str(self::fromCamelCase($string))->camel()); } /** @@ -64,11 +60,9 @@ public static function pluralPascalCase(string $string): string /** * check string ended with 'ia' or 'ium' */ - if (substr($string, -2) == 'ia' || substr($string, -3) == 'ium') { - return ucfirst(str(GeneratorUtils::fromCamelCase($string))->camel()) . 's'; - } + if (str_ends_with($string, 'ia') || str_ends_with($string, 'ium')) return ucfirst(str(self::fromCamelCase($string))->camel()) . 's'; - return ucfirst(str(GeneratorUtils::fromCamelCase($string))->plural()->camel()); + return ucfirst(str(self::fromCamelCase($string))->plural()->camel()); } /** @@ -79,11 +73,9 @@ public static function pluralSnakeCase(string $string): string /** * check string ended with 'ia' or 'ium' */ - if (substr($string, -2) == 'ia' || substr($string, -3) == 'ium') { - return str(GeneratorUtils::fromCamelCase($string))->snake()->lower() . 's'; - } + if (str_ends_with($string, 'ia') || str_ends_with($string, 'ium')) return str(self::fromCamelCase($string))->snake()->lower() . 's'; - return str(GeneratorUtils::fromCamelCase($string))->plural()->snake()->lower(); + return str(self::fromCamelCase($string))->plural()->snake()->lower(); } /** @@ -94,11 +86,9 @@ public static function singularSnakeCase(string $string): string /** * check string ended with 'ia' or 'ium' */ - if (substr($string, -2) == 'ia' || substr($string, -3) == 'ium') { - return str(GeneratorUtils::fromCamelCase($string))->snake()->lower(); - } + if (str_ends_with($string, 'ia') || str_ends_with($string, 'ium')) return str(self::fromCamelCase($string))->snake()->lower(); - return str(GeneratorUtils::fromCamelCase($string))->singular()->snake()->lower(); + return str(self::fromCamelCase($string))->singular()->snake()->lower(); } /** @@ -109,11 +99,9 @@ public static function pluralCamelCase(string $string): string /** * check string ended with 'ia' or 'ium' */ - if (substr($string, -2) == 'ia' || substr($string, -3) == 'ium') { - return str(GeneratorUtils::fromCamelCase($string))->camel() . 's'; - } + if (str_ends_with($string, 'ia') || str_ends_with($string, 'ium')) return str(self::fromCamelCase($string))->camel() . 's'; - return str(GeneratorUtils::fromCamelCase($string))->plural()->camel(); + return str(self::fromCamelCase($string))->plural()->camel(); } /** @@ -124,11 +112,9 @@ public static function singularCamelCase(string $string): string /** * check string ended with 'ia' or 'ium' */ - if (substr($string, -2) == 'ia' || substr($string, -3) == 'ium') { - return str(GeneratorUtils::fromCamelCase($string))->camel(); - } + if (str_ends_with($string, 'ia') || str_ends_with($string, 'ium')) return str(self::fromCamelCase($string))->camel(); - return str(GeneratorUtils::fromCamelCase($string))->singular()->camel(); + return str(self::fromCamelCase($string))->singular()->camel(); } /** @@ -139,11 +125,9 @@ public static function pluralKebabCase(string $string): string /** * check string ended with 'ia' or 'ium' */ - if (substr($string, -2) == 'ia' || substr($string, -3) == 'ium') { - return str(preg_replace('/[^A-Za-z0-9() -]/', ' ', GeneratorUtils::fromCamelCase($string)))->kebab()->lower() . 's'; - } + if (str_ends_with($string, 'ia') || str_ends_with($string, 'ium')) return str(preg_replace('/[^A-Za-z0-9() -]/', ' ', self::fromCamelCase($string)))->kebab()->lower() . 's'; - return str(preg_replace('/[^A-Za-z0-9() -]/', ' ', GeneratorUtils::fromCamelCase($string)))->plural()->kebab()->lower(); + return str(preg_replace('/[^A-Za-z0-9() -]/', ' ', self::fromCamelCase($string)))->plural()->kebab()->lower(); } /** @@ -151,7 +135,7 @@ public static function pluralKebabCase(string $string): string */ public static function kebabCase(string $string): string { - return str(preg_replace('/[^A-Za-z0-9() -]/', ' ', GeneratorUtils::fromCamelCase($string)))->kebab()->lower(); + return str(preg_replace('/[^A-Za-z0-9() -]/', ' ', self::fromCamelCase($string)))->kebab()->lower(); } /** @@ -162,11 +146,9 @@ public static function singularKebabCase(string $string): string /** * check string ended with 'ia' or 'ium' */ - if (substr($string, -2) == 'ia' || substr($string, -3) == 'ium') { - return str(preg_replace('/[^A-Za-z0-9() -]/', ' ', GeneratorUtils::fromCamelCase($string)))->kebab()->lower(); - } + if (str_ends_with($string, 'ia') || str_ends_with($string, 'ium')) return str(preg_replace('/[^A-Za-z0-9() -]/', ' ', self::fromCamelCase($string)))->kebab()->lower(); - return str(preg_replace('/[^A-Za-z0-9() -]/', ' ', GeneratorUtils::fromCamelCase($string)))->singular()->kebab()->lower(); + return str(preg_replace('/[^A-Za-z0-9() -]/', ' ', self::fromCamelCase($string)))->singular()->kebab()->lower(); } /** @@ -177,11 +159,9 @@ public static function cleanSingularLowerCase(string $string): string /** * check string ended with 'ia' or 'ium' */ - if (substr($string, -2) == 'ia' || substr($string, -3) == 'ium') { - return str(preg_replace('/[^A-Za-z0-9() -]/', ' ', GeneratorUtils::fromCamelCase($string)))->lower(); - } + if (str_ends_with($string, 'ia') || str_ends_with($string, 'ium')) return str(preg_replace('/[^A-Za-z0-9() -]/', ' ', self::fromCamelCase($string)))->lower(); - return str(preg_replace('/[^A-Za-z0-9() -]/', ' ', GeneratorUtils::fromCamelCase($string)))->singular()->lower(); + return str(preg_replace('/[^A-Za-z0-9() -]/', ' ', self::fromCamelCase($string)))->singular()->lower(); } /** @@ -189,7 +169,7 @@ public static function cleanSingularLowerCase(string $string): string */ public static function cleanLowerCase(string $string): string { - return str(preg_replace('/[^A-Za-z0-9() -]/', ' ', GeneratorUtils::fromCamelCase($string)))->lower(); + return str(preg_replace('/[^A-Za-z0-9() -]/', ' ', self::fromCamelCase($string)))->lower(); } /** @@ -200,11 +180,9 @@ public static function cleanPluralUcWords(string $string): string /** * check string ended with 'ia' or 'ium' */ - if (substr($string, -2) == 'ia' || substr($string, -3) == 'ium') { - return ucwords(str(preg_replace('/[^A-Za-z0-9() -]/', ' ', GeneratorUtils::fromCamelCase($string)))->lower()) . 's'; - } + if (str_ends_with($string, 'ia') || str_ends_with($string, 'ium')) return ucwords(str(preg_replace('/[^A-Za-z0-9() -]/', ' ', self::fromCamelCase($string)))->lower()) . 's'; - return ucwords(str(preg_replace('/[^A-Za-z0-9() -]/', ' ', GeneratorUtils::fromCamelCase($string)))->plural()->lower()); + return ucwords(str(preg_replace('/[^A-Za-z0-9() -]/', ' ', self::fromCamelCase($string)))->plural()->lower()); } /** @@ -215,11 +193,9 @@ public static function cleanSingularUcWords(string $string): string /** * check string ended with 'ia' or 'ium' */ - if (substr($string, -2) == 'ia' || substr($string, -3) == 'ium') { - return ucwords(str(preg_replace('/[^A-Za-z0-9() -]/', ' ', GeneratorUtils::fromCamelCase($string)))->lower()); - } + if (str_ends_with($string, 'ia') || str_ends_with($string, 'ium')) return ucwords(str(preg_replace('/[^A-Za-z0-9() -]/', ' ', self::fromCamelCase($string)))->lower()); - return ucwords(str(preg_replace('/[^A-Za-z0-9() -]/', ' ', GeneratorUtils::fromCamelCase($string)))->singular()->lower()); + return ucwords(str(preg_replace('/[^A-Za-z0-9() -]/', ' ', self::fromCamelCase($string)))->singular()->lower()); } /** @@ -227,7 +203,7 @@ public static function cleanSingularUcWords(string $string): string */ public static function cleanUcWords(string $string): string { - return ucwords(preg_replace('/[^A-Za-z0-9() -]/', ' ', GeneratorUtils::fromCamelCase($string))); + return ucwords(preg_replace('/[^A-Za-z0-9() -]/', ' ', self::fromCamelCase($string))); } /** @@ -238,11 +214,9 @@ public static function cleanPluralLowerCase(string $string): string /** * check string ended with 'ia' or 'ium' */ - if (substr($string, -2) == 'ia' || substr($string, -3) == 'ium') { - return str(preg_replace('/[^A-Za-z0-9() -]/', ' ', GeneratorUtils::fromCamelCase($string)))->lower() . 's'; - } + if (str_ends_with($string, 'ia') || str_ends_with($string, 'ium')) return str(preg_replace('/[^A-Za-z0-9() -]/', ' ', self::fromCamelCase($string)))->lower() . 's'; - return str(preg_replace('/[^A-Za-z0-9() -]/', ' ', GeneratorUtils::fromCamelCase($string)))->plural()->lower(); + return str(preg_replace('/[^A-Za-z0-9() -]/', ' ', self::fromCamelCase($string)))->plural()->lower(); } /** @@ -250,7 +224,7 @@ public static function cleanPluralLowerCase(string $string): string */ public static function getColumnAfterId(string $table): string { - $table = GeneratorUtils::pluralSnakeCase($table); + $table = self::pluralSnakeCase($table); $allColumns = Schema::getColumnListing($table); if (sizeof($allColumns) > 0) { @@ -267,7 +241,7 @@ public static function getColumnAfterId(string $table): string */ public static function selectColumnAfterIdAndIdItself(string $table): string { - $table = GeneratorUtils::pluralSnakeCase($table); + $table = self::pluralSnakeCase($table); $allColumns = Schema::getColumnListing($table); if (sizeof($allColumns) > 0) { @@ -293,10 +267,8 @@ public static function getModelLocation(string $model): string */ $path = ""; for ($i = 0; $i < $totalArrModel - 1; $i++) { - $path .= GeneratorUtils::pluralPascalCase($arrModel[$i]); - if ($i + 1 != $totalArrModel - 1) { - $path .= "\\"; - } + $path .= self::pluralPascalCase($arrModel[$i]); + if ($i + 1 != $totalArrModel - 1) $path .= "\\"; } return $path; @@ -308,6 +280,7 @@ public static function getModelLocation(string $model): string public static function fromCamelCase(string $string): string { $a = preg_split('/(?<=[a-z])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])/x', $string); + return trim(implode(' ', $a)); } @@ -327,13 +300,9 @@ public static function setModelName(string $model, string $style = 'pascal case' /** * check string ended with 'ia' or 'ium' */ - if (substr($actualModelName, -2) == 'ia' || substr($actualModelName, -3) == 'ium') { - return self::pascalCase($actualModelName); - } + if (str_ends_with($actualModelName, 'ia') || str_ends_with($actualModelName, 'ium')) return self::pascalCase($actualModelName); - if ($style == 'pascal case') { - return GeneratorUtils::singularPascalCase($actualModelName); - } + if ($style == 'pascal case') return self::singularPascalCase($actualModelName); return $actualModelName; } @@ -359,7 +328,7 @@ public static function setDefaultImage(null|string $default, string $field, stri * Generated code: * $book->cover == null || $book->cover == 'https://via.placeholder.com/350?text=No+Image+Avaiable'" */ - 'form_code' => "$" . GeneratorUtils::singularCamelCase($model) . "->" . str()->snake($field) . " == null || $" . GeneratorUtils::singularCamelCase($model) . "->" . str()->snake($field) . " == '" . $default . "'", + 'form_code' => "$" . self::singularCamelCase($model) . "->" . str()->snake($field) . " == null || $" . self::singularCamelCase($model) . "->" . str()->snake($field) . " == '" . $default . "'", ]; } @@ -380,7 +349,7 @@ public static function setDefaultImage(null|string $default, string $field, stri * * $book->photo == null */ - 'form_code' => "$" . GeneratorUtils::singularCamelCase($model) . "->" . str()->snake($field) . " == null", + 'form_code' => "$" . self::singularCamelCase($model) . "->" . str()->snake($field) . " == null", ]; } @@ -389,7 +358,7 @@ public static function setDefaultImage(null|string $default, string $field, stri 'index_code' => "if (\$row->" . str()->snake($field) . " == null) { return 'https://via.placeholder.com/350?text=No+Image+Avaiable'; }", - 'form_code' => "$" . GeneratorUtils::singularCamelCase($model) . "->" . str()->snake($field) . " == null", + 'form_code' => "$" . self::singularCamelCase($model) . "->" . str()->snake($field) . " == null", ]; } @@ -400,9 +369,7 @@ public static function convertArraySidebarToString(array $sidebars): string { $menu = ""; - foreach ($sidebars as $sidebar) { - $menu .= "'" . $sidebar . "', "; - } + foreach ($sidebars as $sidebar) $menu .= "'" . $sidebar . "', "; return $menu; } @@ -415,53 +382,103 @@ public static function isActiveMenu(string|array $route): string $activeClass = ' active'; if (is_string($route)) { - if (request()->is(substr($route . '*', 1))) { - return $activeClass; - } + if (request()->is(substr($route . '*', 1))) return $activeClass; - if (request()->is(str($route)->slug() . '*')) { - return $activeClass; - } + if (request()->is(str($route)->slug() . '*')) return $activeClass; - if (request()->segment(2) == str($route)->before('/')) { - return $activeClass; - } + if (request()->segment(2) == str($route)->before('/')) return $activeClass; - if (request()->segment(3) == str($route)->after('/')) { - return $activeClass; - } + if (request()->segment(3) == str($route)->after('/')) return $activeClass; } if (is_array($route)) { foreach ($route as $value) { $actualRoute = str($value)->remove(' view')->plural(); - if (request()->is(substr($actualRoute . '*', 1))) { - return $activeClass; - } + if (request()->is(substr($actualRoute . '*', 1))) return $activeClass; - if (request()->is(str($actualRoute)->slug() . '*')) { - return $activeClass; - } + if (request()->is(str($actualRoute)->slug() . '*')) return $activeClass; - if (request()->segment(2) == $actualRoute) { - return $activeClass; - } + if (request()->segment(2) == $actualRoute) return $activeClass; - if (request()->segment(3) == $actualRoute) { - return $activeClass; - } + if (request()->segment(3) == $actualRoute) return $activeClass; } } return ''; } - /** - * Check if generate blade(default) or api. - */ public static function isGenerateApi(): bool { return request()->filled('generate_variant') && request()->get('generate_variant') == 'api'; } + + /** + * Check if package exist in composer. + */ + public static function checkPackage(string $name): bool + { + if(self::getComposerPackage($name) == '{') return false; + + return true; + } + + /** + * Check if package exist in composer and return version. + * @throws \Exception + */ + public static function checkPackageVersion(string $name, bool $strict = false): string + { + $str = self::getComposerPackage($name); + + if(str_contains($str, '{')){ + $message = 'The package '.$name.' is not installed.'; + + if($strict) throw new \Exception($message); + + return $message; + } + + return $str; + + } + + /** + * Check package in composer.json + */ + public static function getComposerPackage(string $name): string + { + $composer = file_get_contents(base_path('composer.json')); + + return str($composer)->after('"'.$name.'": "')->before('"'); + } + + public static function setDiskCodeForController(string $name): string + { + switch(config('generator.image.disk')){ + case 's3': + return "/$name"; + break; + case 'public': + return "public_path('uploads/$name/')"; + break; + default: + return "storage_path('app/public/uploads/$name/')"; + break; + } + } + + public static function setDiskCodeForCastImage(string $model, string $field): string + { + switch(config('generator.image.disk')){ + case 's3': + break; + case 'public': + return "asset('/uploads/". self::pluralKebabCase($field) ."/' . $". self::singularCamelCase($model) ."->". str($field)->snake() .")"; + break; + default: + return "asset('storage/uploads/". self::pluralKebabCase($field) ."/' . $". self::singularCamelCase($model) ."->". str($field)->snake() .");"; + break; + } + } } diff --git a/src/Generators/Interfaces/GeneratorUtilsInterface.php b/src/Generators/Interfaces/GeneratorUtilsInterface.php index e867915a..49ad2a24 100644 --- a/src/Generators/Interfaces/GeneratorUtilsInterface.php +++ b/src/Generators/Interfaces/GeneratorUtilsInterface.php @@ -142,4 +142,19 @@ public static function isActiveMenu(string|array $route): string; * Check if generate blade(default) or api. */ public static function isGenerateApi(): bool; + + /** + * Check if package exist in composer. + */ + public static function checkPackage(string $name): bool; + + /** + * Check if package exist in composer and return version. + */ + public static function checkPackageVersion(string $name): string; + + /** + * Check package in composer.json + */ + public static function getComposerPackage(string $name): string; } diff --git a/src/Generators/Services/GeneratorService.php b/src/Generators/Services/GeneratorService.php index 6852af9c..ead07117 100644 --- a/src/Generators/Services/GeneratorService.php +++ b/src/Generators/Services/GeneratorService.php @@ -35,38 +35,38 @@ class GeneratorService implements GeneratorServiceInterface */ public function generate(array $request): void { - if (empty($request['is_simple_generator'])) (new PermissionGenerator)->generate($request); - - (new ModelGenerator)->generate($request); - (new MigrationGenerator)->generate($request); +// if (empty($request['is_simple_generator'])) (new PermissionGenerator)->generate($request); +// +// (new ModelGenerator)->generate($request); +// (new MigrationGenerator)->generate($request); (new ControllerGenerator)->generate($request); - (new RequestGenerator)->generate($request); - - // blade template - if (empty($request['generate_variant']) || $request['generate_variant'] != 'api') { - (new IndexViewGenerator)->generate($request); - (new CreateViewGenerator)->generate($request); - (new ShowViewGenerator)->generate($request); - (new EditViewGenerator)->generate($request); - (new ActionViewGenerator)->generate($request); - (new FormViewGenerator)->generate($request); - - if (empty($request['is_simple_generator'])) (new MenuGenerator)->generate($request); - - if (in_array('foreignId', $request['column_types'])) (new ViewComposerGenerator)->generate($request); - } - - (new RouteGenerator)->generate($request); - - if (isset($request['generate_seeder']) && $request['generate_seeder'] != null) (new SeederGenerator)->generate($request); - - if (isset($request['generate_factory']) && $request['generate_factory'] != null) (new FactoryGenerator)->generate($request); - - if (GeneratorUtils::isGenerateApi()) (new ResourceApiGenerator)->generate($request); - - if (empty($request['generate_variant']) && $request['generate_variant'] != 'api' || empty($request['is_simple_generator'])) $this->checkSidebarType(); - - Artisan::call('migrate'); +// (new RequestGenerator)->generate($request); +// +// // blade template +// if (empty($request['generate_variant']) || $request['generate_variant'] != 'api') { +// (new IndexViewGenerator)->generate($request); +// (new CreateViewGenerator)->generate($request); +// (new ShowViewGenerator)->generate($request); +// (new EditViewGenerator)->generate($request); +// (new ActionViewGenerator)->generate($request); +// (new FormViewGenerator)->generate($request); +// +// if (empty($request['is_simple_generator'])) (new MenuGenerator)->generate($request); +// +// if (in_array('foreignId', $request['column_types'])) (new ViewComposerGenerator)->generate($request); +// } +// +// (new RouteGenerator)->generate($request); +// +// if (isset($request['generate_seeder']) && $request['generate_seeder'] != null) (new SeederGenerator)->generate($request); +// +// if (isset($request['generate_factory']) && $request['generate_factory'] != null) (new FactoryGenerator)->generate($request); +// +// if (GeneratorUtils::isGenerateApi()) (new ResourceApiGenerator)->generate($request); +// +// if (empty($request['generate_variant']) && $request['generate_variant'] != 'api' || empty($request['is_simple_generator'])) $this->checkSidebarType(); +// +// Artisan::call('migrate'); } /** diff --git a/src/Generators/Views/FormViewGenerator.php b/src/Generators/Views/FormViewGenerator.php index 13cf8ae0..61c7d311 100644 --- a/src/Generators/Views/FormViewGenerator.php +++ b/src/Generators/Views/FormViewGenerator.php @@ -468,7 +468,7 @@ public function generate(array $request): void GeneratorUtils::cleanSingularLowerCase($field), $fieldUcWords, $request['requireds'][$i] == 'yes' ? ' required' : '', - config('generator.image.path') == 'storage' ? "storage/uploads" : "uploads", + config('generator.image.disk') == 'storage' ? "storage/uploads" : "uploads", str()->kebab($field), $default['image'], $default['form_code'] diff --git a/src/Generators/Views/ShowViewGenerator.php b/src/Generators/Views/ShowViewGenerator.php index 6f2e115c..b54c3082 100644 --- a/src/Generators/Views/ShowViewGenerator.php +++ b/src/Generators/Views/ShowViewGenerator.php @@ -37,7 +37,7 @@ public function generate(array $request): void model: $model ); - $uploadPath = config('generator.image.path') == 'storage' ? "storage/uploads/" : "uploads/"; + $uploadPath = config('generator.image.disk') == 'storage' ? "storage/uploads/" : "uploads/"; $trs .= " {{ __('$fieldUcWords') }} diff --git a/stubs/generators/controllers/controller-api-with-upload-file.stub b/stubs/generators/controllers/controller-api-with-upload-file.stub index 1deae51f..864be939 100644 --- a/stubs/generators/controllers/controller-api-with-upload-file.stub +++ b/stubs/generators/controllers/controller-api-with-upload-file.stub @@ -7,25 +7,26 @@ use {{requestPath}}; use {{resourceApiPath}}\{{{modelNameSingularPascalCase}}Collection, {{modelNameSingularPascalCase}}Resource}; use Symfony\Component\HttpFoundation\Response; use Illuminate\Http\JsonResponse; -use Intervention\Image\Facades\Image; +use App\Services\ImageService; class {{modelNameSingularPascalCase}}Controller extends Controller { // TODO: uncomment this code if you are using spatie permission - // public function __construct() - // { - // $this->middleware('permission:{{modelNameSpaceLowercase}} view')->only('index', 'show'); - // $this->middleware('permission:{{modelNameSpaceLowercase}} create')->only('create', 'store'); - // $this->middleware('permission:{{modelNameSpaceLowercase}} edit')->only('edit', 'update'); - // $this->middleware('permission:{{modelNameSpaceLowercase}} delete')->only('destroy'); - // } + public function __construct(public ImageService $imageService{{uploadPaths}}) + { + {{assignUploadPaths}} + // $this->middleware('permission:{{modelNameSpaceLowercase}} view')->only('index', 'show'); + // $this->middleware('permission:{{modelNameSpaceLowercase}} create')->only('create', 'store'); + // $this->middleware('permission:{{modelNameSpaceLowercase}} edit')->only('edit', 'update'); + // $this->middleware('permission:{{modelNameSpaceLowercase}} delete')->only('destroy'); + } /** * Display a listing of the resource. */ public function index(): {{modelNameSingularPascalCase}}Collection|{{modelNameSingularPascalCase}}Resource { - ${{modelNamePluralCamelCase}} = {{modelNameSingularPascalCase}}::{{relations}}paginate(); + ${{modelNamePluralCamelCase}} = {{modelNameSingularPascalCase}}::{{relations}}latest()->paginate(); {{castImageIndex}} return (new {{modelNameSingularPascalCase}}Collection(${{modelNamePluralCamelCase}}))->additional([ 'message' => 'The {{modelNameCleanPlural}} was received successfully.', diff --git a/stubs/generators/controllers/controller-api.stub b/stubs/generators/controllers/controller-api.stub index 48cb503f..8fc24973 100644 --- a/stubs/generators/controllers/controller-api.stub +++ b/stubs/generators/controllers/controller-api.stub @@ -24,7 +24,7 @@ class {{modelNameSingularPascalCase}}Controller extends Controller */ public function index(): {{modelNameSingularPascalCase}}Collection|{{modelNameSingularPascalCase}}Resource { - return (new {{modelNameSingularPascalCase}}Collection({{modelNameSingularPascalCase}}::{{relations}}paginate()))->additional([ + return (new {{modelNameSingularPascalCase}}Collection({{modelNameSingularPascalCase}}::{{relations}}latest()->paginate()))->additional([ 'message' => 'The {{modelNameCleanPlural}} was received successfully.', 'success' => true, 'code' => Response::HTTP_OK diff --git a/stubs/generators/controllers/upload-files/cast-image-index.stub b/stubs/generators/controllers/upload-files/cast-image-index.stub index 6d98c124..579544ee 100644 --- a/stubs/generators/controllers/upload-files/cast-image-index.stub +++ b/stubs/generators/controllers/upload-files/cast-image-index.stub @@ -1,9 +1,6 @@ -${{modelNamePluralCamelCase}}->through(function (${{modelNameSingularCamelCase}}) { + if (!${{modelNameSingularCamelCase}}->{{field}}) { ${{modelNameSingularCamelCase}}->{{field}} = '{{defaultImage}}'; } else { - ${{modelNameSingularCamelCase}}->{{field}} = asset('/{{publicOrStorage}}/uploads/{{fieldPluralKebabCase}}/' . ${{modelNameSingularCamelCase}}->{{field}}); + ${{modelNameSingularCamelCase}}->{{field}} = {{castImage}}; } - - return ${{modelNameSingularCamelCase}}; - }); diff --git a/stubs/generators/controllers/upload-files/cast-image-show.stub b/stubs/generators/controllers/upload-files/cast-image-show.stub index c1c79d46..cf8c4b7d 100644 --- a/stubs/generators/controllers/upload-files/cast-image-show.stub +++ b/stubs/generators/controllers/upload-files/cast-image-show.stub @@ -1,5 +1,5 @@ if (!${{modelNameSingularCamelCase}}->{{field}}) { - ${{modelNameSingularCamelCase}}->{{field}} = '{{defaultImage}}'; - } else { - ${{modelNameSingularCamelCase}}->{{field}} = asset('/{{publicOrStorage}}/uploads/{{fieldPluralKebabCase}}/' . ${{modelNameSingularCamelCase}}->{{field}}); - } + ${{modelNameSingularCamelCase}}->{{field}} = '{{defaultImage}}'; + } else { + ${{modelNameSingularCamelCase}}->{{field}} = {{castImage}}; + } diff --git a/stubs/generators/controllers/upload-files/store.stub b/stubs/generators/controllers/upload-files/store.stub index 6346d47a..baad4221 100644 --- a/stubs/generators/controllers/upload-files/store.stub +++ b/stubs/generators/controllers/upload-files/store.stub @@ -1,10 +1 @@ - if ($request->file('{{fieldSnakeCase}}') && $request->file('{{fieldSnakeCase}}')->isValid()) { - $path = {{uploadPath}}/{{fieldPluralSnakeCase}}/'); - $filename = $request->file('{{fieldSnakeCase}}')->hashName(); - - if (!file_exists($path)) mkdir($path, 0777, true); - - $request->file('{{fieldSnakeCase}}')->move($path, $filename); - - $validated['{{fieldSnakeCase}}'] = $filename; - } + $validated['{{fieldSnakeCase}}'] = $this->imageService->upload(name: '{{fieldSnakeCase}}', path: $this->{{fieldUploadPath}}Path); diff --git a/stubs/generators/controllers/upload-files/update.stub b/stubs/generators/controllers/upload-files/update.stub index e0f66748..da0c3f23 100644 --- a/stubs/generators/controllers/upload-files/update.stub +++ b/stubs/generators/controllers/upload-files/update.stub @@ -1,13 +1 @@ - if ($request->file('{{fieldSnakeCase}}') && $request->file('{{fieldSnakeCase}}')->isValid()) { - $path = {{uploadPath}}/{{fieldPluralSnakeCase}}/'); - $filename = $request->file('{{fieldSnakeCase}}')->hashName(); - - if (!file_exists($path)) mkdir($path, 0777, true); - - $request->file('{{fieldSnakeCase}}')->move($path, $filename); - - // delete old {{fieldSnakeCase}} from storage - if (${{modelNameSingularCamelCase}}->{{fieldSnakeCase}} != null && file_exists($path . ${{modelNameSingularCamelCase}}->{{fieldSnakeCase}})) unlink($path . ${{modelNameSingularCamelCase}}->{{fieldSnakeCase}}); - - $validated['{{fieldSnakeCase}}'] = $filename; - } + $validated['{{fieldSnakeCase}}'] = $this->imageService->upload(name: '{{fieldSnakeCase}}', path: $this->{{fieldUploadPath}}Path, defaultImage: {{defaultImage}}); diff --git a/stubs/generators/controllers/upload-files/with-crop/store.stub b/stubs/generators/controllers/upload-files/with-crop/store.stub index 4a50061a..baad4221 100644 --- a/stubs/generators/controllers/upload-files/with-crop/store.stub +++ b/stubs/generators/controllers/upload-files/with-crop/store.stub @@ -1,12 +1 @@ - if ($request->file('{{fieldSnakeCase}}') && $request->file('{{fieldSnakeCase}}')->isValid()) { - $path = {{uploadPath}}/{{fieldPluralSnakeCase}}/'); - $filename = $request->file('{{fieldSnakeCase}}')->hashName(); - - if (!file_exists($path)) mkdir($path, 0777, true); - - Image::make($request->file('{{fieldSnakeCase}}')->getRealPath())->resize({{width}}, {{height}}, function ($constraint) { - $constraint->upsize();{{aspectRatio}} - })->save($path . $filename); - - $validated['{{fieldSnakeCase}}'] = $filename; - } + $validated['{{fieldSnakeCase}}'] = $this->imageService->upload(name: '{{fieldSnakeCase}}', path: $this->{{fieldUploadPath}}Path); diff --git a/stubs/generators/controllers/upload-files/with-crop/update.stub b/stubs/generators/controllers/upload-files/with-crop/update.stub index f5528d08..15185534 100644 --- a/stubs/generators/controllers/upload-files/with-crop/update.stub +++ b/stubs/generators/controllers/upload-files/with-crop/update.stub @@ -1,15 +1,2 @@ - if ($request->file('{{fieldSnakeCase}}') && $request->file('{{fieldSnakeCase}}')->isValid()) { - $path = {{uploadPath}}/{{fieldPluralSnakeCase}}/'); - $filename = $request->file('{{fieldSnakeCase}}')->hashName(); + $validated['{{fieldSnakeCase}}'] = $this->imageService->upload(name: '{{fieldSnakeCase}}', path: {{uploadPath}}/{{fieldPluralSnakeCase}}/')); - if (!file_exists($path)) mkdir($path, 0777, true); - - Image::make($request->file('{{fieldSnakeCase}}')->getRealPath())->resize({{width}}, {{height}}, function ($constraint) { - $constraint->upsize();{{aspectRatio}} - })->save($path . $filename); - - // delete old {{fieldSnakeCase}} from storage - if (${{modelNameSingularCamelCase}}->{{fieldSnakeCase}} != null && file_exists($path . ${{modelNameSingularCamelCase}}->{{fieldSnakeCase}})) unlink($path . ${{modelNameSingularCamelCase}}->{{fieldSnakeCase}}); - - $validated['{{fieldSnakeCase}}'] = $filename; - } diff --git a/stubs/generators/publish/ImageService.php b/stubs/generators/publish/ImageService.php new file mode 100644 index 00000000..0970cd00 --- /dev/null +++ b/stubs/generators/publish/ImageService.php @@ -0,0 +1,101 @@ +file($name) && request()->file($name)->isValid()) { + $file = request()->file($name); + + if (str_contains(GeneratorUtils::checkPackageVersion('intervention/image-laravel'), '2')) { + $filename = $file->hashName(); + }else{ + // set image to webp + $filename = str()->random(20) . '.webp'; + } + + // s3 or local + switch (config('generator.image.disk', $disk)) { + case 's3': + if (str_contains(GeneratorUtils::checkPackageVersion('intervention/image-laravel'), '2')) { + // for intervention v2 + $image = \Intervention\Image\Facades\Image::make($file)->resize($width, $height, config('generator.image.crop') ? function ($constraint) { + $constraint->aspectRatio(); + $constraint->upsize(); + } : null)->encode($file->extension()); + + } else { + // for intervention v3 + $imageInstance = \Intervention\Image\Laravel\Facades\Image::read($file); + + if(config('generator.image.crop')){ + // constraint aspect ratio + $image = $imageInstance->resizeDown($width, $height)->encode(new \Intervention\Image\Encoders\WebpEncoder(quality: 65)); + }else{ + $image = $imageInstance->resize($width, $height)->encode(new \Intervention\Image\Encoders\WebpEncoder(quality: 65)); + } + } + + Storage::disk('s3')->put($path . '/' . $filename, $image); + + // remove old image + if($defaultImage) $this->delete($path . $defaultImage, 's3'); + break; + default: + if (!file_exists($path)) mkdir($path, 0777, true); + + // for intervention v2 + if (str_contains(GeneratorUtils::checkPackageVersion('intervention/image-laravel'), '2')) { + \Intervention\Image\Facades\Image::make($file->getRealPath())->resize($width, $height, config('generator.image.crop') ? function ($constraint) { + $constraint->aspectRatio(); + $constraint->upsize(); + } : null)->save($path . $filename); + } else { + // for intervention v3 + $image = \Intervention\Image\Laravel\Facades\Image::read($file); + + if(config('generator.image.crop')){ + // constraint aspect ratio + $image->resizeDown($width, $height)->toWebp()->save($path . $filename); + }else{ + $image->resize($width, $height)->toWebp()->save($path . $filename); + } + } + + // remove old image + if($defaultImage) $this->delete($path . $defaultImage); + break; + } + + return $filename; + } + + return $defaultImage; + } + + /** + * Remove image from disk + */ + public function delete(string|null $image, string $disk = 'local'): bool + { + switch ($disk) { + case 's3': + Storage::disk('s3')->delete($image); + break; + default: + if ($image && file_exists($image)) unlink($image); + break; + } + + return true; + } +} diff --git a/stubs/generators/publish/config/full-version/generator.php b/stubs/generators/publish/config/full-version/generator.php index e0c28a11..ec1ef19a 100644 --- a/stubs/generators/publish/config/full-version/generator.php +++ b/stubs/generators/publish/config/full-version/generator.php @@ -2,7 +2,7 @@ return [ /** - * If any input file(image) as default will used options below. + * If any input file(image) as default will use options below. */ 'image' => [ /** @@ -15,7 +15,14 @@ 'path' => 'storage', /** - * Will used if image is nullable and default value is null. + * Supported disk + * 1. local + * 2. S3 + */ + 'disk' => 'local', + + /** + * Will be used if image is nullable and default value is null. */ 'default' => 'https://via.placeholder.com/350?text=No+Image+Avaiable', @@ -38,7 +45,7 @@ 'format' => [ /** - * Will used to first year on select, if any column type year. + * Will be used to first year on select, if any column type year. */ 'first_year' => 1900, @@ -74,7 +81,7 @@ ], /** - * It will used for generator to manage and showing menus on sidebar views. + * It will be used for generator to manage and showing menus on sidebar views. * * Example: * [ @@ -106,13 +113,13 @@ * ], * ], * - * This code below always changes when you use a generator and maybe you must lint or format the code. + * This code below always changes when you use a generator, and maybe you must format the code. */ 'sidebars' => [ [ 'header' => 'Main', 'permissions' => [ - 'test view' + 'test view', ], 'menus' => [ [ @@ -121,14 +128,14 @@ 'route' => null, 'permission' => null, 'permissions' => [ - 'test view' + 'test view', ], 'submenus' => [ [ 'title' => 'Tests', 'route' => '/tests', 'permission' => 'test view' - ] + ], ] ] ] @@ -155,8 +162,8 @@ 'permission' => 'role & permission view', 'permissions' => [], 'submenus' => [] - ], + ] ] - ], - ], + ] + ] ]; diff --git a/stubs/generators/publish/config/simple-version/generator.php b/stubs/generators/publish/config/simple-version/generator.php index 799267f8..ec1ef19a 100644 --- a/stubs/generators/publish/config/simple-version/generator.php +++ b/stubs/generators/publish/config/simple-version/generator.php @@ -2,20 +2,27 @@ return [ /** - * If any input file(image) as default will used options below. + * If any input file(image) as default will use options below. */ 'image' => [ /** * Path for store the image. * - * avaiable options: + * available options: * 1. public * 2. storage */ 'path' => 'storage', /** - * Will used if image is nullable and default value is null. + * Supported disk + * 1. local + * 2. S3 + */ + 'disk' => 'local', + + /** + * Will be used if image is nullable and default value is null. */ 'default' => 'https://via.placeholder.com/350?text=No+Image+Avaiable', @@ -38,7 +45,7 @@ 'format' => [ /** - * Will used to first year on select, if any column type year. + * Will be used to first year on select, if any column type year. */ 'first_year' => 1900, @@ -72,4 +79,91 @@ */ 'limit_text' => 100, ], + + /** + * It will be used for generator to manage and showing menus on sidebar views. + * + * Example: + * [ + * 'header' => 'Main', + * + * // All permissions in menus[] and submenus[] + * 'permissions' => ['test view'], + * + * menus' => [ + * [ + * 'title' => 'Main Data', + * 'icon' => '', + * 'route' => null, + * + * // permission always null when isset submenus + * 'permission' => null, + * + * // All permissions on submenus[] and will empty[] when submenus equals to [] + * 'permissions' => ['test view'], + * + * 'submenus' => [ + * [ + * 'title' => 'Tests', + * 'route' => '/tests', + * 'permission' => 'test view' + * ] + * ], + * ], + * ], + * ], + * + * This code below always changes when you use a generator, and maybe you must format the code. + */ + 'sidebars' => [ + [ + 'header' => 'Main', + 'permissions' => [ + 'test view', + ], + 'menus' => [ + [ + 'title' => 'Main Data', + 'icon' => '', + 'route' => null, + 'permission' => null, + 'permissions' => [ + 'test view', + ], + 'submenus' => [ + [ + 'title' => 'Tests', + 'route' => '/tests', + 'permission' => 'test view' + ], + ] + ] + ] + ], + [ + 'header' => 'Users', + 'permissions' => [ + 'user view', + 'role & permission view' + ], + 'menus' => [ + [ + 'title' => 'Users', + 'icon' => '', + 'route' => '/users', + 'permission' => 'user view', + 'permissions' => [], + 'submenus' => [] + ], + [ + 'title' => 'Roles & permissions', + 'icon' => '', + 'route' => '/roles', + 'permission' => 'role & permission view', + 'permissions' => [], + 'submenus' => [] + ] + ] + ] + ] ]; diff --git a/stubs/generators/publish/utils/GeneratorUtils.php b/stubs/generators/publish/utils/GeneratorUtils.php index 985980f8..7382f6c1 100644 --- a/stubs/generators/publish/utils/GeneratorUtils.php +++ b/stubs/generators/publish/utils/GeneratorUtils.php @@ -28,9 +28,7 @@ public static function getPublishedFiles(string $path): string */ public static function checkFolder(string $path): void { - if (!file_exists($path)) { - mkdir($path, 0777, true); - } + if (!file_exists($path)) mkdir($path, 0777, true); } /** @@ -41,11 +39,9 @@ public static function singularPascalCase(string $string): string /** * check string ended with 'ia' or 'ium' */ - if (substr($string, -2) == 'ia' || substr($string, -3) == 'ium') { - return ucfirst(str(GeneratorUtils::fromCamelCase($string))->camel()); - } + if (str_ends_with($string, 'ia') || str_ends_with($string, 'ium')) return ucfirst(str(self::fromCamelCase($string))->camel()); - return ucfirst(str(GeneratorUtils::fromCamelCase($string))->singular()->camel()); + return ucfirst(str(self::fromCamelCase($string))->singular()->camel()); } /** @@ -53,7 +49,7 @@ public static function singularPascalCase(string $string): string */ public static function pascalCase(string $string): string { - return ucfirst(str(GeneratorUtils::fromCamelCase($string))->camel()); + return ucfirst(str(self::fromCamelCase($string))->camel()); } /** @@ -64,11 +60,9 @@ public static function pluralPascalCase(string $string): string /** * check string ended with 'ia' or 'ium' */ - if (substr($string, -2) == 'ia' || substr($string, -3) == 'ium') { - return ucfirst(str(GeneratorUtils::fromCamelCase($string))->camel()) . 's'; - } + if (str_ends_with($string, 'ia') || str_ends_with($string, 'ium')) return ucfirst(str(self::fromCamelCase($string))->camel()) . 's'; - return ucfirst(str(GeneratorUtils::fromCamelCase($string))->plural()->camel()); + return ucfirst(str(self::fromCamelCase($string))->plural()->camel()); } /** @@ -79,11 +73,9 @@ public static function pluralSnakeCase(string $string): string /** * check string ended with 'ia' or 'ium' */ - if (substr($string, -2) == 'ia' || substr($string, -3) == 'ium') { - return str(GeneratorUtils::fromCamelCase($string))->snake()->lower() . 's'; - } + if (str_ends_with($string, 'ia') || str_ends_with($string, 'ium')) return str(self::fromCamelCase($string))->snake()->lower() . 's'; - return str(GeneratorUtils::fromCamelCase($string))->plural()->snake()->lower(); + return str(self::fromCamelCase($string))->plural()->snake()->lower(); } /** @@ -94,11 +86,9 @@ public static function singularSnakeCase(string $string): string /** * check string ended with 'ia' or 'ium' */ - if (substr($string, -2) == 'ia' || substr($string, -3) == 'ium') { - return str(GeneratorUtils::fromCamelCase($string))->snake()->lower(); - } + if (str_ends_with($string, 'ia') || str_ends_with($string, 'ium')) return str(self::fromCamelCase($string))->snake()->lower(); - return str(GeneratorUtils::fromCamelCase($string))->singular()->snake()->lower(); + return str(self::fromCamelCase($string))->singular()->snake()->lower(); } /** @@ -109,11 +99,9 @@ public static function pluralCamelCase(string $string): string /** * check string ended with 'ia' or 'ium' */ - if (substr($string, -2) == 'ia' || substr($string, -3) == 'ium') { - return str(GeneratorUtils::fromCamelCase($string))->camel() . 's'; - } + if (str_ends_with($string, 'ia') || str_ends_with($string, 'ium')) return str(self::fromCamelCase($string))->camel() . 's'; - return str(GeneratorUtils::fromCamelCase($string))->plural()->camel(); + return str(self::fromCamelCase($string))->plural()->camel(); } /** @@ -124,11 +112,9 @@ public static function singularCamelCase(string $string): string /** * check string ended with 'ia' or 'ium' */ - if (substr($string, -2) == 'ia' || substr($string, -3) == 'ium') { - return str(GeneratorUtils::fromCamelCase($string))->camel(); - } + if (str_ends_with($string, 'ia') || str_ends_with($string, 'ium')) return str(self::fromCamelCase($string))->camel(); - return str(GeneratorUtils::fromCamelCase($string))->singular()->camel(); + return str(self::fromCamelCase($string))->singular()->camel(); } /** @@ -139,11 +125,9 @@ public static function pluralKebabCase(string $string): string /** * check string ended with 'ia' or 'ium' */ - if (substr($string, -2) == 'ia' || substr($string, -3) == 'ium') { - return str(preg_replace('/[^A-Za-z0-9() -]/', ' ', GeneratorUtils::fromCamelCase($string)))->kebab()->lower() . 's'; - } + if (str_ends_with($string, 'ia') || str_ends_with($string, 'ium')) return str(preg_replace('/[^A-Za-z0-9() -]/', ' ', self::fromCamelCase($string)))->kebab()->lower() . 's'; - return str(preg_replace('/[^A-Za-z0-9() -]/', ' ', GeneratorUtils::fromCamelCase($string)))->plural()->kebab()->lower(); + return str(preg_replace('/[^A-Za-z0-9() -]/', ' ', self::fromCamelCase($string)))->plural()->kebab()->lower(); } /** @@ -151,7 +135,7 @@ public static function pluralKebabCase(string $string): string */ public static function kebabCase(string $string): string { - return str(preg_replace('/[^A-Za-z0-9() -]/', ' ', GeneratorUtils::fromCamelCase($string)))->kebab()->lower(); + return str(preg_replace('/[^A-Za-z0-9() -]/', ' ', self::fromCamelCase($string)))->kebab()->lower(); } /** @@ -162,11 +146,9 @@ public static function singularKebabCase(string $string): string /** * check string ended with 'ia' or 'ium' */ - if (substr($string, -2) == 'ia' || substr($string, -3) == 'ium') { - return str(preg_replace('/[^A-Za-z0-9() -]/', ' ', GeneratorUtils::fromCamelCase($string)))->kebab()->lower(); - } + if (str_ends_with($string, 'ia') || str_ends_with($string, 'ium')) return str(preg_replace('/[^A-Za-z0-9() -]/', ' ', self::fromCamelCase($string)))->kebab()->lower(); - return str(preg_replace('/[^A-Za-z0-9() -]/', ' ', GeneratorUtils::fromCamelCase($string)))->singular()->kebab()->lower(); + return str(preg_replace('/[^A-Za-z0-9() -]/', ' ', self::fromCamelCase($string)))->singular()->kebab()->lower(); } /** @@ -177,11 +159,9 @@ public static function cleanSingularLowerCase(string $string): string /** * check string ended with 'ia' or 'ium' */ - if (substr($string, -2) == 'ia' || substr($string, -3) == 'ium') { - return str(preg_replace('/[^A-Za-z0-9() -]/', ' ', GeneratorUtils::fromCamelCase($string)))->lower(); - } + if (str_ends_with($string, 'ia') || str_ends_with($string, 'ium')) return str(preg_replace('/[^A-Za-z0-9() -]/', ' ', self::fromCamelCase($string)))->lower(); - return str(preg_replace('/[^A-Za-z0-9() -]/', ' ', GeneratorUtils::fromCamelCase($string)))->singular()->lower(); + return str(preg_replace('/[^A-Za-z0-9() -]/', ' ', self::fromCamelCase($string)))->singular()->lower(); } /** @@ -189,7 +169,7 @@ public static function cleanSingularLowerCase(string $string): string */ public static function cleanLowerCase(string $string): string { - return str(preg_replace('/[^A-Za-z0-9() -]/', ' ', GeneratorUtils::fromCamelCase($string)))->lower(); + return str(preg_replace('/[^A-Za-z0-9() -]/', ' ', self::fromCamelCase($string)))->lower(); } /** @@ -200,11 +180,9 @@ public static function cleanPluralUcWords(string $string): string /** * check string ended with 'ia' or 'ium' */ - if (substr($string, -2) == 'ia' || substr($string, -3) == 'ium') { - return ucwords(str(preg_replace('/[^A-Za-z0-9() -]/', ' ', GeneratorUtils::fromCamelCase($string)))->lower()) . 's'; - } + if (str_ends_with($string, 'ia') || str_ends_with($string, 'ium')) return ucwords(str(preg_replace('/[^A-Za-z0-9() -]/', ' ', self::fromCamelCase($string)))->lower()) . 's'; - return ucwords(str(preg_replace('/[^A-Za-z0-9() -]/', ' ', GeneratorUtils::fromCamelCase($string)))->plural()->lower()); + return ucwords(str(preg_replace('/[^A-Za-z0-9() -]/', ' ', self::fromCamelCase($string)))->plural()->lower()); } /** @@ -215,11 +193,9 @@ public static function cleanSingularUcWords(string $string): string /** * check string ended with 'ia' or 'ium' */ - if (substr($string, -2) == 'ia' || substr($string, -3) == 'ium') { - return ucwords(str(preg_replace('/[^A-Za-z0-9() -]/', ' ', GeneratorUtils::fromCamelCase($string)))->lower()); - } + if (str_ends_with($string, 'ia') || str_ends_with($string, 'ium')) return ucwords(str(preg_replace('/[^A-Za-z0-9() -]/', ' ', self::fromCamelCase($string)))->lower()); - return ucwords(str(preg_replace('/[^A-Za-z0-9() -]/', ' ', GeneratorUtils::fromCamelCase($string)))->singular()->lower()); + return ucwords(str(preg_replace('/[^A-Za-z0-9() -]/', ' ', self::fromCamelCase($string)))->singular()->lower()); } /** @@ -227,7 +203,7 @@ public static function cleanSingularUcWords(string $string): string */ public static function cleanUcWords(string $string): string { - return ucwords(preg_replace('/[^A-Za-z0-9() -]/', ' ', GeneratorUtils::fromCamelCase($string))); + return ucwords(preg_replace('/[^A-Za-z0-9() -]/', ' ', self::fromCamelCase($string))); } /** @@ -238,11 +214,9 @@ public static function cleanPluralLowerCase(string $string): string /** * check string ended with 'ia' or 'ium' */ - if (substr($string, -2) == 'ia' || substr($string, -3) == 'ium') { - return str(preg_replace('/[^A-Za-z0-9() -]/', ' ', GeneratorUtils::fromCamelCase($string)))->lower() . 's'; - } + if (str_ends_with($string, 'ia') || str_ends_with($string, 'ium')) return str(preg_replace('/[^A-Za-z0-9() -]/', ' ', self::fromCamelCase($string)))->lower() . 's'; - return str(preg_replace('/[^A-Za-z0-9() -]/', ' ', GeneratorUtils::fromCamelCase($string)))->plural()->lower(); + return str(preg_replace('/[^A-Za-z0-9() -]/', ' ', self::fromCamelCase($string)))->plural()->lower(); } /** @@ -250,7 +224,7 @@ public static function cleanPluralLowerCase(string $string): string */ public static function getColumnAfterId(string $table): string { - $table = GeneratorUtils::pluralSnakeCase($table); + $table = self::pluralSnakeCase($table); $allColumns = Schema::getColumnListing($table); if (sizeof($allColumns) > 0) { @@ -267,7 +241,7 @@ public static function getColumnAfterId(string $table): string */ public static function selectColumnAfterIdAndIdItself(string $table): string { - $table = GeneratorUtils::pluralSnakeCase($table); + $table = self::pluralSnakeCase($table); $allColumns = Schema::getColumnListing($table); if (sizeof($allColumns) > 0) { @@ -293,10 +267,8 @@ public static function getModelLocation(string $model): string */ $path = ""; for ($i = 0; $i < $totalArrModel - 1; $i++) { - $path .= GeneratorUtils::pluralPascalCase($arrModel[$i]); - if ($i + 1 != $totalArrModel - 1) { - $path .= "\\"; - } + $path .= self::pluralPascalCase($arrModel[$i]); + if ($i + 1 != $totalArrModel - 1) $path .= "\\"; } return $path; @@ -308,6 +280,7 @@ public static function getModelLocation(string $model): string public static function fromCamelCase(string $string): string { $a = preg_split('/(?<=[a-z])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])/x', $string); + return trim(implode(' ', $a)); } @@ -327,13 +300,9 @@ public static function setModelName(string $model, string $style = 'pascal case' /** * check string ended with 'ia' or 'ium' */ - if (substr($actualModelName, -2) == 'ia' || substr($actualModelName, -3) == 'ium') { - return self::pascalCase($actualModelName); - } + if (str_ends_with($actualModelName, 'ia') || str_ends_with($actualModelName, 'ium')) return self::pascalCase($actualModelName); - if ($style == 'pascal case') { - return GeneratorUtils::singularPascalCase($actualModelName); - } + if ($style == 'pascal case') return self::singularPascalCase($actualModelName); return $actualModelName; } @@ -359,7 +328,7 @@ public static function setDefaultImage(null|string $default, string $field, stri * Generated code: * $book->cover == null || $book->cover == 'https://via.placeholder.com/350?text=No+Image+Avaiable'" */ - 'form_code' => "$" . GeneratorUtils::singularCamelCase($model) . "->" . str()->snake($field) . " == null || $" . GeneratorUtils::singularCamelCase($model) . "->" . str()->snake($field) . " == '" . $default . "'", + 'form_code' => "$" . self::singularCamelCase($model) . "->" . str()->snake($field) . " == null || $" . self::singularCamelCase($model) . "->" . str()->snake($field) . " == '" . $default . "'", ]; } @@ -380,7 +349,7 @@ public static function setDefaultImage(null|string $default, string $field, stri * * $book->photo == null */ - 'form_code' => "$" . GeneratorUtils::singularCamelCase($model) . "->" . str()->snake($field) . " == null", + 'form_code' => "$" . self::singularCamelCase($model) . "->" . str()->snake($field) . " == null", ]; } @@ -389,7 +358,7 @@ public static function setDefaultImage(null|string $default, string $field, stri 'index_code' => "if (\$row->" . str()->snake($field) . " == null) { return 'https://via.placeholder.com/350?text=No+Image+Avaiable'; }", - 'form_code' => "$" . GeneratorUtils::singularCamelCase($model) . "->" . str()->snake($field) . " == null", + 'form_code' => "$" . self::singularCamelCase($model) . "->" . str()->snake($field) . " == null", ]; } @@ -400,9 +369,7 @@ public static function convertArraySidebarToString(array $sidebars): string { $menu = ""; - foreach ($sidebars as $sidebar) { - $menu .= "'" . $sidebar . "', "; - } + foreach ($sidebars as $sidebar) $menu .= "'" . $sidebar . "', "; return $menu; } @@ -415,53 +382,74 @@ public static function isActiveMenu(string|array $route): string $activeClass = ' active'; if (is_string($route)) { - if (request()->is(substr($route . '*', 1))) { - return $activeClass; - } + if (request()->is(substr($route . '*', 1))) return $activeClass; - if (request()->is(str($route)->slug() . '*')) { - return $activeClass; - } + if (request()->is(str($route)->slug() . '*')) return $activeClass; - if (request()->segment(2) == str($route)->before('/')) { - return $activeClass; - } + if (request()->segment(2) == str($route)->before('/')) return $activeClass; - if (request()->segment(3) == str($route)->after('/')) { - return $activeClass; - } + if (request()->segment(3) == str($route)->after('/')) return $activeClass; } if (is_array($route)) { foreach ($route as $value) { $actualRoute = str($value)->remove(' view')->plural(); - if (request()->is(substr($actualRoute . '*', 1))) { - return $activeClass; - } + if (request()->is(substr($actualRoute . '*', 1))) return $activeClass; - if (request()->is(str($actualRoute)->slug() . '*')) { - return $activeClass; - } + if (request()->is(str($actualRoute)->slug() . '*')) return $activeClass; - if (request()->segment(2) == $actualRoute) { - return $activeClass; - } + if (request()->segment(2) == $actualRoute) return $activeClass; - if (request()->segment(3) == $actualRoute) { - return $activeClass; - } + if (request()->segment(3) == $actualRoute) return $activeClass; } } return ''; } - /** - * Check if generate blade(default) or api. - */ public static function isGenerateApi(): bool { return request()->filled('generate_variant') && request()->get('generate_variant') == 'api'; } + + /** + * Check if package exist in composer. + */ + public static function checkPackage(string $name): bool + { + if(self::getComposerPackage($name) == '{') return false; + + return true; + } + + /** + * Check if package exist in composer and return version. + * @throws \Exception + */ + public static function checkPackageVersion(string $name, bool $strict = false): string + { + $str = self::getComposerPackage($name); + + if(str_contains($str, '{')){ + $message = 'The package '.$name.' is not installed.'; + + if($strict) throw new \Exception($message); + + return $message; + } + + return $str; + + } + + /** + * Check package in composer.json + */ + public static function getComposerPackage(string $name): string + { + $composer = file_get_contents(base_path('composer.json')); + + return str($composer)->after('"'.$name.'": "')->before('"'); + } } diff --git a/stubs/generators/publish/utils/Interfaces/GeneratorUtilsInterface.php b/stubs/generators/publish/utils/Interfaces/GeneratorUtilsInterface.php index e867915a..49ad2a24 100644 --- a/stubs/generators/publish/utils/Interfaces/GeneratorUtilsInterface.php +++ b/stubs/generators/publish/utils/Interfaces/GeneratorUtilsInterface.php @@ -142,4 +142,19 @@ public static function isActiveMenu(string|array $route): string; * Check if generate blade(default) or api. */ public static function isGenerateApi(): bool; + + /** + * Check if package exist in composer. + */ + public static function checkPackage(string $name): bool; + + /** + * Check if package exist in composer and return version. + */ + public static function checkPackageVersion(string $name): string; + + /** + * Check package in composer.json + */ + public static function getComposerPackage(string $name): string; } diff --git a/stubs/generators/publish/utils/Interfaces/ImageServiceInterface.php b/stubs/generators/publish/utils/Interfaces/ImageServiceInterface.php new file mode 100644 index 00000000..5584ef4d --- /dev/null +++ b/stubs/generators/publish/utils/Interfaces/ImageServiceInterface.php @@ -0,0 +1,17 @@ + Date: Sat, 24 Feb 2024 12:22:11 +0700 Subject: [PATCH 017/105] wip --- src/Generators/ControllerGenerator.php | 41 +++++++------------ src/Generators/GeneratorUtils.php | 30 +++++++++----- .../controller-api-with-upload-file.stub | 1 + .../controllers/upload-files/delete.stub | 5 +-- .../upload-files/with-crop/delete.stub | 5 +-- .../upload-files/with-crop/update.stub | 3 +- 6 files changed, 40 insertions(+), 45 deletions(-) diff --git a/src/Generators/ControllerGenerator.php b/src/Generators/ControllerGenerator.php index 83d21fd7..d2a921e1 100644 --- a/src/Generators/ControllerGenerator.php +++ b/src/Generators/ControllerGenerator.php @@ -190,20 +190,8 @@ public function generate(array $request): void */ $passwordFieldStore .= "\t\t\$validated['" . str()->snake($request['fields'][$i]) . "'] = bcrypt(\$request->" . str()->snake($request['fields'][$i]) . ");\n"; - /** - * will generate something like: - * - * switch (is_null($request->password)) { - * case true: - * unset($validated['password']); - * break; - * default: - * $validated['password'] = bcrypt($request->password); - * break; - * } - */ $passwordFieldUpdate .= " - if (is_null(\$request->" . str()->snake($request['fields'][$i]) . ")) { + if (!\$request->" . str()->snake($request['fields'][$i]) . ") { unset(\$validated['" . str()->snake($request['fields'][$i]) . "']); } else { \$validated['" . str()->snake($request['fields'][$i]) . "'] = bcrypt(\$request->" . str()->snake($request['fields'][$i]) . "); @@ -259,7 +247,7 @@ public function generate(array $request): void * return $generator; * }); */ - $castImageIndex .= "$". $modelNamePluralCamelCase ."->through(function ($". $modelNameSingularCamelCase .") {"; + $castImageIndex .= "$" . $modelNamePluralCamelCase . "->through(function ($" . $modelNameSingularCamelCase . ") {"; foreach ($request['input_types'] as $i => $input) { if ($input == 'file') { @@ -301,7 +289,7 @@ public function generate(array $request): void field: $request['fields'][$i], path: 'show', model: $modelNameSingularCamelCase, - ); + ) . "\n"; } } @@ -312,7 +300,7 @@ public function generate(array $request): void * $generator->image = asset('/uploads/images/' . $generator->image); * } */ - $castImageIndex .= "\n\t\t\treturn $". $modelNameSingularCamelCase .";\n\t\t\t});"; + $castImageIndex .= "\n\t\t\treturn $" . $modelNameSingularCamelCase . ";\n\t\t});\n"; /** * Remove $validated = $request->validated(); because is already exist in template (.stub) @@ -397,12 +385,6 @@ public function generate(array $request): void ); break; default: - if (GeneratorUtils::isGenerateApi()) { - $getTemplate = GeneratorUtils::getStub('controllers/controller-api'); - } else { - $getTemplate = GeneratorUtils::getStub('controllers/controller'); - } - /** * default controller */ @@ -455,7 +437,7 @@ public function generate(array $request): void $relations, config('generator.image.disk', 'storage'), ], - $getTemplate + GeneratorUtils::isGenerateApi() ? GeneratorUtils::getStub('controllers/controller-api') : GeneratorUtils::getStub('controllers/controller') ); break; } @@ -486,7 +468,7 @@ public function generate(array $request): void /** * Generate an upload file code. */ - protected function generateUploadImageCode(string $field, string $path, string $model, ?string $defaultValue = null): string + protected function generateUploadImageCode(string $field, string $path, string|null $model, ?string $defaultValue = null): string { $replaceString = [ '{{fieldSnakeCase}}', @@ -499,7 +481,9 @@ protected function generateUploadImageCode(string $field, string $path, string $ '{{aspectRatio}}', '{{defaultImageCode}}', '{{fieldUploadPath}}', - '{{defaultImage}}' + '{{defaultImage}}', + '{{fieldCamelCase}}', + '{[modelNameSingularCamelCase}}' ]; $default = GeneratorUtils::setDefaultImage(default: $defaultValue, field: $field, model: $model); @@ -515,7 +499,9 @@ protected function generateUploadImageCode(string $field, string $path, string $ config('generator.image.aspect_ratio') ? "\n\t\t\t\t\$constraint->aspectRatio();" : '', $default['index_code'], str($field)->snake(), - "$" . GeneratorUtils::singularCamelCase($field) . "->" . str($field)->snake() + "$" . GeneratorUtils::singularCamelCase($model) . "->" . str($field)->snake(), + GeneratorUtils::singularCamelCase($field), + GeneratorUtils::singularCamelCase($model) ]; if ($model != null) { @@ -537,6 +523,9 @@ protected function generateUploadImageCode(string $field, string $path, string $ }; } + /** + * Generate a cast image code. + */ public function generateCastImageCode(string $field, string $path, string $model): string { return str_replace([ diff --git a/src/Generators/GeneratorUtils.php b/src/Generators/GeneratorUtils.php index 1192c083..2cae6591 100644 --- a/src/Generators/GeneratorUtils.php +++ b/src/Generators/GeneratorUtils.php @@ -318,17 +318,17 @@ public static function setDefaultImage(null|string $default, string $field, stri /** * Generated code: * - * if ($row->photo == null || $row->photo == $defaultImage = 'https://raw.githubusercontent.com/laravel/art/master/logo-lockup/5%20SVG/2%20CMYK/1%20Full%20Color/laravel-logolockup-cmyk-red.svg') { + * if (!$row->photo || $row->photo == $defaultImage = 'https://raw.githubusercontent.com/laravel/art/master/logo-lockup/5%20SVG/2%20CMYK/1%20Full%20Color/laravel-logolockup-cmyk-red.svg') { * return $defaultImage; */ - 'index_code' => "if (\$row->" . str()->snake($field) . " == null || \$row->" . str()->snake($field) . " == \$defaultImage = '" . $default . "') { + 'index_code' => "if (!\$row->" . str()->snake($field) . " || \$row->" . str()->snake($field) . " == \$defaultImage = '" . $default . "') { return \$defaultImage; }", /** * Generated code: - * $book->cover == null || $book->cover == 'https://via.placeholder.com/350?text=No+Image+Avaiable'" + * !$book->cover || $book->cover == 'https://via.placeholder.com/350?text=No+Image+Avaiable'" */ - 'form_code' => "$" . self::singularCamelCase($model) . "->" . str()->snake($field) . " == null || $" . self::singularCamelCase($model) . "->" . str()->snake($field) . " == '" . $default . "'", + 'form_code' => "!$" . self::singularCamelCase($model) . "->" . str()->snake($field) . " || $" . self::singularCamelCase($model) . "->" . str()->snake($field) . " == '" . $default . "'", ]; } @@ -338,27 +338,27 @@ public static function setDefaultImage(null|string $default, string $field, stri /** * Generated code: * - * if ($row->photo == null) { + * if ($row->photo) { * return 'https://via.placeholder.com/350?text=No+Image+Avaiable'; */ - 'index_code' => "if (\$row->" . str()->snake($field) . " == null) { + 'index_code' => "if (!\$row->" . str()->snake($field) . ") { return '" . config('generator.image.default') . "'; }", /** * Generated code: * - * $book->photo == null + * $book->photo */ - 'form_code' => "$" . self::singularCamelCase($model) . "->" . str()->snake($field) . " == null", + 'form_code' => "!$" . self::singularCamelCase($model) . "->" . str()->snake($field) . "", ]; } return [ 'image' => 'https://via.placeholder.com/350?text=No+Image+Avaiable', - 'index_code' => "if (\$row->" . str()->snake($field) . " == null) { + 'index_code' => "if (!\$row->" . str()->snake($field) . ") { return 'https://via.placeholder.com/350?text=No+Image+Avaiable'; }", - 'form_code' => "$" . self::singularCamelCase($model) . "->" . str()->snake($field) . " == null", + 'form_code' => "!$" . self::singularCamelCase($model) . "->" . str()->snake($field), ]; } @@ -408,6 +408,9 @@ public static function isActiveMenu(string|array $route): string return ''; } + /** + * Check if generate api or blade view. + */ public static function isGenerateApi(): bool { return request()->filled('generate_variant') && request()->get('generate_variant') == 'api'; @@ -440,7 +443,6 @@ public static function checkPackageVersion(string $name, bool $strict = false): } return $str; - } /** @@ -453,6 +455,9 @@ public static function getComposerPackage(string $name): string return str($composer)->after('"'.$name.'": "')->before('"'); } + /** + * Set disk code for controller. + */ public static function setDiskCodeForController(string $name): string { switch(config('generator.image.disk')){ @@ -468,6 +473,9 @@ public static function setDiskCodeForController(string $name): string } } + /** + * Set disk code for cast an image. + */ public static function setDiskCodeForCastImage(string $model, string $field): string { switch(config('generator.image.disk')){ diff --git a/stubs/generators/controllers/controller-api-with-upload-file.stub b/stubs/generators/controllers/controller-api-with-upload-file.stub index 864be939..ce1fcce5 100644 --- a/stubs/generators/controllers/controller-api-with-upload-file.stub +++ b/stubs/generators/controllers/controller-api-with-upload-file.stub @@ -96,6 +96,7 @@ class {{modelNameSingularPascalCase}}Controller extends Controller ${{modelNameSingularCamelCase}} = {{modelNameSingularPascalCase}}::{{relations}}findOrFail($id); {{deleteCode}} + ${{modelNameSingularCamelCase}}->delete(); return (new {{modelNameSingularPascalCase}}Resource(null)) diff --git a/stubs/generators/controllers/upload-files/delete.stub b/stubs/generators/controllers/upload-files/delete.stub index facb8ef7..44405391 100644 --- a/stubs/generators/controllers/upload-files/delete.stub +++ b/stubs/generators/controllers/upload-files/delete.stub @@ -1,3 +1,2 @@ -$path = {{uploadPath}}/{{fieldPluralSnakeCase}}/'); - - if (${{modelNameSingularCamelCase}}->{{fieldSnakeCase}} != null && file_exists($path . ${{modelNameSingularCamelCase}}->{{fieldSnakeCase}})) unlink($path . ${{modelNameSingularCamelCase}}->{{fieldSnakeCase}}); + ${{fieldCamelCase}} = ${{modelNameSingularCamelCase}}->{{fieldSnakeCase}}; + $this->imageService->upload($this->{{fieldUploadPath}}Path . ${{fieldCamelCase}}); diff --git a/stubs/generators/controllers/upload-files/with-crop/delete.stub b/stubs/generators/controllers/upload-files/with-crop/delete.stub index facb8ef7..6f286b8e 100644 --- a/stubs/generators/controllers/upload-files/with-crop/delete.stub +++ b/stubs/generators/controllers/upload-files/with-crop/delete.stub @@ -1,3 +1,2 @@ -$path = {{uploadPath}}/{{fieldPluralSnakeCase}}/'); - - if (${{modelNameSingularCamelCase}}->{{fieldSnakeCase}} != null && file_exists($path . ${{modelNameSingularCamelCase}}->{{fieldSnakeCase}})) unlink($path . ${{modelNameSingularCamelCase}}->{{fieldSnakeCase}}); +${{fieldCamelCase}} = ${{modelNameSingularCamelCase}}->{{fieldSnakeCase}}; + $this->imageService->delete($this->{{fieldUploadPath}}Path . ${{fieldCamelCase}}); diff --git a/stubs/generators/controllers/upload-files/with-crop/update.stub b/stubs/generators/controllers/upload-files/with-crop/update.stub index 15185534..da0c3f23 100644 --- a/stubs/generators/controllers/upload-files/with-crop/update.stub +++ b/stubs/generators/controllers/upload-files/with-crop/update.stub @@ -1,2 +1 @@ - $validated['{{fieldSnakeCase}}'] = $this->imageService->upload(name: '{{fieldSnakeCase}}', path: {{uploadPath}}/{{fieldPluralSnakeCase}}/')); - + $validated['{{fieldSnakeCase}}'] = $this->imageService->upload(name: '{{fieldSnakeCase}}', path: $this->{{fieldUploadPath}}Path, defaultImage: {{defaultImage}}); From aa8a25e512ff869e21d541ee4ddc187da4777598 Mon Sep 17 00:00:00 2001 From: Mohammad Zulfahmi Date: Wed, 28 Feb 2024 15:00:20 +0700 Subject: [PATCH 018/105] fix cast image in controller --- src/Generators/ControllerGenerator.php | 74 +++++++++---------- src/Generators/GeneratorUtils.php | 31 +++----- .../controller-api-with-upload-file.stub | 18 +++-- .../controller-with-upload-file.stub | 39 +++++----- .../upload-files/cast-image-index.stub | 10 +-- .../upload-files/cast-image-show.stub | 10 +-- .../controllers/upload-files/delete.stub | 2 - .../upload-files/with-crop/delete.stub | 2 - 8 files changed, 89 insertions(+), 97 deletions(-) diff --git a/src/Generators/ControllerGenerator.php b/src/Generators/ControllerGenerator.php index d2a921e1..ba74194f 100644 --- a/src/Generators/ControllerGenerator.php +++ b/src/Generators/ControllerGenerator.php @@ -235,25 +235,36 @@ public function generate(array $request): void $updateCode = ""; $deleteCode = ""; - //cast image in index method + $castImageFunc = ""; $castImageIndex = ""; - // cast image in show method - $castImageShow = ""; $uploadPaths = ""; $assignUploadPaths = ""; + $assignImageDelete = ""; + $deleteImageCodes = ""; /** - * $generators->through(function ($generator) { - * return $generator; - * }); + * if (!$generator->image) { + * $generator->image = 'https://via.placeholder.com/350?text=No+Image+Avaiable'; + * } else { + * $generator->image = asset('/uploads/images/' . $generator->image); + * } + * + * return $generator; + * }) */ - $castImageIndex .= "$" . $modelNamePluralCamelCase . "->through(function ($" . $modelNameSingularCamelCase . ") {"; + $castImageIndex .= "\n\t\t$" . $modelNamePluralCamelCase . "->through(function ($" . $modelNameSingularCamelCase . ") {\n\t\t\t\$this->castImages($". $modelNameSingularCamelCase .");\n\t\t\treturn $" . $modelNameSingularCamelCase . ";\n\t\t});\n"; foreach ($request['input_types'] as $i => $input) { if ($input == 'file') { $uploadPaths .= ", public string $" . str($request['fields'][$i])->snake($request['fields'][$i]) . "Path = ''"; $assignUploadPaths .= "\$this->" . GeneratorUtils::pluralSnakeCase($request['fields'][$i]) . "Path = " . GeneratorUtils::setDiskCodeForController($request['fields'][$i]) . ";\n\t\t"; + // Generated code: $image = $generator->image; + $assignImageDelete .= "$". str($request['fields'][$i])->snake() ." = $". GeneratorUtils::singularCamelCase($model) ."->". str($request['fields'][$i])->snake() .";\n\t\t\t"; + + // Generated code: $this->imageService->delete($this->imagePath . $image); + $deleteImageCodes .= "\$this->imageService->delete(\$this->". GeneratorUtils::singularCamelCase($request['fields'][$i]) ."Path . $". str($request['fields'][$i])->snake() .");\n\t\t\t"; + $indexCode .= $this->generateUploadImageCode( field: $request['fields'][$i], path: 'index', @@ -279,29 +290,14 @@ public function generate(array $request): void model: $modelNameSingularCamelCase ); - $castImageIndex .= $this->generateCastImageCode( + $castImageFunc .= $this->generateCastImageCode( field: $request['fields'][$i], path: 'index', model: $modelNameSingularCamelCase, - ); - - $castImageShow .= $this->generateCastImageCode( - field: $request['fields'][$i], - path: 'show', - model: $modelNameSingularCamelCase, - ) . "\n"; + ) . "\t\t"; } } - /** - * if (!$generator->image) { - * $generator->image = 'https://via.placeholder.com/350?text=No+Image+Avaiable'; - * } else { - * $generator->image = asset('/uploads/images/' . $generator->image); - * } - */ - $castImageIndex .= "\n\t\t\treturn $" . $modelNameSingularCamelCase . ";\n\t\t});\n"; - /** * Remove $validated = $request->validated(); because is already exist in template (.stub) */ @@ -311,12 +307,6 @@ public function generate(array $request): void $inputMonths = str_replace('$validated = $request->validated();', '', $inputMonths); $updateDataAction = "\$" . $modelNameSingularCamelCase . "->update(\$validated);"; - if (GeneratorUtils::isGenerateApi()) { - $getTemplate = GeneratorUtils::getStub('controllers/controller-api-with-upload-file'); - } else { - $getTemplate = GeneratorUtils::getStub('controllers/controller-with-upload-file'); - } - /** * controller with upload file code */ @@ -346,10 +336,13 @@ public function generate(array $request): void '{{modelNameCleanSingular}}', '{{modelNameCleanPlural}}', '{{relations}}', - '{{castImageIndex}}', - '{{castImageShow}}', '{{uploadPaths}}', - '{{assignUploadPaths}}' + '{{assignUploadPaths}}', + '{{assignImageDelete}}', + '{{deleteImageCodes}}', + '{{castImageFunction}}', + '{{castImageIndex}}', + '{{castImageShow}}' ], [ $modelNameSingularPascalCase, @@ -376,12 +369,15 @@ public function generate(array $request): void $modelNameCleanSingular, $modelNameCleanPlural, $relations, - $castImageIndex, - $castImageShow, $uploadPaths, - $assignUploadPaths + $assignUploadPaths, + $assignImageDelete, + $deleteImageCodes, + $castImageFunc, + $castImageIndex, + "\n\t\t\$this->castImages($" . $modelNameSingularCamelCase . ");\n" ], - $getTemplate + GeneratorUtils::isGenerateApi() ? GeneratorUtils::getStub('controllers/controller-api-with-upload-file') : GeneratorUtils::getStub('controllers/controller-with-upload-file') ); break; default: @@ -483,7 +479,7 @@ protected function generateUploadImageCode(string $field, string $path, string|n '{{fieldUploadPath}}', '{{defaultImage}}', '{{fieldCamelCase}}', - '{[modelNameSingularCamelCase}}' + '{[modelNameSingularCamelCase}}', ]; $default = GeneratorUtils::setDefaultImage(default: $defaultValue, field: $field, model: $model); @@ -501,7 +497,7 @@ protected function generateUploadImageCode(string $field, string $path, string|n str($field)->snake(), "$" . GeneratorUtils::singularCamelCase($model) . "->" . str($field)->snake(), GeneratorUtils::singularCamelCase($field), - GeneratorUtils::singularCamelCase($model) + GeneratorUtils::singularCamelCase($model), ]; if ($model != null) { diff --git a/src/Generators/GeneratorUtils.php b/src/Generators/GeneratorUtils.php index 2cae6591..3b6ce89f 100644 --- a/src/Generators/GeneratorUtils.php +++ b/src/Generators/GeneratorUtils.php @@ -460,17 +460,11 @@ public static function getComposerPackage(string $name): string */ public static function setDiskCodeForController(string $name): string { - switch(config('generator.image.disk')){ - case 's3': - return "/$name"; - break; - case 'public': - return "public_path('uploads/$name/')"; - break; - default: - return "storage_path('app/public/uploads/$name/')"; - break; - } + return match (config('generator.image.disk')) { + 's3' => "/$name", + 'public' => "public_path('uploads/$name/')", + default => "storage_path('app/public/uploads/$name/')", + }; } /** @@ -478,15 +472,10 @@ public static function setDiskCodeForController(string $name): string */ public static function setDiskCodeForCastImage(string $model, string $field): string { - switch(config('generator.image.disk')){ - case 's3': - break; - case 'public': - return "asset('/uploads/". self::pluralKebabCase($field) ."/' . $". self::singularCamelCase($model) ."->". str($field)->snake() .")"; - break; - default: - return "asset('storage/uploads/". self::pluralKebabCase($field) ."/' . $". self::singularCamelCase($model) ."->". str($field)->snake() .");"; - break; - } + return match (config('generator.image.disk')) { + 's3' => "Storage::disk('s3')->url('/uploads/" . self::pluralKebabCase($field) . "/' . $" . self::singularCamelCase($model) . "->" . str($field)->snake() . ")", + 'public' => "asset('/uploads/" . self::pluralKebabCase($field) . "/' . $" . self::singularCamelCase($model) . "->" . str($field)->snake() . ")", + default => "asset('storage/uploads/" . self::pluralKebabCase($field) . "/' . $" . self::singularCamelCase($model) . "->" . str($field)->snake() . ");", + }; } } diff --git a/stubs/generators/controllers/controller-api-with-upload-file.stub b/stubs/generators/controllers/controller-api-with-upload-file.stub index ce1fcce5..babd0de2 100644 --- a/stubs/generators/controllers/controller-api-with-upload-file.stub +++ b/stubs/generators/controllers/controller-api-with-upload-file.stub @@ -11,13 +11,13 @@ use App\Services\ImageService; class {{modelNameSingularPascalCase}}Controller extends Controller { - // TODO: uncomment this code if you are using spatie permission public function __construct(public ImageService $imageService{{uploadPaths}}) { {{assignUploadPaths}} + // TODO: uncomment this code if you are using spatie permission // $this->middleware('permission:{{modelNameSpaceLowercase}} view')->only('index', 'show'); - // $this->middleware('permission:{{modelNameSpaceLowercase}} create')->only('create', 'store'); - // $this->middleware('permission:{{modelNameSpaceLowercase}} edit')->only('edit', 'update'); + // $this->middleware('permission:{{modelNameSpaceLowercase}} create')->only('store'); + // $this->middleware('permission:{{modelNameSpaceLowercase}} edit')->only('update'); // $this->middleware('permission:{{modelNameSpaceLowercase}} delete')->only('destroy'); } @@ -95,10 +95,10 @@ class {{modelNameSingularPascalCase}}Controller extends Controller try { ${{modelNameSingularCamelCase}} = {{modelNameSingularPascalCase}}::{{relations}}findOrFail($id); - {{deleteCode}} - + {{assignImageDelete}} ${{modelNameSingularCamelCase}}->delete(); + {{deleteImageCodes}} return (new {{modelNameSingularPascalCase}}Resource(null)) ->additional([ 'message' => 'The {{modelNameCleanSingular}} was deleted successfully.', @@ -116,4 +116,12 @@ class {{modelNameSingularPascalCase}}Controller extends Controller ->setStatusCode(Response::HTTP_INTERNAL_SERVER_ERROR); } } + + /** + * Casting all images + */ + public function castImages(${{modelNameSingularCamelCase}}): void + { + {{castImageFunction}} + } } diff --git a/stubs/generators/controllers/controller-with-upload-file.stub b/stubs/generators/controllers/controller-with-upload-file.stub index 9ce6364c..25ead597 100644 --- a/stubs/generators/controllers/controller-with-upload-file.stub +++ b/stubs/generators/controllers/controller-with-upload-file.stub @@ -4,24 +4,26 @@ use {{modelPath}}; use {{requestPath}}; use Yajra\DataTables\Facades\DataTables; -use Intervention\Image\Facades\Image; - +use App\Services\ImageService; +use Illuminate\Contracts\View\View; +use Illuminate\Http\{JsonResponse, RedirectResponse}; class {{modelNameSingularPascalCase}}Controller extends Controller { - // TODO: uncomment this code if you are using spatie permission - // public function __construct() - // { - // $this->middleware('permission:{{modelNameSpaceLowercase}} view')->only('index', 'show'); - // $this->middleware('permission:{{modelNameSpaceLowercase}} create')->only('create', 'store'); - // $this->middleware('permission:{{modelNameSpaceLowercase}} edit')->only('edit', 'update'); - // $this->middleware('permission:{{modelNameSpaceLowercase}} delete')->only('destroy'); - // } + public function __construct(public ImageService $imageService{{uploadPaths}}) + { + {{assignUploadPaths}} + // TODO: uncomment this code if you are using spatie permission + // $this->middleware('permission:{{modelNameSpaceLowercase}} view')->only('index', 'show'); + // $this->middleware('permission:{{modelNameSpaceLowercase}} create')->only('create', 'store'); + // $this->middleware('permission:{{modelNameSpaceLowercase}} edit')->only('edit', 'update'); + // $this->middleware('permission:{{modelNameSpaceLowercase}} delete')->only('destroy'); + } /** * Display a listing of the resource. */ - public function index(): \Illuminate\Contracts\View\View|\Illuminate\Http\JsonResponse + public function index(): View|JsonResponse { if (request()->ajax()) { ${{modelNamePluralCamelCase}} = {{query}}; @@ -39,7 +41,7 @@ class {{modelNameSingularPascalCase}}Controller extends Controller /** * Show the form for creating a new resource. */ - public function create(): \Illuminate\Contracts\View\View + public function create(): View { return view('{{viewPath}}{{modelNamePluralKebabCase}}.create'); } @@ -47,7 +49,7 @@ class {{modelNameSingularPascalCase}}Controller extends Controller /** * Store a newly created resource in storage. */ - public function store(Store{{modelNameSingularPascalCase}}Request $request): \Illuminate\Http\RedirectResponse + public function store(Store{{modelNameSingularPascalCase}}Request $request): RedirectResponse { $validated = $request->validated(); {{passwordFieldStore}}{{inputMonths}} @@ -60,7 +62,7 @@ class {{modelNameSingularPascalCase}}Controller extends Controller /** * Display the specified resource. */ - public function show({{modelNameSingularPascalCase}} ${{modelNameSingularCamelCase}}): \Illuminate\Contracts\View\View + public function show({{modelNameSingularPascalCase}} ${{modelNameSingularCamelCase}}): View { {{loadRelation}}return view('{{viewPath}}{{modelNamePluralKebabCase}}.show', compact('{{modelNameSingularCamelCase}}')); } @@ -68,7 +70,7 @@ class {{modelNameSingularPascalCase}}Controller extends Controller /** * Show the form for editing the specified resource. */ - public function edit({{modelNameSingularPascalCase}} ${{modelNameSingularCamelCase}}): \Illuminate\Contracts\View\View + public function edit({{modelNameSingularPascalCase}} ${{modelNameSingularCamelCase}}): View { {{loadRelation}}return view('{{viewPath}}{{modelNamePluralKebabCase}}.edit', compact('{{modelNameSingularCamelCase}}')); } @@ -76,7 +78,7 @@ class {{modelNameSingularPascalCase}}Controller extends Controller /** * Update the specified resource in storage. */ - public function update(Update{{modelNameSingularPascalCase}}Request $request, {{modelNameSingularPascalCase}} ${{modelNameSingularCamelCase}}): \Illuminate\Http\RedirectResponse + public function update(Update{{modelNameSingularPascalCase}}Request $request, {{modelNameSingularPascalCase}} ${{modelNameSingularCamelCase}}): RedirectResponse { $validated = $request->validated(); {{passwordFieldUpdate}}{{inputMonths}} @@ -89,12 +91,13 @@ class {{modelNameSingularPascalCase}}Controller extends Controller /** * Remove the specified resource from storage. */ - public function destroy({{modelNameSingularPascalCase}} ${{modelNameSingularCamelCase}}): \Illuminate\Http\RedirectResponse + public function destroy({{modelNameSingularPascalCase}} ${{modelNameSingularCamelCase}}): RedirectResponse { try { - {{deleteCode}} + {{assignImageDelete}} ${{modelNameSingularCamelCase}}->delete(); + {{deleteImageCodes}} return to_route('{{modelNamePluralKebabCase}}.index')->with('success', __('The {{modelNameSingularCamelCase}} was deleted successfully.')); } catch (\Throwable $th) { return to_route('{{modelNamePluralKebabCase}}.index')->with('error', __("The {{modelNameSingularCamelCase}} can't be deleted because it's related to another table.")); diff --git a/stubs/generators/controllers/upload-files/cast-image-index.stub b/stubs/generators/controllers/upload-files/cast-image-index.stub index 579544ee..da6bb473 100644 --- a/stubs/generators/controllers/upload-files/cast-image-index.stub +++ b/stubs/generators/controllers/upload-files/cast-image-index.stub @@ -1,6 +1,6 @@ +if (!${{modelNameSingularCamelCase}}->{{field}}) { + ${{modelNameSingularCamelCase}}->{{field}} = '{{defaultImage}}'; + } else { + ${{modelNameSingularCamelCase}}->{{field}} = {{castImage}}; + } - if (!${{modelNameSingularCamelCase}}->{{field}}) { - ${{modelNameSingularCamelCase}}->{{field}} = '{{defaultImage}}'; - } else { - ${{modelNameSingularCamelCase}}->{{field}} = {{castImage}}; - } diff --git a/stubs/generators/controllers/upload-files/cast-image-show.stub b/stubs/generators/controllers/upload-files/cast-image-show.stub index cf8c4b7d..f5b6936e 100644 --- a/stubs/generators/controllers/upload-files/cast-image-show.stub +++ b/stubs/generators/controllers/upload-files/cast-image-show.stub @@ -1,5 +1,5 @@ -if (!${{modelNameSingularCamelCase}}->{{field}}) { - ${{modelNameSingularCamelCase}}->{{field}} = '{{defaultImage}}'; - } else { - ${{modelNameSingularCamelCase}}->{{field}} = {{castImage}}; - } + if (!${{modelNameSingularCamelCase}}->{{field}}) { + ${{modelNameSingularCamelCase}}->{{field}} = '{{defaultImage}}'; + } else { + ${{modelNameSingularCamelCase}}->{{field}} = {{castImage}}; + } diff --git a/stubs/generators/controllers/upload-files/delete.stub b/stubs/generators/controllers/upload-files/delete.stub index 44405391..e69de29b 100644 --- a/stubs/generators/controllers/upload-files/delete.stub +++ b/stubs/generators/controllers/upload-files/delete.stub @@ -1,2 +0,0 @@ - ${{fieldCamelCase}} = ${{modelNameSingularCamelCase}}->{{fieldSnakeCase}}; - $this->imageService->upload($this->{{fieldUploadPath}}Path . ${{fieldCamelCase}}); diff --git a/stubs/generators/controllers/upload-files/with-crop/delete.stub b/stubs/generators/controllers/upload-files/with-crop/delete.stub index 6f286b8e..e69de29b 100644 --- a/stubs/generators/controllers/upload-files/with-crop/delete.stub +++ b/stubs/generators/controllers/upload-files/with-crop/delete.stub @@ -1,2 +0,0 @@ -${{fieldCamelCase}} = ${{modelNameSingularCamelCase}}->{{fieldSnakeCase}}; - $this->imageService->delete($this->{{fieldUploadPath}}Path . ${{fieldCamelCase}}); From 392a750bef514ab6fd66ee6c378c696ad8934077 Mon Sep 17 00:00:00 2001 From: Mohammad Zulfahmi Date: Thu, 29 Feb 2024 21:23:49 +0700 Subject: [PATCH 019/105] fix upload image to s3 in for controller api --- src/Generators/ControllerGenerator.php | 8 +- src/Generators/GeneratorUtils.php | 34 +++-- src/Generators/Services/GeneratorService.php | 62 ++++---- src/Providers/GeneratorServiceProvider.php | 7 +- .../controller-api-with-upload-file.stub | 7 +- .../controller-with-upload-file.stub | 2 +- .../upload-files/cast-image-index.stub | 8 +- .../controllers/upload-files/index.stub | 1 + .../controllers/upload-files/store.stub | 2 +- .../controllers/upload-files/update.stub | 2 +- .../upload-files/with-crop/index.stub | 1 + .../upload-files/with-crop/store.stub | 2 +- .../upload-files/with-crop/update.stub | 2 +- stubs/generators/publish/ImageService.php | 142 +++++++++--------- .../Interfaces/GeneratorUtilsInterface.php | 2 +- ...erviceInterface.php => ImageInterface.php} | 15 +- .../publish/utils/Services/ImageService.php | 102 +++++++++++++ 17 files changed, 254 insertions(+), 145 deletions(-) rename stubs/generators/publish/utils/Interfaces/{ImageServiceInterface.php => ImageInterface.php} (54%) create mode 100644 stubs/generators/publish/utils/Services/ImageService.php diff --git a/src/Generators/ControllerGenerator.php b/src/Generators/ControllerGenerator.php index ba74194f..3473e751 100644 --- a/src/Generators/ControllerGenerator.php +++ b/src/Generators/ControllerGenerator.php @@ -256,14 +256,14 @@ public function generate(array $request): void foreach ($request['input_types'] as $i => $input) { if ($input == 'file') { - $uploadPaths .= ", public string $" . str($request['fields'][$i])->snake($request['fields'][$i]) . "Path = ''"; - $assignUploadPaths .= "\$this->" . GeneratorUtils::pluralSnakeCase($request['fields'][$i]) . "Path = " . GeneratorUtils::setDiskCodeForController($request['fields'][$i]) . ";\n\t\t"; + $uploadPaths .= ", public string $" . GeneratorUtils::singularCamelCase($request['fields'][$i]) . "Path = ''"; + $assignUploadPaths .= "\$this->" . GeneratorUtils::singularCamelCase($request['fields'][$i]) . "Path = " . GeneratorUtils::setDiskCodeForController($request['fields'][$i]) . ";\n\t\t"; // Generated code: $image = $generator->image; $assignImageDelete .= "$". str($request['fields'][$i])->snake() ." = $". GeneratorUtils::singularCamelCase($model) ."->". str($request['fields'][$i])->snake() .";\n\t\t\t"; // Generated code: $this->imageService->delete($this->imagePath . $image); - $deleteImageCodes .= "\$this->imageService->delete(\$this->". GeneratorUtils::singularCamelCase($request['fields'][$i]) ."Path . $". str($request['fields'][$i])->snake() .");\n\t\t\t"; + $deleteImageCodes .= "\$this->imageService->delete(image: \$this->". GeneratorUtils::singularCamelCase($request['fields'][$i]) ."Path . $". str($request['fields'][$i])->snake() . (config('generator.image.disk') == 's3' ? ", disk: 's3'" : '') .");\n\t\t\t"; $indexCode .= $this->generateUploadImageCode( field: $request['fields'][$i], @@ -480,6 +480,7 @@ protected function generateUploadImageCode(string $field, string $path, string|n '{{defaultImage}}', '{{fieldCamelCase}}', '{[modelNameSingularCamelCase}}', + '{{disk}}' ]; $default = GeneratorUtils::setDefaultImage(default: $defaultValue, field: $field, model: $model); @@ -498,6 +499,7 @@ protected function generateUploadImageCode(string $field, string $path, string|n "$" . GeneratorUtils::singularCamelCase($model) . "->" . str($field)->snake(), GeneratorUtils::singularCamelCase($field), GeneratorUtils::singularCamelCase($model), + config('generator.image.disk') == 's3' ? ", disk: 's3'" : '' ]; if ($model != null) { diff --git a/src/Generators/GeneratorUtils.php b/src/Generators/GeneratorUtils.php index 3b6ce89f..c64dbb9e 100644 --- a/src/Generators/GeneratorUtils.php +++ b/src/Generators/GeneratorUtils.php @@ -321,9 +321,7 @@ public static function setDefaultImage(null|string $default, string $field, stri * if (!$row->photo || $row->photo == $defaultImage = 'https://raw.githubusercontent.com/laravel/art/master/logo-lockup/5%20SVG/2%20CMYK/1%20Full%20Color/laravel-logolockup-cmyk-red.svg') { * return $defaultImage; */ - 'index_code' => "if (!\$row->" . str()->snake($field) . " || \$row->" . str()->snake($field) . " == \$defaultImage = '" . $default . "') { - return \$defaultImage; - }", + 'index_code' => "if (!\$row->" . str()->snake($field) . " || \$row->" . str()->snake($field) . " == \$defaultImage = '" . $default . "') return \$defaultImage;", /** * Generated code: * !$book->cover || $book->cover == 'https://via.placeholder.com/350?text=No+Image+Avaiable'" @@ -341,23 +339,19 @@ public static function setDefaultImage(null|string $default, string $field, stri * if ($row->photo) { * return 'https://via.placeholder.com/350?text=No+Image+Avaiable'; */ - 'index_code' => "if (!\$row->" . str()->snake($field) . ") { - return '" . config('generator.image.default') . "'; - }", + 'index_code' => "if (!\$row->" . str()->snake($field) . ") return '" . config('generator.image.default') . "';", /** * Generated code: * * $book->photo */ - 'form_code' => "!$" . self::singularCamelCase($model) . "->" . str()->snake($field) . "", + 'form_code' => "!$" . self::singularCamelCase($model) . "->" . str()->snake($field), ]; } return [ 'image' => 'https://via.placeholder.com/350?text=No+Image+Avaiable', - 'index_code' => "if (!\$row->" . str()->snake($field) . ") { - return 'https://via.placeholder.com/350?text=No+Image+Avaiable'; - }", + 'index_code' => "if (!\$row->" . str()->snake($field) . ") return 'https://via.placeholder.com/350?text=No+Image+Avaiable';", 'form_code' => "!$" . self::singularCamelCase($model) . "->" . str()->snake($field), ]; } @@ -461,9 +455,14 @@ public static function getComposerPackage(string $name): string public static function setDiskCodeForController(string $name): string { return match (config('generator.image.disk')) { - 's3' => "/$name", - 'public' => "public_path('uploads/$name/')", - default => "storage_path('app/public/uploads/$name/')", + // '/images/'; + 's3' => "'/". self::pluralKebabCase($name) ."/'", + + // 'public_path('uploads/images/'); + 'public' => "public_path('uploads/". self::pluralKebabCase($name) ."/')", + + // 'storage_path('app/public/uploads/images/'); + default => "storage_path('app/public/uploads/". self::pluralKebabCase($name) ."/')", }; } @@ -473,9 +472,14 @@ public static function setDiskCodeForController(string $name): string public static function setDiskCodeForCastImage(string $model, string $field): string { return match (config('generator.image.disk')) { - 's3' => "Storage::disk('s3')->url('/uploads/" . self::pluralKebabCase($field) . "/' . $" . self::singularCamelCase($model) . "->" . str($field)->snake() . ")", + // \Illuminate\Support\Facades\Storage::disk('s3')->url('images/' . $generator->image); + 's3' => "\Illuminate\Support\Facades\Storage::disk('s3')->url(\$this->". self::singularCamelCase($field) ."Path . $" . self::singularCamelCase($model) . "->" . str($field)->snake() . ")", + + //asset('/uploads/photos/' . $generator->image); 'public' => "asset('/uploads/" . self::pluralKebabCase($field) . "/' . $" . self::singularCamelCase($model) . "->" . str($field)->snake() . ")", - default => "asset('storage/uploads/" . self::pluralKebabCase($field) . "/' . $" . self::singularCamelCase($model) . "->" . str($field)->snake() . ");", + + //asset('storage/uploads/images/' . $generator->image) + default => "asset('storage/uploads/" . self::pluralKebabCase($field) . "/' . $" . self::singularCamelCase($model) . "->" . str($field)->snake() . ")", }; } } diff --git a/src/Generators/Services/GeneratorService.php b/src/Generators/Services/GeneratorService.php index ead07117..6852af9c 100644 --- a/src/Generators/Services/GeneratorService.php +++ b/src/Generators/Services/GeneratorService.php @@ -35,38 +35,38 @@ class GeneratorService implements GeneratorServiceInterface */ public function generate(array $request): void { -// if (empty($request['is_simple_generator'])) (new PermissionGenerator)->generate($request); -// -// (new ModelGenerator)->generate($request); -// (new MigrationGenerator)->generate($request); + if (empty($request['is_simple_generator'])) (new PermissionGenerator)->generate($request); + + (new ModelGenerator)->generate($request); + (new MigrationGenerator)->generate($request); (new ControllerGenerator)->generate($request); -// (new RequestGenerator)->generate($request); -// -// // blade template -// if (empty($request['generate_variant']) || $request['generate_variant'] != 'api') { -// (new IndexViewGenerator)->generate($request); -// (new CreateViewGenerator)->generate($request); -// (new ShowViewGenerator)->generate($request); -// (new EditViewGenerator)->generate($request); -// (new ActionViewGenerator)->generate($request); -// (new FormViewGenerator)->generate($request); -// -// if (empty($request['is_simple_generator'])) (new MenuGenerator)->generate($request); -// -// if (in_array('foreignId', $request['column_types'])) (new ViewComposerGenerator)->generate($request); -// } -// -// (new RouteGenerator)->generate($request); -// -// if (isset($request['generate_seeder']) && $request['generate_seeder'] != null) (new SeederGenerator)->generate($request); -// -// if (isset($request['generate_factory']) && $request['generate_factory'] != null) (new FactoryGenerator)->generate($request); -// -// if (GeneratorUtils::isGenerateApi()) (new ResourceApiGenerator)->generate($request); -// -// if (empty($request['generate_variant']) && $request['generate_variant'] != 'api' || empty($request['is_simple_generator'])) $this->checkSidebarType(); -// -// Artisan::call('migrate'); + (new RequestGenerator)->generate($request); + + // blade template + if (empty($request['generate_variant']) || $request['generate_variant'] != 'api') { + (new IndexViewGenerator)->generate($request); + (new CreateViewGenerator)->generate($request); + (new ShowViewGenerator)->generate($request); + (new EditViewGenerator)->generate($request); + (new ActionViewGenerator)->generate($request); + (new FormViewGenerator)->generate($request); + + if (empty($request['is_simple_generator'])) (new MenuGenerator)->generate($request); + + if (in_array('foreignId', $request['column_types'])) (new ViewComposerGenerator)->generate($request); + } + + (new RouteGenerator)->generate($request); + + if (isset($request['generate_seeder']) && $request['generate_seeder'] != null) (new SeederGenerator)->generate($request); + + if (isset($request['generate_factory']) && $request['generate_factory'] != null) (new FactoryGenerator)->generate($request); + + if (GeneratorUtils::isGenerateApi()) (new ResourceApiGenerator)->generate($request); + + if (empty($request['generate_variant']) && $request['generate_variant'] != 'api' || empty($request['is_simple_generator'])) $this->checkSidebarType(); + + Artisan::call('migrate'); } /** diff --git a/src/Providers/GeneratorServiceProvider.php b/src/Providers/GeneratorServiceProvider.php index 13677365..6b443db4 100644 --- a/src/Providers/GeneratorServiceProvider.php +++ b/src/Providers/GeneratorServiceProvider.php @@ -91,7 +91,12 @@ public function boot(): void __DIR__ . '/../../stubs/generators/publish/utils' => app_path('Generators') ], 'generator-utils'); - // Illuminate\Foundation\Console\AboutCommand::add('Generator', fn () => ['Version' => '0.2.0']); + \Illuminate\Foundation\Console\AboutCommand::add('Generator', fn () => [ + 'Version' => '0.3.0', + 'Source' => 'https://github.com/evdigiina/generator', + 'Docs' => 'https://evdigi-ina.github.io/generator-docs', + 'About' => 'Package for building basic CRUD, especially for your master(main) data.' + ]); if ($this->app->runningInConsole()) $this->commands([PublishAllFiles::class]); diff --git a/stubs/generators/controllers/controller-api-with-upload-file.stub b/stubs/generators/controllers/controller-api-with-upload-file.stub index babd0de2..538d372c 100644 --- a/stubs/generators/controllers/controller-api-with-upload-file.stub +++ b/stubs/generators/controllers/controller-api-with-upload-file.stub @@ -118,9 +118,10 @@ class {{modelNameSingularPascalCase}}Controller extends Controller } /** - * Casting all images - */ - public function castImages(${{modelNameSingularCamelCase}}): void + * Casting all images + * TODO: casting image in model (soon) + */ + public function castImages({{modelNameSingularPascalCase}} ${{modelNameSingularCamelCase}}): void { {{castImageFunction}} } diff --git a/stubs/generators/controllers/controller-with-upload-file.stub b/stubs/generators/controllers/controller-with-upload-file.stub index 25ead597..28557b61 100644 --- a/stubs/generators/controllers/controller-with-upload-file.stub +++ b/stubs/generators/controllers/controller-with-upload-file.stub @@ -99,7 +99,7 @@ class {{modelNameSingularPascalCase}}Controller extends Controller {{deleteImageCodes}} return to_route('{{modelNamePluralKebabCase}}.index')->with('success', __('The {{modelNameSingularCamelCase}} was deleted successfully.')); - } catch (\Throwable $th) { + } catch (\Exception $e) { return to_route('{{modelNamePluralKebabCase}}.index')->with('error', __("The {{modelNameSingularCamelCase}} can't be deleted because it's related to another table.")); } } diff --git a/stubs/generators/controllers/upload-files/cast-image-index.stub b/stubs/generators/controllers/upload-files/cast-image-index.stub index da6bb473..b2d3d9df 100644 --- a/stubs/generators/controllers/upload-files/cast-image-index.stub +++ b/stubs/generators/controllers/upload-files/cast-image-index.stub @@ -1,6 +1,6 @@ if (!${{modelNameSingularCamelCase}}->{{field}}) { - ${{modelNameSingularCamelCase}}->{{field}} = '{{defaultImage}}'; - } else { - ${{modelNameSingularCamelCase}}->{{field}} = {{castImage}}; - } + ${{modelNameSingularCamelCase}}->{{field}} = '{{defaultImage}}'; + } else { + ${{modelNameSingularCamelCase}}->{{field}} = {{castImage}}; + } diff --git a/stubs/generators/controllers/upload-files/index.stub b/stubs/generators/controllers/upload-files/index.stub index df07d557..9afaee9c 100644 --- a/stubs/generators/controllers/upload-files/index.stub +++ b/stubs/generators/controllers/upload-files/index.stub @@ -1,4 +1,5 @@ ->addColumn('{{fieldSnakeCase}}', function ($row) { {{defaultImageCode}} + return asset('{{uploadPathPublic}}/{{fieldPluralKebabCase}}/' . $row->{{fieldSnakeCase}}); }) diff --git a/stubs/generators/controllers/upload-files/store.stub b/stubs/generators/controllers/upload-files/store.stub index baad4221..de6133ad 100644 --- a/stubs/generators/controllers/upload-files/store.stub +++ b/stubs/generators/controllers/upload-files/store.stub @@ -1 +1 @@ - $validated['{{fieldSnakeCase}}'] = $this->imageService->upload(name: '{{fieldSnakeCase}}', path: $this->{{fieldUploadPath}}Path); + $validated['{{fieldSnakeCase}}'] = $this->imageService->upload(name: '{{fieldSnakeCase}}', path: $this->{{fieldUploadPath}}Path{{disk}}); diff --git a/stubs/generators/controllers/upload-files/update.stub b/stubs/generators/controllers/upload-files/update.stub index da0c3f23..4a77988e 100644 --- a/stubs/generators/controllers/upload-files/update.stub +++ b/stubs/generators/controllers/upload-files/update.stub @@ -1 +1 @@ - $validated['{{fieldSnakeCase}}'] = $this->imageService->upload(name: '{{fieldSnakeCase}}', path: $this->{{fieldUploadPath}}Path, defaultImage: {{defaultImage}}); + $validated['{{fieldSnakeCase}}'] = $this->imageService->upload(name: '{{fieldSnakeCase}}', path: $this->{{fieldUploadPath}}Path, defaultImage: {{defaultImage}}{{disk}}); diff --git a/stubs/generators/controllers/upload-files/with-crop/index.stub b/stubs/generators/controllers/upload-files/with-crop/index.stub index df07d557..9afaee9c 100644 --- a/stubs/generators/controllers/upload-files/with-crop/index.stub +++ b/stubs/generators/controllers/upload-files/with-crop/index.stub @@ -1,4 +1,5 @@ ->addColumn('{{fieldSnakeCase}}', function ($row) { {{defaultImageCode}} + return asset('{{uploadPathPublic}}/{{fieldPluralKebabCase}}/' . $row->{{fieldSnakeCase}}); }) diff --git a/stubs/generators/controllers/upload-files/with-crop/store.stub b/stubs/generators/controllers/upload-files/with-crop/store.stub index baad4221..de6133ad 100644 --- a/stubs/generators/controllers/upload-files/with-crop/store.stub +++ b/stubs/generators/controllers/upload-files/with-crop/store.stub @@ -1 +1 @@ - $validated['{{fieldSnakeCase}}'] = $this->imageService->upload(name: '{{fieldSnakeCase}}', path: $this->{{fieldUploadPath}}Path); + $validated['{{fieldSnakeCase}}'] = $this->imageService->upload(name: '{{fieldSnakeCase}}', path: $this->{{fieldUploadPath}}Path{{disk}}); diff --git a/stubs/generators/controllers/upload-files/with-crop/update.stub b/stubs/generators/controllers/upload-files/with-crop/update.stub index da0c3f23..4a77988e 100644 --- a/stubs/generators/controllers/upload-files/with-crop/update.stub +++ b/stubs/generators/controllers/upload-files/with-crop/update.stub @@ -1 +1 @@ - $validated['{{fieldSnakeCase}}'] = $this->imageService->upload(name: '{{fieldSnakeCase}}', path: $this->{{fieldUploadPath}}Path, defaultImage: {{defaultImage}}); + $validated['{{fieldSnakeCase}}'] = $this->imageService->upload(name: '{{fieldSnakeCase}}', path: $this->{{fieldUploadPath}}Path, defaultImage: {{defaultImage}}{{disk}}); diff --git a/stubs/generators/publish/ImageService.php b/stubs/generators/publish/ImageService.php index 0970cd00..5681a21b 100644 --- a/stubs/generators/publish/ImageService.php +++ b/stubs/generators/publish/ImageService.php @@ -8,94 +8,94 @@ class ImageService { /** - * Upload image to disk * @throws \Exception */ - public function upload(string $name, string $path, string|null $defaultImage = null, string $disk = 'local', int $width = 500, int $height = 500): string|null + public function upload(string $name, string $path, string|null $defaultImage = null, string $disk = 'local', int $width = 500, int $height = 500, bool $isCustomUpload = false): string|null { if (request()->file($name) && request()->file($name)->isValid()) { - $file = request()->file($name); - - if (str_contains(GeneratorUtils::checkPackageVersion('intervention/image-laravel'), '2')) { - $filename = $file->hashName(); - }else{ - // set image to webp - $filename = str()->random(20) . '.webp'; - } - - // s3 or local - switch (config('generator.image.disk', $disk)) { - case 's3': - if (str_contains(GeneratorUtils::checkPackageVersion('intervention/image-laravel'), '2')) { - // for intervention v2 - $image = \Intervention\Image\Facades\Image::make($file)->resize($width, $height, config('generator.image.crop') ? function ($constraint) { - $constraint->aspectRatio(); - $constraint->upsize(); - } : null)->encode($file->extension()); - - } else { - // for intervention v3 - $imageInstance = \Intervention\Image\Laravel\Facades\Image::read($file); - - if(config('generator.image.crop')){ - // constraint aspect ratio - $image = $imageInstance->resizeDown($width, $height)->encode(new \Intervention\Image\Encoders\WebpEncoder(quality: 65)); - }else{ - $image = $imageInstance->resize($width, $height)->encode(new \Intervention\Image\Encoders\WebpEncoder(quality: 65)); + if(!$isCustomUpload){ + $file = request()->file($name); + + if (str_contains(GeneratorUtils::checkPackageVersion('intervention/image-laravel'), '2')) { + $filename = $file->hashName(); + } else { + // set image to webp + $filename = str()->random(30) . '.webp'; + } + + // s3 or local + switch (config('generator.image.disk', $disk)) { + case 's3': + if (str_contains(GeneratorUtils::checkPackageVersion('intervention/image-laravel'), '2')) { + // for intervention v2 + $image = \Intervention\Image\Facades\Image::make($file)->resize($width, $height, config('generator.image.crop') ? function ($constraint) { + $constraint->aspectRatio(); + $constraint->upsize(); + } : null)->encode($file->extension()); + } else { + // for intervention v3 + $imageInstance = \Intervention\Image\Laravel\Facades\Image::read($file); + + if (config('generator.image.crop')) { + // constraint aspect ratio + $image = $imageInstance->resizeDown($width, $height)->encode(new \Intervention\Image\Encoders\WebpEncoder(quality: 65)); + } else { + $image = $imageInstance->encode(new \Intervention\Image\Encoders\WebpEncoder(quality: 65)); + } } - } - - Storage::disk('s3')->put($path . '/' . $filename, $image); - // remove old image - if($defaultImage) $this->delete($path . $defaultImage, 's3'); - break; - default: - if (!file_exists($path)) mkdir($path, 0777, true); + Storage::disk('s3')->put($path . '/' . $filename, $image); - // for intervention v2 - if (str_contains(GeneratorUtils::checkPackageVersion('intervention/image-laravel'), '2')) { - \Intervention\Image\Facades\Image::make($file->getRealPath())->resize($width, $height, config('generator.image.crop') ? function ($constraint) { - $constraint->aspectRatio(); - $constraint->upsize(); - } : null)->save($path . $filename); - } else { - // for intervention v3 - $image = \Intervention\Image\Laravel\Facades\Image::read($file); + // remove old image + if ($defaultImage) $this->delete($path . $defaultImage, 's3'); + break; + default: + if (!file_exists($path)) mkdir($path, 0777, true); - if(config('generator.image.crop')){ - // constraint aspect ratio - $image->resizeDown($width, $height)->toWebp()->save($path . $filename); - }else{ - $image->resize($width, $height)->toWebp()->save($path . $filename); + // for intervention v2 + if (str_contains(GeneratorUtils::checkPackageVersion('intervention/image-laravel'), '2')) { + \Intervention\Image\Facades\Image::make($file->getRealPath())->resize($width, $height, config('generator.image.crop') ? function ($constraint) { + $constraint->aspectRatio(); + $constraint->upsize(); + } : null)->save($path . $filename); + } else { + // for intervention v3 + $image = \Intervention\Image\Laravel\Facades\Image::read($file); + + if (config('generator.image.crop')) { + // constraint aspect ratio + $image->resizeDown($width, $height)->toWebp()->save($path . $filename); + } else { + $image->resize($width, $height)->toWebp()->save($path . $filename); + } } - } - // remove old image - if($defaultImage) $this->delete($path . $defaultImage); - break; - } + // remove old image + if ($defaultImage) $this->delete($path . $defaultImage); + break; + } - return $filename; + return $filename; + }else{ + // TODO: write your logic here + return 'something'; + } } return $defaultImage; } - /** - * Remove image from disk - */ - public function delete(string|null $image, string $disk = 'local'): bool + public function delete(string|null $image, string $disk = 'local'): void { - switch ($disk) { - case 's3': - Storage::disk('s3')->delete($image); - break; - default: - if ($image && file_exists($image)) unlink($image); - break; + if ($image) { + switch ($disk) { + case 's3': + Storage::disk('s3')->delete($image); + break; + default: + if (file_exists($image)) unlink($image); + break; + } } - - return true; } } diff --git a/stubs/generators/publish/utils/Interfaces/GeneratorUtilsInterface.php b/stubs/generators/publish/utils/Interfaces/GeneratorUtilsInterface.php index 49ad2a24..bb768a8a 100644 --- a/stubs/generators/publish/utils/Interfaces/GeneratorUtilsInterface.php +++ b/stubs/generators/publish/utils/Interfaces/GeneratorUtilsInterface.php @@ -1,6 +1,6 @@ file($name) && request()->file($name)->isValid()) { + if(!$isCustomUpload){ + $file = request()->file($name); + + if (str_contains(GeneratorUtils::checkPackageVersion('intervention/image-laravel'), '2')) { + $filename = $file->hashName(); + } else { + // set image to webp + $filename = str()->random(30) . '.webp'; + } + + // s3 or local + switch (config('generator.image.disk', $disk)) { + case 's3': + if (str_contains(GeneratorUtils::checkPackageVersion('intervention/image-laravel'), '2')) { + // for intervention v2 + $image = \Intervention\Image\Facades\Image::make($file)->resize($width, $height, config('generator.image.crop') ? function ($constraint) { + $constraint->aspectRatio(); + $constraint->upsize(); + } : null)->encode($file->extension()); + } else { + // for intervention v3 + $imageInstance = \Intervention\Image\Laravel\Facades\Image::read($file); + + if (config('generator.image.crop')) { + // constraint aspect ratio + $image = $imageInstance->resizeDown($width, $height)->encode(new \Intervention\Image\Encoders\WebpEncoder(quality: 65)); + } else { + $image = $imageInstance->encode(new \Intervention\Image\Encoders\WebpEncoder(quality: 65)); + } + } + + Storage::disk('s3')->put($path . '/' . $filename, $image); + + // remove old image + if ($defaultImage) $this->delete($path . $defaultImage, 's3'); + break; + default: + if (!file_exists($path)) mkdir($path, 0777, true); + + // for intervention v2 + if (str_contains(GeneratorUtils::checkPackageVersion('intervention/image-laravel'), '2')) { + \Intervention\Image\Facades\Image::make($file->getRealPath())->resize($width, $height, config('generator.image.crop') ? function ($constraint) { + $constraint->aspectRatio(); + $constraint->upsize(); + } : null)->save($path . $filename); + } else { + // for intervention v3 + $image = \Intervention\Image\Laravel\Facades\Image::read($file); + + if (config('generator.image.crop')) { + // constraint aspect ratio + $image->resizeDown($width, $height)->toWebp()->save($path . $filename); + } else { + $image->toWebp()->save($path . $filename); + } + } + + // remove old image + if ($defaultImage) $this->delete($path . $defaultImage); + break; + } + + return $filename; + }else{ + // TODO: write your logic here + return 'something'; + } + } + + return $defaultImage; + } + + public function delete(string|null $image, string $disk = 'local'): void + { + if ($image) { + switch ($disk) { + case 's3': + Storage::disk('s3')->delete($image); + break; + default: + if (file_exists($image)) unlink($image); + break; + } + } + } +} From 23e750ffa63ee18a40cfe6898a997279c696e332 Mon Sep 17 00:00:00 2001 From: Mohammad Zulfahmi Date: Fri, 1 Mar 2024 08:36:05 +0700 Subject: [PATCH 020/105] fix cast image in index datatable --- src/Generators/ControllerGenerator.php | 18 +++- src/Generators/GeneratorUtils.php | 18 ++-- src/Generators/Services/GeneratorService.php | 62 +++++------ .../controller-api-with-upload-file.stub | 2 +- .../controller-with-upload-file.stub | 4 +- .../controllers/upload-files/index.stub | 4 +- .../upload-files/with-crop/index.stub | 4 +- stubs/generators/publish/ImageService.php | 101 ------------------ .../publish/utils/GeneratorUtils.php | 48 +++++++-- ...nterface.php => ImageServiceInterface.php} | 4 +- .../publish/utils/Services/ImageService.php | 4 +- 11 files changed, 107 insertions(+), 162 deletions(-) delete mode 100644 stubs/generators/publish/ImageService.php rename stubs/generators/publish/utils/Interfaces/{ImageInterface.php => ImageServiceInterface.php} (90%) diff --git a/src/Generators/ControllerGenerator.php b/src/Generators/ControllerGenerator.php index 3473e751..d9210172 100644 --- a/src/Generators/ControllerGenerator.php +++ b/src/Generators/ControllerGenerator.php @@ -254,6 +254,8 @@ public function generate(array $request): void */ $castImageIndex .= "\n\t\t$" . $modelNamePluralCamelCase . "->through(function ($" . $modelNameSingularCamelCase . ") {\n\t\t\t\$this->castImages($". $modelNameSingularCamelCase .");\n\t\t\treturn $" . $modelNameSingularCamelCase . ";\n\t\t});\n"; + $castImageDatatable = ""; + foreach ($request['input_types'] as $i => $input) { if ($input == 'file') { $uploadPaths .= ", public string $" . GeneratorUtils::singularCamelCase($request['fields'][$i]) . "Path = ''"; @@ -265,6 +267,8 @@ public function generate(array $request): void // Generated code: $this->imageService->delete($this->imagePath . $image); $deleteImageCodes .= "\$this->imageService->delete(image: \$this->". GeneratorUtils::singularCamelCase($request['fields'][$i]) ."Path . $". str($request['fields'][$i])->snake() . (config('generator.image.disk') == 's3' ? ", disk: 's3'" : '') .");\n\t\t\t"; + $castImageDatatable .= GeneratorUtils::setDiskCodeForCastImage($model, $request['fields'][$i]); + $indexCode .= $this->generateUploadImageCode( field: $request['fields'][$i], path: 'index', @@ -342,7 +346,8 @@ public function generate(array $request): void '{{deleteImageCodes}}', '{{castImageFunction}}', '{{castImageIndex}}', - '{{castImageShow}}' + '{{castImageShow}}', + '{{castImageDatatable}}' ], [ $modelNameSingularPascalCase, @@ -359,12 +364,16 @@ public function generate(array $request): void $query, $namespace, $requestPath, + + // App\Models\Product $path != '' ? "App\Models\\$path\\$modelNameSingularPascalCase" : "App\Models\\$modelNameSingularPascalCase", $path != '' ? str_replace('\\', '.', strtolower($path)) . "." : '', $passwordFieldStore, $passwordFieldUpdate, $updateDataAction, $inputMonths, + + // App\Http\Resources\ProductResource $path != '' ? "App\Http\Resources\\$path\\$modelNamePluralPascalCase" : "App\Http\Resources\\$modelNamePluralPascalCase", $modelNameCleanSingular, $modelNameCleanPlural, @@ -375,7 +384,10 @@ public function generate(array $request): void $deleteImageCodes, $castImageFunc, $castImageIndex, - "\n\t\t\$this->castImages($" . $modelNameSingularCamelCase . ");\n" + + // $this->castImages($product); + "\n\t\t\$this->castImages($" . $modelNameSingularCamelCase . ");\n", + $castImageDatatable ], GeneratorUtils::isGenerateApi() ? GeneratorUtils::getStub('controllers/controller-api-with-upload-file') : GeneratorUtils::getStub('controllers/controller-with-upload-file') ); @@ -480,7 +492,7 @@ protected function generateUploadImageCode(string $field, string $path, string|n '{{defaultImage}}', '{{fieldCamelCase}}', '{[modelNameSingularCamelCase}}', - '{{disk}}' + '{{disk}}', ]; $default = GeneratorUtils::setDefaultImage(default: $defaultValue, field: $field, model: $model); diff --git a/src/Generators/GeneratorUtils.php b/src/Generators/GeneratorUtils.php index c64dbb9e..6a8d6de5 100644 --- a/src/Generators/GeneratorUtils.php +++ b/src/Generators/GeneratorUtils.php @@ -318,10 +318,9 @@ public static function setDefaultImage(null|string $default, string $field, stri /** * Generated code: * - * if (!$row->photo || $row->photo == $defaultImage = 'https://raw.githubusercontent.com/laravel/art/master/logo-lockup/5%20SVG/2%20CMYK/1%20Full%20Color/laravel-logolockup-cmyk-red.svg') { - * return $defaultImage; + * if (!$generator->image || $generator->image == $defaultImage = 'https://raw.githubusercontent.com/laravel/art/master/logo-lockup/5%20SVG/2%20CMYK/1%20Full%20Color/laravel-logolockup-cmyk-red.svg') return $defaultImage; */ - 'index_code' => "if (!\$row->" . str()->snake($field) . " || \$row->" . str()->snake($field) . " == \$defaultImage = '" . $default . "') return \$defaultImage;", + 'index_code' => "if (!$". self::singularCamelCase($model) ."->" . str()->snake($field) . " || $". self::singularCamelCase($model) ."->" . str()->snake($field) . " == \$defaultImage = '" . $default . "') return \$defaultImage;", /** * Generated code: * !$book->cover || $book->cover == 'https://via.placeholder.com/350?text=No+Image+Avaiable'" @@ -336,14 +335,13 @@ public static function setDefaultImage(null|string $default, string $field, stri /** * Generated code: * - * if ($row->photo) { - * return 'https://via.placeholder.com/350?text=No+Image+Avaiable'; + * if (!$generator->image == null) return 'https://via.placeholder.com/350?text=No+Image+Avaiable'; */ - 'index_code' => "if (!\$row->" . str()->snake($field) . ") return '" . config('generator.image.default') . "';", + 'index_code' => "if (!\$". self::singularCamelCase($model) ."->" . str()->snake($field) . ") return '" . config('generator.image.default') . "';", /** * Generated code: * - * $book->photo + * !$book->photo */ 'form_code' => "!$" . self::singularCamelCase($model) . "->" . str()->snake($field), ]; @@ -351,7 +349,7 @@ public static function setDefaultImage(null|string $default, string $field, stri return [ 'image' => 'https://via.placeholder.com/350?text=No+Image+Avaiable', - 'index_code' => "if (!\$row->" . str()->snake($field) . ") return 'https://via.placeholder.com/350?text=No+Image+Avaiable';", + 'index_code' => "if (!\$". self::singularCamelCase($model) ."->" . str()->snake($field) . ") return 'https://via.placeholder.com/350?text=No+Image+Avaiable';", 'form_code' => "!$" . self::singularCamelCase($model) . "->" . str()->snake($field), ]; } @@ -429,7 +427,7 @@ public static function checkPackageVersion(string $name, bool $strict = false): $str = self::getComposerPackage($name); if(str_contains($str, '{')){ - $message = 'The package '.$name.' is not installed.'; + $message = 'The package ' . $name . ' is not installed.'; if($strict) throw new \Exception($message); @@ -446,7 +444,7 @@ public static function getComposerPackage(string $name): string { $composer = file_get_contents(base_path('composer.json')); - return str($composer)->after('"'.$name.'": "')->before('"'); + return str($composer)->after('"' . $name . '": "')->before('"'); } /** diff --git a/src/Generators/Services/GeneratorService.php b/src/Generators/Services/GeneratorService.php index 6852af9c..ead07117 100644 --- a/src/Generators/Services/GeneratorService.php +++ b/src/Generators/Services/GeneratorService.php @@ -35,38 +35,38 @@ class GeneratorService implements GeneratorServiceInterface */ public function generate(array $request): void { - if (empty($request['is_simple_generator'])) (new PermissionGenerator)->generate($request); - - (new ModelGenerator)->generate($request); - (new MigrationGenerator)->generate($request); +// if (empty($request['is_simple_generator'])) (new PermissionGenerator)->generate($request); +// +// (new ModelGenerator)->generate($request); +// (new MigrationGenerator)->generate($request); (new ControllerGenerator)->generate($request); - (new RequestGenerator)->generate($request); - - // blade template - if (empty($request['generate_variant']) || $request['generate_variant'] != 'api') { - (new IndexViewGenerator)->generate($request); - (new CreateViewGenerator)->generate($request); - (new ShowViewGenerator)->generate($request); - (new EditViewGenerator)->generate($request); - (new ActionViewGenerator)->generate($request); - (new FormViewGenerator)->generate($request); - - if (empty($request['is_simple_generator'])) (new MenuGenerator)->generate($request); - - if (in_array('foreignId', $request['column_types'])) (new ViewComposerGenerator)->generate($request); - } - - (new RouteGenerator)->generate($request); - - if (isset($request['generate_seeder']) && $request['generate_seeder'] != null) (new SeederGenerator)->generate($request); - - if (isset($request['generate_factory']) && $request['generate_factory'] != null) (new FactoryGenerator)->generate($request); - - if (GeneratorUtils::isGenerateApi()) (new ResourceApiGenerator)->generate($request); - - if (empty($request['generate_variant']) && $request['generate_variant'] != 'api' || empty($request['is_simple_generator'])) $this->checkSidebarType(); - - Artisan::call('migrate'); +// (new RequestGenerator)->generate($request); +// +// // blade template +// if (empty($request['generate_variant']) || $request['generate_variant'] != 'api') { +// (new IndexViewGenerator)->generate($request); +// (new CreateViewGenerator)->generate($request); +// (new ShowViewGenerator)->generate($request); +// (new EditViewGenerator)->generate($request); +// (new ActionViewGenerator)->generate($request); +// (new FormViewGenerator)->generate($request); +// +// if (empty($request['is_simple_generator'])) (new MenuGenerator)->generate($request); +// +// if (in_array('foreignId', $request['column_types'])) (new ViewComposerGenerator)->generate($request); +// } +// +// (new RouteGenerator)->generate($request); +// +// if (isset($request['generate_seeder']) && $request['generate_seeder'] != null) (new SeederGenerator)->generate($request); +// +// if (isset($request['generate_factory']) && $request['generate_factory'] != null) (new FactoryGenerator)->generate($request); +// +// if (GeneratorUtils::isGenerateApi()) (new ResourceApiGenerator)->generate($request); +// +// if (empty($request['generate_variant']) && $request['generate_variant'] != 'api' || empty($request['is_simple_generator'])) $this->checkSidebarType(); +// +// Artisan::call('migrate'); } /** diff --git a/stubs/generators/controllers/controller-api-with-upload-file.stub b/stubs/generators/controllers/controller-api-with-upload-file.stub index 538d372c..0d40688f 100644 --- a/stubs/generators/controllers/controller-api-with-upload-file.stub +++ b/stubs/generators/controllers/controller-api-with-upload-file.stub @@ -7,7 +7,7 @@ use {{requestPath}}; use {{resourceApiPath}}\{{{modelNameSingularPascalCase}}Collection, {{modelNameSingularPascalCase}}Resource}; use Symfony\Component\HttpFoundation\Response; use Illuminate\Http\JsonResponse; -use App\Services\ImageService; +use App\Generators\Services\ImageService; class {{modelNameSingularPascalCase}}Controller extends Controller { diff --git a/stubs/generators/controllers/controller-with-upload-file.stub b/stubs/generators/controllers/controller-with-upload-file.stub index 28557b61..6732ac0c 100644 --- a/stubs/generators/controllers/controller-with-upload-file.stub +++ b/stubs/generators/controllers/controller-with-upload-file.stub @@ -3,9 +3,9 @@ {{namespace}} use {{modelPath}}; use {{requestPath}}; -use Yajra\DataTables\Facades\DataTables; -use App\Services\ImageService; use Illuminate\Contracts\View\View; +use Yajra\DataTables\Facades\DataTables; +use App\Generators\Services\ImageService; use Illuminate\Http\{JsonResponse, RedirectResponse}; class {{modelNameSingularPascalCase}}Controller extends Controller diff --git a/stubs/generators/controllers/upload-files/index.stub b/stubs/generators/controllers/upload-files/index.stub index 9afaee9c..013e89d9 100644 --- a/stubs/generators/controllers/upload-files/index.stub +++ b/stubs/generators/controllers/upload-files/index.stub @@ -1,5 +1,5 @@ - ->addColumn('{{fieldSnakeCase}}', function ($row) { + ->addColumn('{{fieldSnakeCase}}', function (${{modelNameSingularCamelCase}}) { {{defaultImageCode}} - return asset('{{uploadPathPublic}}/{{fieldPluralKebabCase}}/' . $row->{{fieldSnakeCase}}); + return {{castImageDatatable}}; }) diff --git a/stubs/generators/controllers/upload-files/with-crop/index.stub b/stubs/generators/controllers/upload-files/with-crop/index.stub index 9afaee9c..013e89d9 100644 --- a/stubs/generators/controllers/upload-files/with-crop/index.stub +++ b/stubs/generators/controllers/upload-files/with-crop/index.stub @@ -1,5 +1,5 @@ - ->addColumn('{{fieldSnakeCase}}', function ($row) { + ->addColumn('{{fieldSnakeCase}}', function (${{modelNameSingularCamelCase}}) { {{defaultImageCode}} - return asset('{{uploadPathPublic}}/{{fieldPluralKebabCase}}/' . $row->{{fieldSnakeCase}}); + return {{castImageDatatable}}; }) diff --git a/stubs/generators/publish/ImageService.php b/stubs/generators/publish/ImageService.php deleted file mode 100644 index 5681a21b..00000000 --- a/stubs/generators/publish/ImageService.php +++ /dev/null @@ -1,101 +0,0 @@ -file($name) && request()->file($name)->isValid()) { - if(!$isCustomUpload){ - $file = request()->file($name); - - if (str_contains(GeneratorUtils::checkPackageVersion('intervention/image-laravel'), '2')) { - $filename = $file->hashName(); - } else { - // set image to webp - $filename = str()->random(30) . '.webp'; - } - - // s3 or local - switch (config('generator.image.disk', $disk)) { - case 's3': - if (str_contains(GeneratorUtils::checkPackageVersion('intervention/image-laravel'), '2')) { - // for intervention v2 - $image = \Intervention\Image\Facades\Image::make($file)->resize($width, $height, config('generator.image.crop') ? function ($constraint) { - $constraint->aspectRatio(); - $constraint->upsize(); - } : null)->encode($file->extension()); - } else { - // for intervention v3 - $imageInstance = \Intervention\Image\Laravel\Facades\Image::read($file); - - if (config('generator.image.crop')) { - // constraint aspect ratio - $image = $imageInstance->resizeDown($width, $height)->encode(new \Intervention\Image\Encoders\WebpEncoder(quality: 65)); - } else { - $image = $imageInstance->encode(new \Intervention\Image\Encoders\WebpEncoder(quality: 65)); - } - } - - Storage::disk('s3')->put($path . '/' . $filename, $image); - - // remove old image - if ($defaultImage) $this->delete($path . $defaultImage, 's3'); - break; - default: - if (!file_exists($path)) mkdir($path, 0777, true); - - // for intervention v2 - if (str_contains(GeneratorUtils::checkPackageVersion('intervention/image-laravel'), '2')) { - \Intervention\Image\Facades\Image::make($file->getRealPath())->resize($width, $height, config('generator.image.crop') ? function ($constraint) { - $constraint->aspectRatio(); - $constraint->upsize(); - } : null)->save($path . $filename); - } else { - // for intervention v3 - $image = \Intervention\Image\Laravel\Facades\Image::read($file); - - if (config('generator.image.crop')) { - // constraint aspect ratio - $image->resizeDown($width, $height)->toWebp()->save($path . $filename); - } else { - $image->resize($width, $height)->toWebp()->save($path . $filename); - } - } - - // remove old image - if ($defaultImage) $this->delete($path . $defaultImage); - break; - } - - return $filename; - }else{ - // TODO: write your logic here - return 'something'; - } - } - - return $defaultImage; - } - - public function delete(string|null $image, string $disk = 'local'): void - { - if ($image) { - switch ($disk) { - case 's3': - Storage::disk('s3')->delete($image); - break; - default: - if (file_exists($image)) unlink($image); - break; - } - } - } -} diff --git a/stubs/generators/publish/utils/GeneratorUtils.php b/stubs/generators/publish/utils/GeneratorUtils.php index 7382f6c1..b7ec0309 100644 --- a/stubs/generators/publish/utils/GeneratorUtils.php +++ b/stubs/generators/publish/utils/GeneratorUtils.php @@ -318,10 +318,10 @@ public static function setDefaultImage(null|string $default, string $field, stri /** * Generated code: * - * if ($row->photo == null || $row->photo == $defaultImage = 'https://raw.githubusercontent.com/laravel/art/master/logo-lockup/5%20SVG/2%20CMYK/1%20Full%20Color/laravel-logolockup-cmyk-red.svg') { + * if ($generator->image == null || $generator->image == $defaultImage = 'https://raw.githubusercontent.com/laravel/art/master/logo-lockup/5%20SVG/2%20CMYK/1%20Full%20Color/laravel-logolockup-cmyk-red.svg') { * return $defaultImage; */ - 'index_code' => "if (\$row->" . str()->snake($field) . " == null || \$row->" . str()->snake($field) . " == \$defaultImage = '" . $default . "') { + 'index_code' => "if (\$". self::singularCamelCase($model) ."->" . str()->snake($field) . " == null || \$". self::singularCamelCase($model) .">" . str()->snake($field) . " == \$defaultImage = '" . $default . "') { return \$defaultImage; }", /** @@ -338,10 +338,10 @@ public static function setDefaultImage(null|string $default, string $field, stri /** * Generated code: * - * if ($row->photo == null) { + * if ($generator->image == null) { * return 'https://via.placeholder.com/350?text=No+Image+Avaiable'; */ - 'index_code' => "if (\$row->" . str()->snake($field) . " == null) { + 'index_code' => "if (\$". self::singularCamelCase($model) ."->" . str()->snake($field) . " == null) { return '" . config('generator.image.default') . "'; }", /** @@ -355,7 +355,7 @@ public static function setDefaultImage(null|string $default, string $field, stri return [ 'image' => 'https://via.placeholder.com/350?text=No+Image+Avaiable', - 'index_code' => "if (\$row->" . str()->snake($field) . " == null) { + 'index_code' => "if (\$". self::singularCamelCase($model) ."->" . str()->snake($field) . " == null) { return 'https://via.placeholder.com/350?text=No+Image+Avaiable'; }", 'form_code' => "$" . self::singularCamelCase($model) . "->" . str()->snake($field) . " == null", @@ -408,6 +408,9 @@ public static function isActiveMenu(string|array $route): string return ''; } + /** + * Check if generate api or blade view. + */ public static function isGenerateApi(): bool { return request()->filled('generate_variant') && request()->get('generate_variant') == 'api'; @@ -440,7 +443,6 @@ public static function checkPackageVersion(string $name, bool $strict = false): } return $str; - } /** @@ -452,4 +454,38 @@ public static function getComposerPackage(string $name): string return str($composer)->after('"'.$name.'": "')->before('"'); } + + /** + * Set disk code for controller. + */ + public static function setDiskCodeForController(string $name): string + { + return match (config('generator.image.disk')) { + // '/images/'; + 's3' => "'/". self::pluralKebabCase($name) ."/'", + + // 'public_path('uploads/images/'); + 'public' => "public_path('uploads/". self::pluralKebabCase($name) ."/')", + + // 'storage_path('app/public/uploads/images/'); + default => "storage_path('app/public/uploads/". self::pluralKebabCase($name) ."/')", + }; + } + + /** + * Set disk code for cast an image. + */ + public static function setDiskCodeForCastImage(string $model, string $field): string + { + return match (config('generator.image.disk')) { + // \Illuminate\Support\Facades\Storage::disk('s3')->url('images/' . $generator->image); + 's3' => "\Illuminate\Support\Facades\Storage::disk('s3')->url(\$this->". self::singularCamelCase($field) ."Path . $" . self::singularCamelCase($model) . "->" . str($field)->snake() . ")", + + //asset('/uploads/photos/' . $generator->image); + 'public' => "asset('/uploads/" . self::pluralKebabCase($field) . "/' . $" . self::singularCamelCase($model) . "->" . str($field)->snake() . ")", + + //asset('storage/uploads/images/' . $generator->image) + default => "asset('storage/uploads/" . self::pluralKebabCase($field) . "/' . $" . self::singularCamelCase($model) . "->" . str($field)->snake() . ")", + }; + } } diff --git a/stubs/generators/publish/utils/Interfaces/ImageInterface.php b/stubs/generators/publish/utils/Interfaces/ImageServiceInterface.php similarity index 90% rename from stubs/generators/publish/utils/Interfaces/ImageInterface.php rename to stubs/generators/publish/utils/Interfaces/ImageServiceInterface.php index f5f316cc..be7282bc 100644 --- a/stubs/generators/publish/utils/Interfaces/ImageInterface.php +++ b/stubs/generators/publish/utils/Interfaces/ImageServiceInterface.php @@ -2,9 +2,9 @@ namespace App\Generators\Interfaces; -interface ImageInterface +interface ImageServiceInterface { public function upload(string $name, string $path, string|null $defaultImage = null, string $disk = 'local', int $width = 500, int $height = 500, bool $isCustomUpload = false): string|null; - + public function delete(string|null $image, string $disk = 'local'): void; } diff --git a/stubs/generators/publish/utils/Services/ImageService.php b/stubs/generators/publish/utils/Services/ImageService.php index f53e50a1..c6ae8ea1 100644 --- a/stubs/generators/publish/utils/Services/ImageService.php +++ b/stubs/generators/publish/utils/Services/ImageService.php @@ -3,10 +3,10 @@ namespace App\Generators\Services; use App\Generators\GeneratorUtils; -use App\Generators\Interfaces\ImageInterface; +use App\Generators\Interfaces\ImageServiceInterface; use Illuminate\Support\Facades\Storage; -class ImageService implements ImageInterface +class ImageService implements ImageServiceInterface { /** * @throws \Exception From 27c781042ffdaae2b4b98101adda18e05a1a969e Mon Sep 17 00:00:00 2001 From: Mohammad Zulfahmi Date: Thu, 14 Mar 2024 21:21:18 +0700 Subject: [PATCH 021/105] change intervention image ti version 3 --- composer.json | 2 +- src/Generators/PermissionGenerator.php | 12 +- src/Generators/Services/GeneratorService.php | 62 +++++----- src/Generators/Views/FormViewGenerator.php | 23 ++-- src/Generators/Views/ShowViewGenerator.php | 14 +-- .../publish/config/full-version/generator.php | 115 ++++++++---------- .../config/simple-version/generator.php | 115 ++++++++---------- .../full-version/FortifyServiceProvider.php | 28 ++--- .../full-version/RouteServiceProvider.php | 4 +- .../publish/utils/Services/ImageService.php | 2 +- stubs/generators/views/forms/image.stub | 2 +- 11 files changed, 167 insertions(+), 212 deletions(-) diff --git a/composer.json b/composer.json index f07586d2..58df6829 100644 --- a/composer.json +++ b/composer.json @@ -27,7 +27,7 @@ ], "require": { "php": "^8.2", - "intervention/image": "^2.7", + "intervention/image-laravel": "^1.1", "yajra/laravel-datatables-oracle": "^10.0" }, "require-dev": { diff --git a/src/Generators/PermissionGenerator.php b/src/Generators/PermissionGenerator.php index 141025a5..70b4f615 100644 --- a/src/Generators/PermissionGenerator.php +++ b/src/Generators/PermissionGenerator.php @@ -65,25 +65,23 @@ protected function insertRoleAndPermissions(string $model): void $permissions = [ [ 'name' => "$model view", - // 'guard_name' => GeneratorUtils::isGenerateApi() ? 'api' : 'web' + 'guard_name' => GeneratorUtils::isGenerateApi() ? 'api' : 'web' ], [ 'name' => "$model create", - // 'guard_name' => GeneratorUtils::isGenerateApi() ? 'api' : 'web' + 'guard_name' => GeneratorUtils::isGenerateApi() ? 'api' : 'web' ], [ 'name' => "$model edit", - // 'guard_name' => GeneratorUtils::isGenerateApi() ? 'api' : 'web' + 'guard_name' => GeneratorUtils::isGenerateApi() ? 'api' : 'web' ], [ 'name' => "$model delete", - // 'guard_name' => GeneratorUtils::isGenerateApi() ? 'api' : 'web' + 'guard_name' => GeneratorUtils::isGenerateApi() ? 'api' : 'web' ] ]; - foreach ($permissions as $permission) { - Permission::firstOrCreate($permission); - } + foreach ($permissions as $permission) Permission::firstOrCreate($permission); $role->givePermissionTo([ "$model view", diff --git a/src/Generators/Services/GeneratorService.php b/src/Generators/Services/GeneratorService.php index ead07117..6852af9c 100644 --- a/src/Generators/Services/GeneratorService.php +++ b/src/Generators/Services/GeneratorService.php @@ -35,38 +35,38 @@ class GeneratorService implements GeneratorServiceInterface */ public function generate(array $request): void { -// if (empty($request['is_simple_generator'])) (new PermissionGenerator)->generate($request); -// -// (new ModelGenerator)->generate($request); -// (new MigrationGenerator)->generate($request); + if (empty($request['is_simple_generator'])) (new PermissionGenerator)->generate($request); + + (new ModelGenerator)->generate($request); + (new MigrationGenerator)->generate($request); (new ControllerGenerator)->generate($request); -// (new RequestGenerator)->generate($request); -// -// // blade template -// if (empty($request['generate_variant']) || $request['generate_variant'] != 'api') { -// (new IndexViewGenerator)->generate($request); -// (new CreateViewGenerator)->generate($request); -// (new ShowViewGenerator)->generate($request); -// (new EditViewGenerator)->generate($request); -// (new ActionViewGenerator)->generate($request); -// (new FormViewGenerator)->generate($request); -// -// if (empty($request['is_simple_generator'])) (new MenuGenerator)->generate($request); -// -// if (in_array('foreignId', $request['column_types'])) (new ViewComposerGenerator)->generate($request); -// } -// -// (new RouteGenerator)->generate($request); -// -// if (isset($request['generate_seeder']) && $request['generate_seeder'] != null) (new SeederGenerator)->generate($request); -// -// if (isset($request['generate_factory']) && $request['generate_factory'] != null) (new FactoryGenerator)->generate($request); -// -// if (GeneratorUtils::isGenerateApi()) (new ResourceApiGenerator)->generate($request); -// -// if (empty($request['generate_variant']) && $request['generate_variant'] != 'api' || empty($request['is_simple_generator'])) $this->checkSidebarType(); -// -// Artisan::call('migrate'); + (new RequestGenerator)->generate($request); + + // blade template + if (empty($request['generate_variant']) || $request['generate_variant'] != 'api') { + (new IndexViewGenerator)->generate($request); + (new CreateViewGenerator)->generate($request); + (new ShowViewGenerator)->generate($request); + (new EditViewGenerator)->generate($request); + (new ActionViewGenerator)->generate($request); + (new FormViewGenerator)->generate($request); + + if (empty($request['is_simple_generator'])) (new MenuGenerator)->generate($request); + + if (in_array('foreignId', $request['column_types'])) (new ViewComposerGenerator)->generate($request); + } + + (new RouteGenerator)->generate($request); + + if (isset($request['generate_seeder']) && $request['generate_seeder'] != null) (new SeederGenerator)->generate($request); + + if (isset($request['generate_factory']) && $request['generate_factory'] != null) (new FactoryGenerator)->generate($request); + + if (GeneratorUtils::isGenerateApi()) (new ResourceApiGenerator)->generate($request); + + if (empty($request['generate_variant']) && $request['generate_variant'] != 'api' || empty($request['is_simple_generator'])) $this->checkSidebarType(); + + Artisan::call('migrate'); } /** diff --git a/src/Generators/Views/FormViewGenerator.php b/src/Generators/Views/FormViewGenerator.php index 61c7d311..b4a3019b 100644 --- a/src/Generators/Views/FormViewGenerator.php +++ b/src/Generators/Views/FormViewGenerator.php @@ -197,7 +197,7 @@ public function generate(array $request): void } break; case 'year': - $firstYear = is_int(config('generator.format.first_year')) ? config('generator.format.first_year') : 1900; + $firstYear = is_int(config('generator.format.first_year')) ? config('generator.format.first_year') : 1970; /** * Will generate something like: @@ -344,11 +344,11 @@ public function generate(array $request): void $formatValue = "{{ isset($$modelNameSingularCamelCase) && $" . $modelNameSingularCamelCase . "->$fieldSnakeCase ? $" . $modelNameSingularCamelCase . "->" . $fieldSnakeCase . "->format('Y-m-d\TH:i') : old('$fieldSnakeCase') }}"; $template .= $this->setInputTypeTemplate( + field: $field, request: [ 'input_types' => $request['input_types'][$i], 'requireds' => $request['requireds'][$i] ], - field: $field, formatValue: $formatValue ); break; @@ -361,11 +361,11 @@ public function generate(array $request): void $formatValue = "{{ isset($$modelNameSingularCamelCase) && $" . $modelNameSingularCamelCase . "->$fieldSnakeCase ? $" . $modelNameSingularCamelCase . "->" . $fieldSnakeCase . "->format('Y-m-d') : old('$fieldSnakeCase') }}"; $template .= $this->setInputTypeTemplate( + field: $field, request: [ 'input_types' => $request['input_types'][$i], 'requireds' => $request['requireds'][$i] ], - field: $field, formatValue: $formatValue ); break; @@ -378,11 +378,11 @@ public function generate(array $request): void $formatValue = "{{ isset($$modelNameSingularCamelCase) && $" . $modelNameSingularCamelCase . "->$fieldSnakeCase ? $" . $modelNameSingularCamelCase . "->" . $fieldSnakeCase . "->format('H:i') : old('$fieldSnakeCase') }}"; $template .= $this->setInputTypeTemplate( + field: $field, request: [ 'input_types' => $request['input_types'][$i], 'requireds' => $request['requireds'][$i] ], - field: $field, formatValue: $formatValue ); break; @@ -395,11 +395,11 @@ public function generate(array $request): void $formatValue = "{{ isset($$modelNameSingularCamelCase) && $" . $modelNameSingularCamelCase . "->$fieldSnakeCase ? $" . $modelNameSingularCamelCase . "->" . $fieldSnakeCase . "->format('Y-\WW') : old('$fieldSnakeCase') }}"; $template .= $this->setInputTypeTemplate( + field: $field, request: [ 'input_types' => $request['input_types'][$i], 'requireds' => $request['requireds'][$i] ], - field: $field, formatValue: $formatValue ); break; @@ -412,11 +412,11 @@ public function generate(array $request): void $formatValue = "{{ isset($$modelNameSingularCamelCase) && $" . $modelNameSingularCamelCase . "->$fieldSnakeCase ? $" . $modelNameSingularCamelCase . "->" . $fieldSnakeCase . "->format('Y-m') : old('$fieldSnakeCase') }}"; $template .= $this->setInputTypeTemplate( + field: $field, request: [ 'input_types' => $request['input_types'][$i], 'requireds' => $request['requireds'][$i] ], - field: $field, formatValue: $formatValue ); break; @@ -429,7 +429,6 @@ public function generate(array $request): void '{{modelName}}', '{{nullable}}', '{{fieldSnakeCase}}' - ], [ GeneratorUtils::kebabCase($field), @@ -460,6 +459,7 @@ public function generate(array $request): void '{{fieldKebabCase}}', '{{defaultImage}}', '{{defaultImageCodeForm}}', + '{{setDiskForCastImage}}' ], [ $modelNameSingularCamelCase, @@ -471,7 +471,12 @@ public function generate(array $request): void config('generator.image.disk') == 'storage' ? "storage/uploads" : "uploads", str()->kebab($field), $default['image'], - $default['form_code'] + $default['form_code'], + /* + * when disk is s3 it will generate something like: \Illuminate\Support\Facades\Storage::disk('s3')->url($this->photoPath . $cat->photo) + * $this->photoPath, not available in view then change to 'photos/' + */ + str_replace("\$this->". GeneratorUtils::singularCamelCase($field) ."Path", "'". GeneratorUtils::pluralKebabCase($field) ."/'", GeneratorUtils::setDiskCodeForCastImage($model, $field) ) ], GeneratorUtils::getStub('views/forms/image') ); @@ -521,11 +526,11 @@ public function generate(array $request): void break; default: $template .= $this->setInputTypeTemplate( + field: $field, request: [ 'input_types' => $request['input_types'][$i], 'requireds' => $request['requireds'][$i] ], - field: $field, formatValue: $formatValue ); break; diff --git a/src/Generators/Views/ShowViewGenerator.php b/src/Generators/Views/ShowViewGenerator.php index b54c3082..a81ec2fd 100644 --- a/src/Generators/Views/ShowViewGenerator.php +++ b/src/Generators/Views/ShowViewGenerator.php @@ -23,9 +23,7 @@ public function generate(array $request): void foreach ($request['fields'] as $i => $field) { if ($request['input_types'][$i] != 'password') { - if ($i >= 1) { - $trs .= "\t\t\t\t\t\t\t\t\t"; - } + if ($i >= 1) $trs .= "\t\t\t\t\t\t\t\t\t"; $fieldUcWords = GeneratorUtils::cleanUcWords($field); $fieldSnakeCase = str($field)->snake(); @@ -45,7 +43,7 @@ public function generate(array $request): void @if (" . $default['form_code'] . ") \"$fieldUcWords\" @else - plural()->snake() . "/' . $" . $modelNameSingularCamelCase . "->" . $fieldSnakeCase . ") }}\" alt=\"$fieldUcWords\" class=\"rounded\" width=\"200\" height=\"150\" style=\"object-fit: cover\"> + \"$fieldUcWords\" @endif "; @@ -70,9 +68,7 @@ public function generate(array $request): void case 'date': $dateFormat = config('generator.format.date') ? config('generator.format.date') : 'd/m/Y'; - if ($request['input_types'][$i] == 'month') { - $dateFormat = config('generator.format.month') ? config('generator.format.month') : 'm/Y'; - } + if ($request['input_types'][$i] == 'month') $dateFormat = config('generator.format.month') ? config('generator.format.month') : 'm/Y'; $trs .= " {{ __('$fieldUcWords') }} @@ -103,9 +99,7 @@ public function generate(array $request): void break; } - if ($i + 1 != $totalFields) { - $trs .= "\n"; - } + if ($i + 1 != $totalFields) $trs .= "\n"; } } diff --git a/stubs/generators/publish/config/full-version/generator.php b/stubs/generators/publish/config/full-version/generator.php index ec1ef19a..4a34947e 100644 --- a/stubs/generators/publish/config/full-version/generator.php +++ b/stubs/generators/publish/config/full-version/generator.php @@ -4,50 +4,44 @@ /** * If any input file(image) as default will use options below. */ - 'image' => [ + "image" => [ /** * Path for store the image. * - * available options: + * Available options: * 1. public * 2. storage + * 3. S3 */ - 'path' => 'storage', - - /** - * Supported disk - * 1. local - * 2. S3 - */ - 'disk' => 'local', + "disk" => "s3", /** * Will be used if image is nullable and default value is null. */ - 'default' => 'https://via.placeholder.com/350?text=No+Image+Avaiable', + "default" => "https://via.placeholder.com/350?text=No+Image+Avaiable", /** * Crop the uploaded image using intervention image. */ - 'crop' => true, + "crop" => false, /** * When set to true the uploaded image aspect ratio will still original. */ - 'aspect_ratio' => true, + "aspect_ratio" => true, /** * Crop image size. */ - 'width' => 500, - 'height' => 500, + "width" => 500, + "height" => 500, ], - 'format' => [ + "format" => [ /** * Will be used to first year on select, if any column type year. */ - 'first_year' => 1900, + "first_year" => 1970, /** * If any date column type will cast and display used this format, but for input date still will used Y-m-d format. @@ -57,27 +51,27 @@ * - d F Y * - Y m d */ - 'date' => 'd/m/Y', + "date" => "d/m/Y", /** * If any input type month will cast and display used this format. */ - 'month' => 'm/Y', + "month" => "m/Y", /** * If any input type time will cast and display used this format. */ - 'time' => 'H:i', + "time" => "H:i", /** * If any datetime column type or datetime-local on input, will cast and display used this format. */ - 'datetime' => 'Y-m-d H:i:s', + "datetime" => "Y-m-d H:i:s", /** * Limit string on index view for any column type text or longtext. */ - 'limit_text' => 100, + "limit_text" => 100, ], /** @@ -115,55 +109,48 @@ * * This code below always changes when you use a generator, and maybe you must format the code. */ - 'sidebars' => [ + "sidebars" => [ [ - 'header' => 'Main', - 'permissions' => [ - 'test view', - ], - 'menus' => [ + "header" => "Main", + "permissions" => ["test view"], + "menus" => [ [ - 'title' => 'Main Data', - 'icon' => '', - 'route' => null, - 'permission' => null, - 'permissions' => [ - 'test view', - ], - 'submenus' => [ + "title" => "Main Data", + "icon" => '', + "route" => null, + "permission" => null, + "permissions" => ["test view"], + "submenus" => [ [ - 'title' => 'Tests', - 'route' => '/tests', - 'permission' => 'test view' + "title" => "Tests", + "route" => "/tests", + "permission" => "test view", ], - ] - ] - ] + ], + ], + ], ], [ - 'header' => 'Users', - 'permissions' => [ - 'user view', - 'role & permission view' - ], - 'menus' => [ + "header" => "Users", + "permissions" => ["user view", "role & permission view"], + "menus" => [ [ - 'title' => 'Users', - 'icon' => '', - 'route' => '/users', - 'permission' => 'user view', - 'permissions' => [], - 'submenus' => [] + "title" => "Users", + "icon" => '', + "route" => "/users", + "permission" => "user view", + "permissions" => [], + "submenus" => [], ], [ - 'title' => 'Roles & permissions', - 'icon' => '', - 'route' => '/roles', - 'permission' => 'role & permission view', - 'permissions' => [], - 'submenus' => [] - ] - ] - ] - ] + "title" => "Roles & permissions", + "icon" => '', + "route" => "/roles", + "permission" => "role & permission view", + "permissions" => [], + "submenus" => [], + ], + ], + ], + ], ]; diff --git a/stubs/generators/publish/config/simple-version/generator.php b/stubs/generators/publish/config/simple-version/generator.php index ec1ef19a..4a34947e 100644 --- a/stubs/generators/publish/config/simple-version/generator.php +++ b/stubs/generators/publish/config/simple-version/generator.php @@ -4,50 +4,44 @@ /** * If any input file(image) as default will use options below. */ - 'image' => [ + "image" => [ /** * Path for store the image. * - * available options: + * Available options: * 1. public * 2. storage + * 3. S3 */ - 'path' => 'storage', - - /** - * Supported disk - * 1. local - * 2. S3 - */ - 'disk' => 'local', + "disk" => "s3", /** * Will be used if image is nullable and default value is null. */ - 'default' => 'https://via.placeholder.com/350?text=No+Image+Avaiable', + "default" => "https://via.placeholder.com/350?text=No+Image+Avaiable", /** * Crop the uploaded image using intervention image. */ - 'crop' => true, + "crop" => false, /** * When set to true the uploaded image aspect ratio will still original. */ - 'aspect_ratio' => true, + "aspect_ratio" => true, /** * Crop image size. */ - 'width' => 500, - 'height' => 500, + "width" => 500, + "height" => 500, ], - 'format' => [ + "format" => [ /** * Will be used to first year on select, if any column type year. */ - 'first_year' => 1900, + "first_year" => 1970, /** * If any date column type will cast and display used this format, but for input date still will used Y-m-d format. @@ -57,27 +51,27 @@ * - d F Y * - Y m d */ - 'date' => 'd/m/Y', + "date" => "d/m/Y", /** * If any input type month will cast and display used this format. */ - 'month' => 'm/Y', + "month" => "m/Y", /** * If any input type time will cast and display used this format. */ - 'time' => 'H:i', + "time" => "H:i", /** * If any datetime column type or datetime-local on input, will cast and display used this format. */ - 'datetime' => 'Y-m-d H:i:s', + "datetime" => "Y-m-d H:i:s", /** * Limit string on index view for any column type text or longtext. */ - 'limit_text' => 100, + "limit_text" => 100, ], /** @@ -115,55 +109,48 @@ * * This code below always changes when you use a generator, and maybe you must format the code. */ - 'sidebars' => [ + "sidebars" => [ [ - 'header' => 'Main', - 'permissions' => [ - 'test view', - ], - 'menus' => [ + "header" => "Main", + "permissions" => ["test view"], + "menus" => [ [ - 'title' => 'Main Data', - 'icon' => '', - 'route' => null, - 'permission' => null, - 'permissions' => [ - 'test view', - ], - 'submenus' => [ + "title" => "Main Data", + "icon" => '', + "route" => null, + "permission" => null, + "permissions" => ["test view"], + "submenus" => [ [ - 'title' => 'Tests', - 'route' => '/tests', - 'permission' => 'test view' + "title" => "Tests", + "route" => "/tests", + "permission" => "test view", ], - ] - ] - ] + ], + ], + ], ], [ - 'header' => 'Users', - 'permissions' => [ - 'user view', - 'role & permission view' - ], - 'menus' => [ + "header" => "Users", + "permissions" => ["user view", "role & permission view"], + "menus" => [ [ - 'title' => 'Users', - 'icon' => '', - 'route' => '/users', - 'permission' => 'user view', - 'permissions' => [], - 'submenus' => [] + "title" => "Users", + "icon" => '', + "route" => "/users", + "permission" => "user view", + "permissions" => [], + "submenus" => [], ], [ - 'title' => 'Roles & permissions', - 'icon' => '', - 'route' => '/roles', - 'permission' => 'role & permission view', - 'permissions' => [], - 'submenus' => [] - ] - ] - ] - ] + "title" => "Roles & permissions", + "icon" => '', + "route" => "/roles", + "permission" => "role & permission view", + "permissions" => [], + "submenus" => [], + ], + ], + ], + ], ]; diff --git a/stubs/generators/publish/providers/full-version/FortifyServiceProvider.php b/stubs/generators/publish/providers/full-version/FortifyServiceProvider.php index 446b905c..1d8539e9 100644 --- a/stubs/generators/publish/providers/full-version/FortifyServiceProvider.php +++ b/stubs/generators/publish/providers/full-version/FortifyServiceProvider.php @@ -36,32 +36,18 @@ public function boot(): void return Limit::perMinute(5)->by($throttleKey); }); - RateLimiter::for('two-factor', function (Request $request) { - return Limit::perMinute(5)->by($request->session()->get('login.id')); - }); + RateLimiter::for('two-factor', fn (Request $request) => Limit::perMinute(5)->by($request->session()->get('login.id'))); - Fortify::registerView(function () { - return view('auth.register'); - }); + Fortify::registerView(fn () => view('auth.register')); - Fortify::loginView(function () { - return view('auth.login'); - }); + Fortify::loginView(fn() => view('auth.login')); - Fortify::confirmPasswordView(function () { - return view('auth.confirm-password'); - }); + Fortify::confirmPasswordView(fn() => view('auth.confirm-password')); - Fortify::twoFactorChallengeView(function () { - return view('auth.two-factor-challenge'); - }); + Fortify::twoFactorChallengeView(fn () => view('auth.two-factor-challenge')); - Fortify::requestPasswordResetLinkView(function () { - return view('auth.forgot-password'); - }); + Fortify::requestPasswordResetLinkView(fn() => view('auth.forgot-password')); - Fortify::resetPasswordView(function ($request) { - return view('auth.reset-password', ['request' => $request]); - }); + Fortify::resetPasswordView(fn (Request $request) => view('auth.reset-password', ['request' => $request])); } } diff --git a/stubs/generators/publish/providers/full-version/RouteServiceProvider.php b/stubs/generators/publish/providers/full-version/RouteServiceProvider.php index 8f86ab5a..bfaa2fec 100644 --- a/stubs/generators/publish/providers/full-version/RouteServiceProvider.php +++ b/stubs/generators/publish/providers/full-version/RouteServiceProvider.php @@ -23,9 +23,7 @@ class RouteServiceProvider extends ServiceProvider */ public function boot(): void { - RateLimiter::for('api', function (Request $request) { - return Limit::perMinute(60)->by($request->user()?->id ?: $request->ip()); - }); + RateLimiter::for('api', fn (Request $request) => Limit::perMinute(60)->by($request->user()?->id ?: $request->ip())); $this->routes(function () { Route::middleware('api')->prefix('api')->group(base_path('routes/api.php')); diff --git a/stubs/generators/publish/utils/Services/ImageService.php b/stubs/generators/publish/utils/Services/ImageService.php index c6ae8ea1..1bc29de8 100644 --- a/stubs/generators/publish/utils/Services/ImageService.php +++ b/stubs/generators/publish/utils/Services/ImageService.php @@ -17,7 +17,7 @@ public function upload(string $name, string $path, string|null $defaultImage = n if(!$isCustomUpload){ $file = request()->file($name); - if (str_contains(GeneratorUtils::checkPackageVersion('intervention/image-laravel'), '2')) { + if (str_contains(GeneratorUtils::checkPackageVersion('intervention/image'), '2')) { $filename = $file->hashName(); } else { // set image to webp diff --git a/stubs/generators/views/forms/image.stub b/stubs/generators/views/forms/image.stub index 33def578..c2f49283 100644 --- a/stubs/generators/views/forms/image.stub +++ b/stubs/generators/views/forms/image.stub @@ -5,7 +5,7 @@ @if ({{defaultImageCodeForm}}) {{fieldUcWords}} @else - {{fieldUcWords}} + {{fieldUcWords}} @endif
From 76bea803d3bc13f8bf080cd8c96e6e131d970165 Mon Sep 17 00:00:00 2001 From: Mohammad Zulfahmi Date: Fri, 15 Mar 2024 08:11:33 +0700 Subject: [PATCH 022/105] fix image in show page generator --- src/Generators/Views/ShowViewGenerator.php | 9 +++++++-- stubs/generators/views/forms/image.stub | 4 ++-- 2 files changed, 9 insertions(+), 4 deletions(-) diff --git a/src/Generators/Views/ShowViewGenerator.php b/src/Generators/Views/ShowViewGenerator.php index a81ec2fd..5e509fea 100644 --- a/src/Generators/Views/ShowViewGenerator.php +++ b/src/Generators/Views/ShowViewGenerator.php @@ -35,7 +35,12 @@ public function generate(array $request): void model: $model ); - $uploadPath = config('generator.image.disk') == 'storage' ? "storage/uploads/" : "uploads/"; + $castImage = str_replace( + "\$this->" . GeneratorUtils::singularCamelCase($field) . "Path", + "'" . GeneratorUtils::pluralKebabCase($field) . "/'", + GeneratorUtils::setDiskCodeForCastImage($model, $field) + ); + $trs .= " {{ __('$fieldUcWords') }} @@ -43,7 +48,7 @@ public function generate(array $request): void @if (" . $default['form_code'] . ") \"$fieldUcWords\" @else - \"$fieldUcWords\" + \"$fieldUcWords\" @endif "; diff --git a/stubs/generators/views/forms/image.stub b/stubs/generators/views/forms/image.stub index c2f49283..e7930ae3 100644 --- a/stubs/generators/views/forms/image.stub +++ b/stubs/generators/views/forms/image.stub @@ -1,7 +1,7 @@ @isset(${{modelCamelCase}})
-
+
@if ({{defaultImageCodeForm}}) {{fieldUcWords}} @else @@ -9,7 +9,7 @@ @endif
-
+
From a271a26669fe01462036d3791b5347ed0b9d2c07 Mon Sep 17 00:00:00 2001 From: Mohammad Zulfahmi Date: Sat, 16 Mar 2024 09:24:38 +0700 Subject: [PATCH 023/105] update Intervention/image & laravel-datatables-oracle --- composer.json | 11 ++++------- src/Generators/MenuGenerator.php | 14 ++++++++++---- 2 files changed, 14 insertions(+), 11 deletions(-) diff --git a/composer.json b/composer.json index 58df6829..7fa8487e 100644 --- a/composer.json +++ b/composer.json @@ -28,11 +28,10 @@ "require": { "php": "^8.2", "intervention/image-laravel": "^1.1", - "yajra/laravel-datatables-oracle": "^10.0" + "yajra/laravel-datatables-oracle": "^11.0" }, "require-dev": { - "nunomaduro/collision": "^6.3", - "orchestra/testbench": "^7.14" + "orchestra/testbench": "9.0" }, "config": { "optimize-autoloader": true, @@ -44,12 +43,10 @@ "laravel": { "providers": [ "EvdigiIna\\Generator\\Providers\\GeneratorServiceProvider", - "Yajra\\DataTables\\DataTablesServiceProvider", - "Intervention\\Image\\ImageServiceProvider" + "Yajra\\DataTables\\DataTablesServiceProvider" ], "aliases": { - "DataTables": "Yajra\\DataTables\\Facades\\DataTables", - "Image": "Intervention\\Image\\Facades\\Image" + "DataTables": "Yajra\\DataTables\\Facades\\DataTables" } } } diff --git a/src/Generators/MenuGenerator.php b/src/Generators/MenuGenerator.php index 23d869e3..f4e154a2 100644 --- a/src/Generators/MenuGenerator.php +++ b/src/Generators/MenuGenerator.php @@ -2,8 +2,6 @@ namespace EvdigiIna\Generator\Generators; -use Spatie\Permission\Models\Permission; - class MenuGenerator { /** @@ -140,9 +138,17 @@ protected function generateNewSubMenu(array $menu, string $model, array $configS */ protected function generateFile(string $jsonToArrayString): void { - $configStringCode = str(file_get_contents(config_path('generator.php')))->before("'sidebars' => "); + $stringConfig = str(file_get_contents(config_path('generator.php'))); + + if(str_contains($stringConfig, "'sidebars' => ")){ + $search = "'sidebars' => "; + $stringConfigCode = $stringConfig->before($search); + }else{ + $search = '"sidebars" => '; + $stringConfigCode = $stringConfig->before($search); + } - $template = $configStringCode . "'sidebars' => " . $jsonToArrayString . "\n];"; + $template = $stringConfigCode . $search . $jsonToArrayString . "\n];"; file_put_contents(base_path('config/generator.php'), $template); } From 9493e1a2eaaa7931cb7476b770180598d443cee4 Mon Sep 17 00:00:00 2001 From: Mohammad Zulfahmi Date: Wed, 20 Mar 2024 10:15:29 +0700 Subject: [PATCH 024/105] fix wrong namespace in publish GeneratorUtils --- src/Generators/ModelGenerator.php | 26 ++-- src/Providers/GeneratorServiceProvider.php | 12 +- .../publish/config/full-version/fortify.php | 18 ++- .../publish/config/full-version/generator.php | 4 +- .../config/full-version/permission.php | 49 ++++++-- .../config/simple-version/generator.php | 4 +- stubs/generators/publish/models/User.php | 15 ++- .../publish/utils/GeneratorUtils.php | 5 +- .../publish/utils/Services/ImageService.php | 116 +++++++++--------- stubs/generators/views/forms/datalist.stub | 2 +- 10 files changed, 145 insertions(+), 106 deletions(-) diff --git a/src/Generators/ModelGenerator.php b/src/Generators/ModelGenerator.php index 109a72a0..0ed0dbac 100644 --- a/src/Generators/ModelGenerator.php +++ b/src/Generators/ModelGenerator.php @@ -17,7 +17,7 @@ public function generate(array $request): void $casts = "["; $relations = ""; $totalFields = count($request['fields']); - $dateTimeFormat = config('generator.format.datetime') ? config('generator.format.datetime') : 'Y-m-d H:i:s'; + $dateTimeFormat = config('generator.format.datetime') ?? 'Y-m-d H:i:s'; $protectedHidden = ""; if (in_array('password', $request['input_types'])) { @@ -39,14 +39,12 @@ public function generate(array $request): void default => "'" . str()->snake($field) . "']", }; - if ($request['input_types'][$i] == 'password') { - $protectedHidden .= "'" . str()->snake($field) . "', "; - } + if ($request['input_types'][$i] == 'password') $protectedHidden .= "'" . str()->snake($field) . "', "; switch ($request['column_types'][$i]) { case 'date': if ($request['input_types'][$i] != 'month') { - $dateFormat = config('generator.format.date') ? config('generator.format.date') : 'd/m/Y'; + $dateFormat = config('generator.format.date') ?? 'd/m/Y'; $casts .= "'" . str()->snake($field) . "' => 'date:$dateFormat', "; } break; @@ -75,9 +73,7 @@ public function generate(array $request): void $foreign_id = isset($request['foreign_ids'][$i]) ? ", '" . $request['foreign_ids'][$i] . "'" : ''; - if ($i > 0) { - $relations .= "\t"; - } + if ($i > 0) $relations .= "\t"; /** * will generate something like: @@ -116,13 +112,9 @@ public function generate(array $request): void } // integer/bigInteger/tinyInteger/ - if (str_contains($request['column_types'][$i], 'integer')) { - $casts .= "'" . str()->snake($field) . "' => 'integer', "; - } + if (str_contains($request['column_types'][$i], 'integer')) $casts .= "'" . str()->snake($field) . "' => 'integer', "; - if (in_array($request['column_types'][$i], ['string', 'text', 'char']) && $request['input_types'][$i] != 'week') { - $casts .= "'" . str()->snake($field) . "' => 'string', "; - } + if (in_array($request['column_types'][$i], ['string', 'text', 'char']) && $request['input_types'][$i] != 'week') $casts .= "'" . str()->snake($field) . "' => 'string', "; } if ($protectedHidden != "") { @@ -131,9 +123,9 @@ public function generate(array $request): void $protectedHidden = substr($protectedHidden, 0, -2) . "];"; } - // $casts .= << 'datetime:$dateTimeFormat', 'updated_at' => 'datetime:$dateTimeFormat'] - // PHP; + $casts .= << 'datetime:$dateTimeFormat', 'updated_at' => 'datetime:$dateTimeFormat'] + PHP; $casts .= "]"; diff --git a/src/Providers/GeneratorServiceProvider.php b/src/Providers/GeneratorServiceProvider.php index 6b443db4..0369dd56 100644 --- a/src/Providers/GeneratorServiceProvider.php +++ b/src/Providers/GeneratorServiceProvider.php @@ -91,12 +91,12 @@ public function boot(): void __DIR__ . '/../../stubs/generators/publish/utils' => app_path('Generators') ], 'generator-utils'); - \Illuminate\Foundation\Console\AboutCommand::add('Generator', fn () => [ - 'Version' => '0.3.0', - 'Source' => 'https://github.com/evdigiina/generator', - 'Docs' => 'https://evdigi-ina.github.io/generator-docs', - 'About' => 'Package for building basic CRUD, especially for your master(main) data.' - ]); + \Illuminate\Foundation\Console\AboutCommand::add('Generator', fn () => [ + 'Version' => '0.3.0', + 'Source' => 'https://github.com/evdigiina/generator', + 'Docs' => 'https://evdigi-ina.github.io/generator-docs', + 'About' => 'Package for building basic CRUD, especially for your main data.' + ]); if ($this->app->runningInConsole()) $this->commands([PublishAllFiles::class]); diff --git a/stubs/generators/publish/config/full-version/fortify.php b/stubs/generators/publish/config/full-version/fortify.php index 0226449c..2385239b 100644 --- a/stubs/generators/publish/config/full-version/fortify.php +++ b/stubs/generators/publish/config/full-version/fortify.php @@ -1,6 +1,5 @@ 'email', + /* + |-------------------------------------------------------------------------- + | Lowercase Usernames + |-------------------------------------------------------------------------- + | + | This value defines whether usernames should be lowercased before saving + | them in the database, as some database system string fields are case + | sensitive. You may disable this for your application if necessary. + | + */ + + 'lowercase_usernames' => true, + /* |-------------------------------------------------------------------------- | Home Path @@ -61,7 +73,7 @@ | */ - 'home' => RouteServiceProvider::HOME, + 'home' => '/', /* |-------------------------------------------------------------------------- @@ -138,7 +150,9 @@ Features::updateProfileInformation(), Features::updatePasswords(), Features::twoFactorAuthentication([ + 'confirm' => true, 'confirmPassword' => true, + // 'window' => 0, ]), ], diff --git a/stubs/generators/publish/config/full-version/generator.php b/stubs/generators/publish/config/full-version/generator.php index 4a34947e..4849c41e 100644 --- a/stubs/generators/publish/config/full-version/generator.php +++ b/stubs/generators/publish/config/full-version/generator.php @@ -13,7 +13,7 @@ * 2. storage * 3. S3 */ - "disk" => "s3", + "disk" => "storage", /** * Will be used if image is nullable and default value is null. @@ -69,7 +69,7 @@ "datetime" => "Y-m-d H:i:s", /** - * Limit string on index view for any column type text or longtext. + * Limit string on index view for any column type text or long text. */ "limit_text" => 100, ], diff --git a/stubs/generators/publish/config/full-version/permission.php b/stubs/generators/publish/config/full-version/permission.php index 82f39272..c89f6ba9 100644 --- a/stubs/generators/publish/config/full-version/permission.php +++ b/stubs/generators/publish/config/full-version/permission.php @@ -98,43 +98,68 @@ /* * When set to true, the method for checking permissions will be registered on the gate. - * Set this to false, if you want to implement custom logic for checking permissions. + * Set this to false if you want to implement custom logic for checking permissions. */ 'register_permission_check_method' => true, /* - * When set to true the package implements teams using the 'team_foreign_key'. If you want - * the migrations to register the 'team_foreign_key', you must set this to true - * before doing the migration. If you already did the migration then you must make a new - * migration to also add 'team_foreign_key' to 'roles', 'model_has_roles', and - * 'model_has_permissions'(view the latest version of package's migration file) + * When set to true, Laravel\Octane\Events\OperationTerminated event listener will be registered + * this will refresh permissions on every TickTerminated, TaskTerminated and RequestTerminated + * NOTE: This should not be needed in most cases, but an Octane/Vapor combination benefited from it. + */ + 'register_octane_reset_listener' => false, + + /* + * Teams Feature. + * When set to true the package implements teams using the 'team_foreign_key'. + * If you want the migrations to register the 'team_foreign_key', you must + * set this to true before doing the migration. + * If you already did the migration then you must make a new migration to also + * add 'team_foreign_key' to 'roles', 'model_has_roles', and 'model_has_permissions' + * (view the latest version of this package's migration file) */ 'teams' => false, /* - * When set to true, the required permission names are added to the exception - * message. This could be considered an information leak in some contexts, so - * the default setting is false here for optimum safety. + * Passport Client Credentials Grant + * When set to true the package will use Passports Client to check permissions + */ + + 'use_passport_client_credentials' => false, + + /* + * When set to true, the required permission names are added to exception messages. + * This could be considered an information leak in some contexts, so the default + * setting is false here for optimum safety. */ 'display_permission_in_exception' => false, /* - * When set to true, the required role names are added to the exception - * message. This could be considered an information leak in some contexts, so - * the default setting is false here for optimum safety. + * When set to true, the required role names are added to exception messages. + * This could be considered an information leak in some contexts, so the default + * setting is false here for optimum safety. */ 'display_role_in_exception' => false, /* * By default wildcard permission lookups are disabled. + * See documentation to understand supported syntax. */ 'enable_wildcard_permission' => false, + /* + * The class to use for interpreting wildcard permissions. + * If you need to modify delimiters, override the class and specify its name here. + */ + // 'permission.wildcard_permission' => Spatie\Permission\WildcardPermission::class, + + /* Cache-specific settings */ + 'cache' => [ /* diff --git a/stubs/generators/publish/config/simple-version/generator.php b/stubs/generators/publish/config/simple-version/generator.php index 4a34947e..4849c41e 100644 --- a/stubs/generators/publish/config/simple-version/generator.php +++ b/stubs/generators/publish/config/simple-version/generator.php @@ -13,7 +13,7 @@ * 2. storage * 3. S3 */ - "disk" => "s3", + "disk" => "storage", /** * Will be used if image is nullable and default value is null. @@ -69,7 +69,7 @@ "datetime" => "Y-m-d H:i:s", /** - * Limit string on index view for any column type text or longtext. + * Limit string on index view for any column type text or long text. */ "limit_text" => 100, ], diff --git a/stubs/generators/publish/models/User.php b/stubs/generators/publish/models/User.php index 8a902d3a..2ebd4553 100644 --- a/stubs/generators/publish/models/User.php +++ b/stubs/generators/publish/models/User.php @@ -2,17 +2,24 @@ namespace App\Models; -use Illuminate\Contracts\Auth\MustVerifyEmail; +// use Illuminate\Contracts\Auth\MustVerifyEmail; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Foundation\Auth\User as Authenticatable; use Illuminate\Notifications\Notifiable; -use Laravel\Sanctum\HasApiTokens; +// use Laravel\Sanctum\HasApiTokens; use Laravel\Fortify\TwoFactorAuthenticatable; -use Spatie\Permission\Traits\HasRoles; +// use Spatie\Permission\Traits\HasRoles; class User extends Authenticatable { - use HasApiTokens, HasFactory, Notifiable, TwoFactorAuthenticatable, HasRoles; + use HasFactory, Notifiable, TwoFactorAuthenticatable; + + // for laravel 11 & you want to create an api + // use HasApiTokens; + + // if you are using spatie/permission + // https://laravel.com/docs/11.x/sanctum#introduction + // use HasRoles; /** * The attributes that are mass assignable. diff --git a/stubs/generators/publish/utils/GeneratorUtils.php b/stubs/generators/publish/utils/GeneratorUtils.php index b7ec0309..ece2e3be 100644 --- a/stubs/generators/publish/utils/GeneratorUtils.php +++ b/stubs/generators/publish/utils/GeneratorUtils.php @@ -1,10 +1,11 @@ file($name) && request()->file($name)->isValid()) { - if(!$isCustomUpload){ - $file = request()->file($name); + if (!$isCustomUpload) { + $file = request()->file($name); - if (str_contains(GeneratorUtils::checkPackageVersion('intervention/image'), '2')) { - $filename = $file->hashName(); - } else { - // set image to webp - $filename = str()->random(30) . '.webp'; - } + if (str_contains(GeneratorUtils::checkPackageVersion('intervention/image'), '2')) { + $filename = $file->hashName(); + } else { + // set image to webp + $filename = str()->random(30) . '.webp'; + } - // s3 or local - switch (config('generator.image.disk', $disk)) { - case 's3': - if (str_contains(GeneratorUtils::checkPackageVersion('intervention/image-laravel'), '2')) { - // for intervention v2 - $image = \Intervention\Image\Facades\Image::make($file)->resize($width, $height, config('generator.image.crop') ? function ($constraint) { - $constraint->aspectRatio(); - $constraint->upsize(); - } : null)->encode($file->extension()); - } else { - // for intervention v3 - $imageInstance = \Intervention\Image\Laravel\Facades\Image::read($file); + // s3 or local + switch (config('generator.image.disk', $disk)) { + case 's3': + if (str_contains(GeneratorUtils::checkPackageVersion('intervention/image-laravel'), '2')) { + // for intervention v2 + $image = \Intervention\Image\Facades\Image::make($file)->resize($width, $height, config('generator.image.crop') ? function ($constraint) { + $constraint->aspectRatio(); + $constraint->upsize(); + } : null)->encode($file->extension()); + } else { + // for intervention v3 + $imageInstance = \Intervention\Image\Laravel\Facades\Image::read($file); - if (config('generator.image.crop')) { - // constraint aspect ratio - $image = $imageInstance->resizeDown($width, $height)->encode(new \Intervention\Image\Encoders\WebpEncoder(quality: 65)); - } else { - $image = $imageInstance->encode(new \Intervention\Image\Encoders\WebpEncoder(quality: 65)); - } - } + if (config('generator.image.crop')) { + // constraint aspect ratio + $image = $imageInstance->resizeDown($width, $height)->encode(new \Intervention\Image\Encoders\WebpEncoder(quality: 65)); + } else { + $image = $imageInstance->encode(new \Intervention\Image\Encoders\WebpEncoder(quality: 65)); + } + } - Storage::disk('s3')->put($path . '/' . $filename, $image); + Storage::disk('s3')->put($path . '/' . $filename, $image); - // remove old image - if ($defaultImage) $this->delete($path . $defaultImage, 's3'); - break; - default: - if (!file_exists($path)) mkdir($path, 0777, true); + // remove old image + if ($defaultImage) $this->delete($path . $defaultImage, 's3'); + break; + default: + if (!file_exists($path)) mkdir($path, 0777, true); - // for intervention v2 - if (str_contains(GeneratorUtils::checkPackageVersion('intervention/image-laravel'), '2')) { - \Intervention\Image\Facades\Image::make($file->getRealPath())->resize($width, $height, config('generator.image.crop') ? function ($constraint) { - $constraint->aspectRatio(); - $constraint->upsize(); - } : null)->save($path . $filename); - } else { - // for intervention v3 - $image = \Intervention\Image\Laravel\Facades\Image::read($file); + // for intervention v2 + if (str_contains(GeneratorUtils::checkPackageVersion('intervention/image-laravel'), '2')) { + \Intervention\Image\Facades\Image::make($file->getRealPath())->resize($width, $height, config('generator.image.crop') ? function ($constraint) { + $constraint->aspectRatio(); + $constraint->upsize(); + } : null)->save($path . $filename); + } else { + // for intervention v3 + $image = \Intervention\Image\Laravel\Facades\Image::read($file); - if (config('generator.image.crop')) { - // constraint aspect ratio - $image->resizeDown($width, $height)->toWebp()->save($path . $filename); - } else { - $image->toWebp()->save($path . $filename); - } - } + if (config('generator.image.crop')) { + // constraint aspect ratio + $image->resizeDown($width, $height)->toWebp()->save($path . $filename); + } else { + $image->toWebp()->save($path . $filename); + } + } - // remove old image - if ($defaultImage) $this->delete($path . $defaultImage); - break; - } + // remove old image + if ($defaultImage) $this->delete($path . $defaultImage); + break; + } - return $filename; - }else{ - // TODO: write your logic here - return 'something'; - } + return $filename; + } else { + // TODO: write your logic here + return 'something'; + } } return $defaultImage; diff --git a/stubs/generators/views/forms/datalist.stub b/stubs/generators/views/forms/datalist.stub index 74ebefb3..65155180 100644 --- a/stubs/generators/views/forms/datalist.stub +++ b/stubs/generators/views/forms/datalist.stub @@ -1,6 +1,6 @@
- + {{options}} From a706128d8a92a3f8811997372ab3db81238de48e Mon Sep 17 00:00:00 2001 From: Mohammad Zulfahmi Date: Wed, 20 Mar 2024 10:59:25 +0700 Subject: [PATCH 025/105] wip --- src/Commands/PublishAllFiles.php | 4 +- src/Commands/SetSidebarType.php | 6 +- src/Generators/FactoryGenerator.php | 4 +- src/Generators/GeneratorUtils.php | 56 +++++++------ .../Interfaces/GeneratorUtilsInterface.php | 5 ++ src/Generators/RequestGenerator.php | 12 +-- src/Generators/RouteGenerator.php | 4 +- src/Generators/SeederGenerator.php | 4 +- src/Generators/ViewComposerGenerator.php | 4 +- src/Generators/Views/IndexViewGenerator.php | 4 +- src/Routes/generator.php | 1 - .../publish/utils/GeneratorUtils.php | 84 +++++++++---------- .../Interfaces/GeneratorUtilsInterface.php | 5 ++ 13 files changed, 97 insertions(+), 96 deletions(-) diff --git a/src/Commands/PublishAllFiles.php b/src/Commands/PublishAllFiles.php index 54c604ab..4210c238 100644 --- a/src/Commands/PublishAllFiles.php +++ b/src/Commands/PublishAllFiles.php @@ -111,7 +111,7 @@ public function handle(): void Artisan::call('vendor:publish --tag=generator-config-simple'); Artisan::call('vendor:publish --tag=generator-view-provider'); - Artisan::call('vendor:publish --provider="Intervention\Image\ImageServiceProviderLaravelRecent"'); + Artisan::call('vendor:publish --provider="Intervention\Image\Laravel\ServiceProvider"'); Artisan::call('vendor:publish --tag=datatables'); Artisan::call('vendor:publish --tag=generator-utils'); @@ -207,7 +207,7 @@ public function runPublishAll(): void Artisan::call('vendor:publish --tag=generator-model --force'); Artisan::call('vendor:publish --tag=generator-assets --force'); Artisan::call('vendor:publish --tag=generator-utils --force'); - Artisan::call('vendor:publish --provider="Intervention\Image\ImageServiceProviderLaravelRecent"'); + Artisan::call('vendor:publish --provider="Intervention\Image\Laravel\ServiceProvider"'); Artisan::call('vendor:publish --tag=datatables --force'); $template = GeneratorUtils::getStub('route'); diff --git a/src/Commands/SetSidebarType.php b/src/Commands/SetSidebarType.php index 550f06cd..c0961fe3 100644 --- a/src/Commands/SetSidebarType.php +++ b/src/Commands/SetSidebarType.php @@ -114,14 +114,14 @@ public function handle(): void file_put_contents(resource_path('views/layouts/sidebar.blade.php'), $template); - $this->info('Success change sidebar view to fully blade code..'); + $this->info('You have successfully switched to full blade code in the sidebar view.'); break; case 'dynamic': $this->checkGeneratorVariant(); file_put_contents(resource_path('views/layouts/sidebar.blade.php'), GeneratorUtils::getStub('sidebar-dynamic')); - $this->info('The sidebar used a dynamic list from config.'); + $this->info('A dynamic list from the config(config/generator) was used in the sidebar.'); break; default: $this->error("The type must be 'static' or 'dynamic'."); @@ -135,7 +135,7 @@ public function handle(): void public function checkGeneratorVariant(): void { if (empty(config('generator.sidebars'))) { - $this->error("This command is only accessible in the full version, it appears that you are using the simple version."); + $this->error("It looks that you are using the simple version, this command is only available in the full version. Please refer to the section on available commands at https://evdigi-ina.github.io/generator-docs/features/"); die; } diff --git a/src/Generators/FactoryGenerator.php b/src/Generators/FactoryGenerator.php index 79f28a66..f5572095 100644 --- a/src/Generators/FactoryGenerator.php +++ b/src/Generators/FactoryGenerator.php @@ -16,9 +16,7 @@ public function generate(array $request): void $fields .= "// '" . $field ."' => "; $fields .= $request['requireds'][$i] == 'yes' ? "\$this->faker->" : "null"; - if($i + 1 != $totalField) { - $fields .= ",\r\n\t\t\t"; - } + if($i + 1 != $totalField) $fields .= ",\r\n\t\t\t"; } $modelPath = $path ? $path . "\\" : ""; diff --git a/src/Generators/GeneratorUtils.php b/src/Generators/GeneratorUtils.php index 6a8d6de5..7fa0f022 100644 --- a/src/Generators/GeneratorUtils.php +++ b/src/Generators/GeneratorUtils.php @@ -39,7 +39,7 @@ public static function singularPascalCase(string $string): string /** * check string ended with 'ia' or 'ium' */ - if (str_ends_with($string, 'ia') || str_ends_with($string, 'ium')) return ucfirst(str(self::fromCamelCase($string))->camel()); + if (self::checkStringEndWith($string)) return ucfirst(str(self::fromCamelCase($string))->camel()); return ucfirst(str(self::fromCamelCase($string))->singular()->camel()); } @@ -60,7 +60,7 @@ public static function pluralPascalCase(string $string): string /** * check string ended with 'ia' or 'ium' */ - if (str_ends_with($string, 'ia') || str_ends_with($string, 'ium')) return ucfirst(str(self::fromCamelCase($string))->camel()) . 's'; + if (self::checkStringEndWith($string)) return ucfirst(str(self::fromCamelCase($string))->camel()) . 's'; return ucfirst(str(self::fromCamelCase($string))->plural()->camel()); } @@ -73,7 +73,7 @@ public static function pluralSnakeCase(string $string): string /** * check string ended with 'ia' or 'ium' */ - if (str_ends_with($string, 'ia') || str_ends_with($string, 'ium')) return str(self::fromCamelCase($string))->snake()->lower() . 's'; + if (self::checkStringEndWith($string)) return str(self::fromCamelCase($string))->snake()->lower() . 's'; return str(self::fromCamelCase($string))->plural()->snake()->lower(); } @@ -86,7 +86,7 @@ public static function singularSnakeCase(string $string): string /** * check string ended with 'ia' or 'ium' */ - if (str_ends_with($string, 'ia') || str_ends_with($string, 'ium')) return str(self::fromCamelCase($string))->snake()->lower(); + if (self::checkStringEndWith($string)) return str(self::fromCamelCase($string))->snake()->lower(); return str(self::fromCamelCase($string))->singular()->snake()->lower(); } @@ -99,7 +99,7 @@ public static function pluralCamelCase(string $string): string /** * check string ended with 'ia' or 'ium' */ - if (str_ends_with($string, 'ia') || str_ends_with($string, 'ium')) return str(self::fromCamelCase($string))->camel() . 's'; + if (self::checkStringEndWith($string)) return str(self::fromCamelCase($string))->camel() . 's'; return str(self::fromCamelCase($string))->plural()->camel(); } @@ -112,7 +112,7 @@ public static function singularCamelCase(string $string): string /** * check string ended with 'ia' or 'ium' */ - if (str_ends_with($string, 'ia') || str_ends_with($string, 'ium')) return str(self::fromCamelCase($string))->camel(); + if (self::checkStringEndWith($string)) return str(self::fromCamelCase($string))->camel(); return str(self::fromCamelCase($string))->singular()->camel(); } @@ -125,7 +125,7 @@ public static function pluralKebabCase(string $string): string /** * check string ended with 'ia' or 'ium' */ - if (str_ends_with($string, 'ia') || str_ends_with($string, 'ium')) return str(preg_replace('/[^A-Za-z0-9() -]/', ' ', self::fromCamelCase($string)))->kebab()->lower() . 's'; + if (self::checkStringEndWith($string)) return str(preg_replace('/[^A-Za-z0-9() -]/', ' ', self::fromCamelCase($string)))->kebab()->lower() . 's'; return str(preg_replace('/[^A-Za-z0-9() -]/', ' ', self::fromCamelCase($string)))->plural()->kebab()->lower(); } @@ -146,7 +146,7 @@ public static function singularKebabCase(string $string): string /** * check string ended with 'ia' or 'ium' */ - if (str_ends_with($string, 'ia') || str_ends_with($string, 'ium')) return str(preg_replace('/[^A-Za-z0-9() -]/', ' ', self::fromCamelCase($string)))->kebab()->lower(); + if (self::checkStringEndWith($string)) return str(preg_replace('/[^A-Za-z0-9() -]/', ' ', self::fromCamelCase($string)))->kebab()->lower(); return str(preg_replace('/[^A-Za-z0-9() -]/', ' ', self::fromCamelCase($string)))->singular()->kebab()->lower(); } @@ -159,7 +159,7 @@ public static function cleanSingularLowerCase(string $string): string /** * check string ended with 'ia' or 'ium' */ - if (str_ends_with($string, 'ia') || str_ends_with($string, 'ium')) return str(preg_replace('/[^A-Za-z0-9() -]/', ' ', self::fromCamelCase($string)))->lower(); + if (self::checkStringEndWith($string)) return str(preg_replace('/[^A-Za-z0-9() -]/', ' ', self::fromCamelCase($string)))->lower(); return str(preg_replace('/[^A-Za-z0-9() -]/', ' ', self::fromCamelCase($string)))->singular()->lower(); } @@ -180,7 +180,7 @@ public static function cleanPluralUcWords(string $string): string /** * check string ended with 'ia' or 'ium' */ - if (str_ends_with($string, 'ia') || str_ends_with($string, 'ium')) return ucwords(str(preg_replace('/[^A-Za-z0-9() -]/', ' ', self::fromCamelCase($string)))->lower()) . 's'; + if (self::checkStringEndWith($string)) return ucwords(str(preg_replace('/[^A-Za-z0-9() -]/', ' ', self::fromCamelCase($string)))->lower()) . 's'; return ucwords(str(preg_replace('/[^A-Za-z0-9() -]/', ' ', self::fromCamelCase($string)))->plural()->lower()); } @@ -193,7 +193,7 @@ public static function cleanSingularUcWords(string $string): string /** * check string ended with 'ia' or 'ium' */ - if (str_ends_with($string, 'ia') || str_ends_with($string, 'ium')) return ucwords(str(preg_replace('/[^A-Za-z0-9() -]/', ' ', self::fromCamelCase($string)))->lower()); + if (self::checkStringEndWith($string)) return ucwords(str(preg_replace('/[^A-Za-z0-9() -]/', ' ', self::fromCamelCase($string)))->lower()); return ucwords(str(preg_replace('/[^A-Za-z0-9() -]/', ' ', self::fromCamelCase($string)))->singular()->lower()); } @@ -214,11 +214,19 @@ public static function cleanPluralLowerCase(string $string): string /** * check string ended with 'ia' or 'ium' */ - if (str_ends_with($string, 'ia') || str_ends_with($string, 'ium')) return str(preg_replace('/[^A-Za-z0-9() -]/', ' ', self::fromCamelCase($string)))->lower() . 's'; + if (self::checkStringEndWith($string)) return str(preg_replace('/[^A-Za-z0-9() -]/', ' ', self::fromCamelCase($string)))->lower() . 's'; return str(preg_replace('/[^A-Za-z0-9() -]/', ' ', self::fromCamelCase($string)))->plural()->lower(); } + /** + * Check if the given string ends with 'ia' or 'ium'. + */ + public static function checkStringEndWith(string $string): bool + { + return str_ends_with($string, 'ia') || str_ends_with($string, 'ium'); + } + /** * Get 1 column after id on the table. */ @@ -320,7 +328,7 @@ public static function setDefaultImage(null|string $default, string $field, stri * * if (!$generator->image || $generator->image == $defaultImage = 'https://raw.githubusercontent.com/laravel/art/master/logo-lockup/5%20SVG/2%20CMYK/1%20Full%20Color/laravel-logolockup-cmyk-red.svg') return $defaultImage; */ - 'index_code' => "if (!$". self::singularCamelCase($model) ."->" . str()->snake($field) . " || $". self::singularCamelCase($model) ."->" . str()->snake($field) . " == \$defaultImage = '" . $default . "') return \$defaultImage;", + 'index_code' => "if (!$" . self::singularCamelCase($model) . "->" . str()->snake($field) . " || $" . self::singularCamelCase($model) . "->" . str()->snake($field) . " == \$defaultImage = '" . $default . "') return \$defaultImage;", /** * Generated code: * !$book->cover || $book->cover == 'https://via.placeholder.com/350?text=No+Image+Avaiable'" @@ -337,7 +345,7 @@ public static function setDefaultImage(null|string $default, string $field, stri * * if (!$generator->image == null) return 'https://via.placeholder.com/350?text=No+Image+Avaiable'; */ - 'index_code' => "if (!\$". self::singularCamelCase($model) ."->" . str()->snake($field) . ") return '" . config('generator.image.default') . "';", + 'index_code' => "if (!\$" . self::singularCamelCase($model) . "->" . str()->snake($field) . ") return '" . config('generator.image.default') . "';", /** * Generated code: * @@ -349,7 +357,7 @@ public static function setDefaultImage(null|string $default, string $field, stri return [ 'image' => 'https://via.placeholder.com/350?text=No+Image+Avaiable', - 'index_code' => "if (!\$". self::singularCamelCase($model) ."->" . str()->snake($field) . ") return 'https://via.placeholder.com/350?text=No+Image+Avaiable';", + 'index_code' => "if (!\$" . self::singularCamelCase($model) . "->" . str()->snake($field) . ") return 'https://via.placeholder.com/350?text=No+Image+Avaiable';", 'form_code' => "!$" . self::singularCamelCase($model) . "->" . str()->snake($field), ]; } @@ -413,7 +421,7 @@ public static function isGenerateApi(): bool */ public static function checkPackage(string $name): bool { - if(self::getComposerPackage($name) == '{') return false; + if (self::getComposerPackage($name) == '{') return false; return true; } @@ -426,10 +434,10 @@ public static function checkPackageVersion(string $name, bool $strict = false): { $str = self::getComposerPackage($name); - if(str_contains($str, '{')){ + if (str_contains($str, '{')) { $message = 'The package ' . $name . ' is not installed.'; - if($strict) throw new \Exception($message); + if ($strict) throw new \Exception($message); return $message; } @@ -454,13 +462,13 @@ public static function setDiskCodeForController(string $name): string { return match (config('generator.image.disk')) { // '/images/'; - 's3' => "'/". self::pluralKebabCase($name) ."/'", + 's3' => "'/" . self::pluralKebabCase($name) . "/'", // 'public_path('uploads/images/'); - 'public' => "public_path('uploads/". self::pluralKebabCase($name) ."/')", + 'public' => "public_path('uploads/" . self::pluralKebabCase($name) . "/')", - // 'storage_path('app/public/uploads/images/'); - default => "storage_path('app/public/uploads/". self::pluralKebabCase($name) ."/')", + // 'storage_path('app/public/uploads/images/'); + default => "storage_path('app/public/uploads/" . self::pluralKebabCase($name) . "/')", }; } @@ -471,12 +479,12 @@ public static function setDiskCodeForCastImage(string $model, string $field): st { return match (config('generator.image.disk')) { // \Illuminate\Support\Facades\Storage::disk('s3')->url('images/' . $generator->image); - 's3' => "\Illuminate\Support\Facades\Storage::disk('s3')->url(\$this->". self::singularCamelCase($field) ."Path . $" . self::singularCamelCase($model) . "->" . str($field)->snake() . ")", + 's3' => "\Illuminate\Support\Facades\Storage::disk('s3')->url(\$this->" . self::singularCamelCase($field) . "Path . $" . self::singularCamelCase($model) . "->" . str($field)->snake() . ")", //asset('/uploads/photos/' . $generator->image); 'public' => "asset('/uploads/" . self::pluralKebabCase($field) . "/' . $" . self::singularCamelCase($model) . "->" . str($field)->snake() . ")", - //asset('storage/uploads/images/' . $generator->image) + //asset('storage/uploads/images/' . $generator->image) default => "asset('storage/uploads/" . self::pluralKebabCase($field) . "/' . $" . self::singularCamelCase($model) . "->" . str($field)->snake() . ")", }; } diff --git a/src/Generators/Interfaces/GeneratorUtilsInterface.php b/src/Generators/Interfaces/GeneratorUtilsInterface.php index 49ad2a24..2eb93de5 100644 --- a/src/Generators/Interfaces/GeneratorUtilsInterface.php +++ b/src/Generators/Interfaces/GeneratorUtilsInterface.php @@ -99,6 +99,11 @@ public static function cleanUcWords(string $string): string; */ public static function cleanPluralLowerCase(string $string): string; + /** + * Check if the given string ends with 'ia' or 'ium'. + */ + public static function checkStringEndWith(string $string): bool; + /** * Get 1 column after id on the table. */ diff --git a/src/Generators/RequestGenerator.php b/src/Generators/RequestGenerator.php index 057ba18c..c2541ea5 100644 --- a/src/Generators/RequestGenerator.php +++ b/src/Generators/RequestGenerator.php @@ -76,13 +76,9 @@ public function generate(array $request): void if ($request['input_types'][$i] == 'file' && $request['file_types'][$i] == 'image') { $maxSize = 1024; - if (config('generator.image.size_max')) { - $maxSize = config('generator.image.size_max'); - } + if (config('generator.image.size_max')) $maxSize = config('generator.image.size_max'); - if ($request['files_sizes'][$i]) { - $maxSize = $request['files_sizes'][$i]; - } + if ($request['files_sizes'][$i]) $maxSize = $request['files_sizes'][$i]; /** * result: @@ -199,9 +195,7 @@ public function generate(array $request): void break; } - if ($i + 1 != $totalFields) { - $validations .= "\n\t\t\t"; - } + if ($i + 1 != $totalFields) $validations .= "\n\t\t\t"; } // end of foreach diff --git a/src/Generators/RouteGenerator.php b/src/Generators/RouteGenerator.php index 44f49a59..7d29a16e 100644 --- a/src/Generators/RouteGenerator.php +++ b/src/Generators/RouteGenerator.php @@ -19,9 +19,7 @@ public function generate(array $request): void $middleware = "->middleware('auth')"; - if (isset($request['is_simple_generator']) || GeneratorUtils::isGenerateApi()) { - $middleware = ""; - } + if (isset($request['is_simple_generator']) || GeneratorUtils::isGenerateApi()) $middleware = ""; if (GeneratorUtils::isGenerateApi()) { $routeFacade = "Route::apiResource('"; diff --git a/src/Generators/SeederGenerator.php b/src/Generators/SeederGenerator.php index ec79c515..b0892928 100644 --- a/src/Generators/SeederGenerator.php +++ b/src/Generators/SeederGenerator.php @@ -18,9 +18,7 @@ public function generate(array $request): void $fields .= "'" . $field ."' => "; $fields .= $request['requireds'][$i] == 'yes' ? "''" : "null"; - if($i + 1 != $totalField) { - $fields .= ",\r\n\t\t\t"; - } + if($i + 1 != $totalField) $fields .= ",\r\n\t\t\t"; } $modelPath = $path ? $path . "\\" : ""; diff --git a/src/Generators/ViewComposerGenerator.php b/src/Generators/ViewComposerGenerator.php index a7c67a90..438630ee 100644 --- a/src/Generators/ViewComposerGenerator.php +++ b/src/Generators/ViewComposerGenerator.php @@ -38,9 +38,7 @@ public function generate(array $request): void $fieldsSelect = "'id'"; } - if ($i > 1) { - $template .= "\t\t"; - } + if ($i > 1) $template .= "\t\t"; $template .= str_replace( [ diff --git a/src/Generators/Views/IndexViewGenerator.php b/src/Generators/Views/IndexViewGenerator.php index c329ed3e..4a832e8d 100644 --- a/src/Generators/Views/IndexViewGenerator.php +++ b/src/Generators/Views/IndexViewGenerator.php @@ -50,9 +50,7 @@ public function generate(array $request): void */ $imgStyle = ''; - if(isset($request['is_simple_generator'])){ - $imgStyle = 'class="rounded" width="50" height="40" style="object-fit: cover"'; - } + if(isset($request['is_simple_generator'])) $imgStyle = 'class="rounded" width="50" height="40" style="object-fit: cover"'; $tdColumns .= "{ data: '" . str()->snake($field) . "', diff --git a/src/Routes/generator.php b/src/Routes/generator.php index c3219027..3ebd79d4 100644 --- a/src/Routes/generator.php +++ b/src/Routes/generator.php @@ -1,6 +1,5 @@ camel()); + if (self::checkStringEndWith($string)) return ucfirst(str(self::fromCamelCase($string))->camel()); return ucfirst(str(self::fromCamelCase($string))->singular()->camel()); } @@ -61,7 +60,7 @@ public static function pluralPascalCase(string $string): string /** * check string ended with 'ia' or 'ium' */ - if (str_ends_with($string, 'ia') || str_ends_with($string, 'ium')) return ucfirst(str(self::fromCamelCase($string))->camel()) . 's'; + if (self::checkStringEndWith($string)) return ucfirst(str(self::fromCamelCase($string))->camel()) . 's'; return ucfirst(str(self::fromCamelCase($string))->plural()->camel()); } @@ -74,7 +73,7 @@ public static function pluralSnakeCase(string $string): string /** * check string ended with 'ia' or 'ium' */ - if (str_ends_with($string, 'ia') || str_ends_with($string, 'ium')) return str(self::fromCamelCase($string))->snake()->lower() . 's'; + if (self::checkStringEndWith($string)) return str(self::fromCamelCase($string))->snake()->lower() . 's'; return str(self::fromCamelCase($string))->plural()->snake()->lower(); } @@ -87,7 +86,7 @@ public static function singularSnakeCase(string $string): string /** * check string ended with 'ia' or 'ium' */ - if (str_ends_with($string, 'ia') || str_ends_with($string, 'ium')) return str(self::fromCamelCase($string))->snake()->lower(); + if (self::checkStringEndWith($string)) return str(self::fromCamelCase($string))->snake()->lower(); return str(self::fromCamelCase($string))->singular()->snake()->lower(); } @@ -100,7 +99,7 @@ public static function pluralCamelCase(string $string): string /** * check string ended with 'ia' or 'ium' */ - if (str_ends_with($string, 'ia') || str_ends_with($string, 'ium')) return str(self::fromCamelCase($string))->camel() . 's'; + if (self::checkStringEndWith($string)) return str(self::fromCamelCase($string))->camel() . 's'; return str(self::fromCamelCase($string))->plural()->camel(); } @@ -113,7 +112,7 @@ public static function singularCamelCase(string $string): string /** * check string ended with 'ia' or 'ium' */ - if (str_ends_with($string, 'ia') || str_ends_with($string, 'ium')) return str(self::fromCamelCase($string))->camel(); + if (self::checkStringEndWith($string)) return str(self::fromCamelCase($string))->camel(); return str(self::fromCamelCase($string))->singular()->camel(); } @@ -126,7 +125,7 @@ public static function pluralKebabCase(string $string): string /** * check string ended with 'ia' or 'ium' */ - if (str_ends_with($string, 'ia') || str_ends_with($string, 'ium')) return str(preg_replace('/[^A-Za-z0-9() -]/', ' ', self::fromCamelCase($string)))->kebab()->lower() . 's'; + if (self::checkStringEndWith($string)) return str(preg_replace('/[^A-Za-z0-9() -]/', ' ', self::fromCamelCase($string)))->kebab()->lower() . 's'; return str(preg_replace('/[^A-Za-z0-9() -]/', ' ', self::fromCamelCase($string)))->plural()->kebab()->lower(); } @@ -147,7 +146,7 @@ public static function singularKebabCase(string $string): string /** * check string ended with 'ia' or 'ium' */ - if (str_ends_with($string, 'ia') || str_ends_with($string, 'ium')) return str(preg_replace('/[^A-Za-z0-9() -]/', ' ', self::fromCamelCase($string)))->kebab()->lower(); + if (self::checkStringEndWith($string)) return str(preg_replace('/[^A-Za-z0-9() -]/', ' ', self::fromCamelCase($string)))->kebab()->lower(); return str(preg_replace('/[^A-Za-z0-9() -]/', ' ', self::fromCamelCase($string)))->singular()->kebab()->lower(); } @@ -160,7 +159,7 @@ public static function cleanSingularLowerCase(string $string): string /** * check string ended with 'ia' or 'ium' */ - if (str_ends_with($string, 'ia') || str_ends_with($string, 'ium')) return str(preg_replace('/[^A-Za-z0-9() -]/', ' ', self::fromCamelCase($string)))->lower(); + if (self::checkStringEndWith($string)) return str(preg_replace('/[^A-Za-z0-9() -]/', ' ', self::fromCamelCase($string)))->lower(); return str(preg_replace('/[^A-Za-z0-9() -]/', ' ', self::fromCamelCase($string)))->singular()->lower(); } @@ -181,7 +180,7 @@ public static function cleanPluralUcWords(string $string): string /** * check string ended with 'ia' or 'ium' */ - if (str_ends_with($string, 'ia') || str_ends_with($string, 'ium')) return ucwords(str(preg_replace('/[^A-Za-z0-9() -]/', ' ', self::fromCamelCase($string)))->lower()) . 's'; + if (self::checkStringEndWith($string)) return ucwords(str(preg_replace('/[^A-Za-z0-9() -]/', ' ', self::fromCamelCase($string)))->lower()) . 's'; return ucwords(str(preg_replace('/[^A-Za-z0-9() -]/', ' ', self::fromCamelCase($string)))->plural()->lower()); } @@ -194,7 +193,7 @@ public static function cleanSingularUcWords(string $string): string /** * check string ended with 'ia' or 'ium' */ - if (str_ends_with($string, 'ia') || str_ends_with($string, 'ium')) return ucwords(str(preg_replace('/[^A-Za-z0-9() -]/', ' ', self::fromCamelCase($string)))->lower()); + if (self::checkStringEndWith($string)) return ucwords(str(preg_replace('/[^A-Za-z0-9() -]/', ' ', self::fromCamelCase($string)))->lower()); return ucwords(str(preg_replace('/[^A-Za-z0-9() -]/', ' ', self::fromCamelCase($string)))->singular()->lower()); } @@ -215,11 +214,19 @@ public static function cleanPluralLowerCase(string $string): string /** * check string ended with 'ia' or 'ium' */ - if (str_ends_with($string, 'ia') || str_ends_with($string, 'ium')) return str(preg_replace('/[^A-Za-z0-9() -]/', ' ', self::fromCamelCase($string)))->lower() . 's'; + if (self::checkStringEndWith($string)) return str(preg_replace('/[^A-Za-z0-9() -]/', ' ', self::fromCamelCase($string)))->lower() . 's'; return str(preg_replace('/[^A-Za-z0-9() -]/', ' ', self::fromCamelCase($string)))->plural()->lower(); } + /** + * Check if the given string ends with 'ia' or 'ium'. + */ + public static function checkStringEndWith(string $string): bool + { + return str_ends_with($string, 'ia') || str_ends_with($string, 'ium'); + } + /** * Get 1 column after id on the table. */ @@ -319,17 +326,14 @@ public static function setDefaultImage(null|string $default, string $field, stri /** * Generated code: * - * if ($generator->image == null || $generator->image == $defaultImage = 'https://raw.githubusercontent.com/laravel/art/master/logo-lockup/5%20SVG/2%20CMYK/1%20Full%20Color/laravel-logolockup-cmyk-red.svg') { - * return $defaultImage; + * if (!$generator->image || $generator->image == $defaultImage = 'https://raw.githubusercontent.com/laravel/art/master/logo-lockup/5%20SVG/2%20CMYK/1%20Full%20Color/laravel-logolockup-cmyk-red.svg') return $defaultImage; */ - 'index_code' => "if (\$". self::singularCamelCase($model) ."->" . str()->snake($field) . " == null || \$". self::singularCamelCase($model) .">" . str()->snake($field) . " == \$defaultImage = '" . $default . "') { - return \$defaultImage; - }", + 'index_code' => "if (!$" . self::singularCamelCase($model) . "->" . str()->snake($field) . " || $" . self::singularCamelCase($model) . "->" . str()->snake($field) . " == \$defaultImage = '" . $default . "') return \$defaultImage;", /** * Generated code: - * $book->cover == null || $book->cover == 'https://via.placeholder.com/350?text=No+Image+Avaiable'" + * !$book->cover || $book->cover == 'https://via.placeholder.com/350?text=No+Image+Avaiable'" */ - 'form_code' => "$" . self::singularCamelCase($model) . "->" . str()->snake($field) . " == null || $" . self::singularCamelCase($model) . "->" . str()->snake($field) . " == '" . $default . "'", + 'form_code' => "!$" . self::singularCamelCase($model) . "->" . str()->snake($field) . " || $" . self::singularCamelCase($model) . "->" . str()->snake($field) . " == '" . $default . "'", ]; } @@ -339,27 +343,22 @@ public static function setDefaultImage(null|string $default, string $field, stri /** * Generated code: * - * if ($generator->image == null) { - * return 'https://via.placeholder.com/350?text=No+Image+Avaiable'; + * if (!$generator->image == null) return 'https://via.placeholder.com/350?text=No+Image+Avaiable'; */ - 'index_code' => "if (\$". self::singularCamelCase($model) ."->" . str()->snake($field) . " == null) { - return '" . config('generator.image.default') . "'; - }", + 'index_code' => "if (!\$" . self::singularCamelCase($model) . "->" . str()->snake($field) . ") return '" . config('generator.image.default') . "';", /** * Generated code: * - * $book->photo == null + * !$book->photo */ - 'form_code' => "$" . self::singularCamelCase($model) . "->" . str()->snake($field) . " == null", + 'form_code' => "!$" . self::singularCamelCase($model) . "->" . str()->snake($field), ]; } return [ 'image' => 'https://via.placeholder.com/350?text=No+Image+Avaiable', - 'index_code' => "if (\$". self::singularCamelCase($model) ."->" . str()->snake($field) . " == null) { - return 'https://via.placeholder.com/350?text=No+Image+Avaiable'; - }", - 'form_code' => "$" . self::singularCamelCase($model) . "->" . str()->snake($field) . " == null", + 'index_code' => "if (!\$" . self::singularCamelCase($model) . "->" . str()->snake($field) . ") return 'https://via.placeholder.com/350?text=No+Image+Avaiable';", + 'form_code' => "!$" . self::singularCamelCase($model) . "->" . str()->snake($field), ]; } @@ -422,7 +421,7 @@ public static function isGenerateApi(): bool */ public static function checkPackage(string $name): bool { - if(self::getComposerPackage($name) == '{') return false; + if (self::getComposerPackage($name) == '{') return false; return true; } @@ -435,10 +434,10 @@ public static function checkPackageVersion(string $name, bool $strict = false): { $str = self::getComposerPackage($name); - if(str_contains($str, '{')){ - $message = 'The package '.$name.' is not installed.'; + if (str_contains($str, '{')) { + $message = 'The package ' . $name . ' is not installed.'; - if($strict) throw new \Exception($message); + if ($strict) throw new \Exception($message); return $message; } @@ -453,7 +452,7 @@ public static function getComposerPackage(string $name): string { $composer = file_get_contents(base_path('composer.json')); - return str($composer)->after('"'.$name.'": "')->before('"'); + return str($composer)->after('"' . $name . '": "')->before('"'); } /** @@ -463,13 +462,13 @@ public static function setDiskCodeForController(string $name): string { return match (config('generator.image.disk')) { // '/images/'; - 's3' => "'/". self::pluralKebabCase($name) ."/'", + 's3' => "'/" . self::pluralKebabCase($name) . "/'", // 'public_path('uploads/images/'); - 'public' => "public_path('uploads/". self::pluralKebabCase($name) ."/')", + 'public' => "public_path('uploads/" . self::pluralKebabCase($name) . "/')", - // 'storage_path('app/public/uploads/images/'); - default => "storage_path('app/public/uploads/". self::pluralKebabCase($name) ."/')", + // 'storage_path('app/public/uploads/images/'); + default => "storage_path('app/public/uploads/" . self::pluralKebabCase($name) . "/')", }; } @@ -480,13 +479,14 @@ public static function setDiskCodeForCastImage(string $model, string $field): st { return match (config('generator.image.disk')) { // \Illuminate\Support\Facades\Storage::disk('s3')->url('images/' . $generator->image); - 's3' => "\Illuminate\Support\Facades\Storage::disk('s3')->url(\$this->". self::singularCamelCase($field) ."Path . $" . self::singularCamelCase($model) . "->" . str($field)->snake() . ")", + 's3' => "\Illuminate\Support\Facades\Storage::disk('s3')->url(\$this->" . self::singularCamelCase($field) . "Path . $" . self::singularCamelCase($model) . "->" . str($field)->snake() . ")", //asset('/uploads/photos/' . $generator->image); 'public' => "asset('/uploads/" . self::pluralKebabCase($field) . "/' . $" . self::singularCamelCase($model) . "->" . str($field)->snake() . ")", - //asset('storage/uploads/images/' . $generator->image) + //asset('storage/uploads/images/' . $generator->image) default => "asset('storage/uploads/" . self::pluralKebabCase($field) . "/' . $" . self::singularCamelCase($model) . "->" . str($field)->snake() . ")", }; } } + diff --git a/stubs/generators/publish/utils/Interfaces/GeneratorUtilsInterface.php b/stubs/generators/publish/utils/Interfaces/GeneratorUtilsInterface.php index bb768a8a..4950518f 100644 --- a/stubs/generators/publish/utils/Interfaces/GeneratorUtilsInterface.php +++ b/stubs/generators/publish/utils/Interfaces/GeneratorUtilsInterface.php @@ -99,6 +99,11 @@ public static function cleanUcWords(string $string): string; */ public static function cleanPluralLowerCase(string $string): string; + /** + * Check if the given string ends with 'ia' or 'ium'. + */ + public static function checkStringEndWith(string $string): bool; + /** * Get 1 column after id on the table. */ From 3baf9c04dcc3c67866ed23a10ed9cd6c526b52cf Mon Sep 17 00:00:00 2001 From: Mohammad Zulfahmi Date: Wed, 20 Mar 2024 11:39:52 +0700 Subject: [PATCH 026/105] add Orchestra\Testbench --- .phpunit.cache/test-results | 1 + composer.json | 31 +++++- phpunit.xml | 27 +++--- phpunit.xml.bak | 21 ++++ testbench.yaml | 22 +++++ tests/BaseTestCase.php | 8 -- tests/GeneratorUtilsTest.php | 95 ++++++++++--------- tests/TestCase.php | 57 +++++++++++ workbench/app/Models/.gitkeep | 0 .../Providers/WorkbenchServiceProvider.php | 24 +++++ workbench/bootstrap/.gitkeep | 0 workbench/database/factories/.gitkeep | 0 workbench/database/migrations/.gitkeep | 0 workbench/database/seeders/.gitkeep | 0 workbench/database/seeders/DatabaseSeeder.php | 17 ++++ workbench/resources/views/.gitkeep | 0 workbench/routes/.gitkeep | 0 workbench/routes/console.php | 8 ++ workbench/routes/web.php | 7 ++ 19 files changed, 245 insertions(+), 73 deletions(-) create mode 100644 .phpunit.cache/test-results create mode 100644 phpunit.xml.bak create mode 100644 testbench.yaml delete mode 100644 tests/BaseTestCase.php create mode 100644 tests/TestCase.php create mode 100644 workbench/app/Models/.gitkeep create mode 100644 workbench/app/Providers/WorkbenchServiceProvider.php create mode 100644 workbench/bootstrap/.gitkeep create mode 100644 workbench/database/factories/.gitkeep create mode 100644 workbench/database/migrations/.gitkeep create mode 100644 workbench/database/seeders/.gitkeep create mode 100644 workbench/database/seeders/DatabaseSeeder.php create mode 100644 workbench/resources/views/.gitkeep create mode 100644 workbench/routes/.gitkeep create mode 100644 workbench/routes/console.php create mode 100644 workbench/routes/web.php diff --git a/.phpunit.cache/test-results b/.phpunit.cache/test-results new file mode 100644 index 00000000..4bb1b742 --- /dev/null +++ b/.phpunit.cache/test-results @@ -0,0 +1 @@ +{"version":1,"defects":{"Tests\\GeneratorUtilsTest::it_has_get_template_method":8,"Tests\\GeneratorUtilsTest::it_has_check_folder_method":8,"Tests\\GeneratorUtilsTest::it_has_singular_pascal_case_method":8,"Tests\\GeneratorUtilsTest::it_has_plural_pascal_case_method":8,"Tests\\GeneratorUtilsTest::it_has_plural_snake_case_method":8,"Tests\\GeneratorUtilsTest::it_has_singular_snake_case_method":8,"Tests\\GeneratorUtilsTest::it_has_plural_camel_case_method":8,"Tests\\GeneratorUtilsTest::it_has_kebab_case_method":8,"Tests\\GeneratorUtilsTest::it_has_plural_kebab_case_method":8,"Tests\\GeneratorUtilsTest::it_has_singular_kebab_case_method":8,"Tests\\GeneratorUtilsTest::it_has_singular_camel_case_method":8,"Tests\\GeneratorUtilsTest::it_has_clean_lower_case_method":8,"Tests\\GeneratorUtilsTest::it_has_clean_singular_uc_words_method":8,"Tests\\GeneratorUtilsTest::it_has_clean_uc_words_method":8,"Tests\\GeneratorUtilsTest::it_has_clean_plural_lower_case_method":8,"Tests\\GeneratorUtilsTest::it_has_get_column_after_id_method":8,"Tests\\GeneratorUtilsTest::it_has_select_column_after_id_and_id_itself_method":8,"Tests\\GeneratorUtilsTest::it_has_clean_singular_sower_case_method":8,"Tests\\GeneratorUtilsTest::it_has_get_model_location_method":8,"Tests\\GeneratorUtilsTest::it_has_from_camel_case_method":8,"Tests\\GeneratorUtilsTest::it_has_set_model_name_method":8,"Tests\\GeneratorUtilsTest::it_has_set_default_image_method":8,"Tests\\GeneratorUtilsTest::it_has_convert_array_sidebar_to_string_method":8},"times":{"Tests\\GeneratorUtilsTest::it_has_get_template_method":0.001,"Tests\\GeneratorUtilsTest::it_has_check_folder_method":0,"Tests\\GeneratorUtilsTest::it_has_singular_pascal_case_method":0,"Tests\\GeneratorUtilsTest::it_has_plural_pascal_case_method":0,"Tests\\GeneratorUtilsTest::it_has_plural_snake_case_method":0,"Tests\\GeneratorUtilsTest::it_has_singular_snake_case_method":0,"Tests\\GeneratorUtilsTest::it_has_plural_camel_case_method":0,"Tests\\GeneratorUtilsTest::it_has_kebab_case_method":0,"Tests\\GeneratorUtilsTest::it_has_plural_kebab_case_method":0,"Tests\\GeneratorUtilsTest::it_has_singular_kebab_case_method":0,"Tests\\GeneratorUtilsTest::it_has_singular_camel_case_method":0,"Tests\\GeneratorUtilsTest::it_has_clean_lower_case_method":0,"Tests\\GeneratorUtilsTest::it_has_clean_singular_uc_words_method":0,"Tests\\GeneratorUtilsTest::it_has_clean_uc_words_method":0,"Tests\\GeneratorUtilsTest::it_has_clean_plural_lower_case_method":0,"Tests\\GeneratorUtilsTest::it_has_get_column_after_id_method":0,"Tests\\GeneratorUtilsTest::it_has_select_column_after_id_and_id_itself_method":0,"Tests\\GeneratorUtilsTest::it_has_clean_singular_sower_case_method":0,"Tests\\GeneratorUtilsTest::it_has_get_model_location_method":0,"Tests\\GeneratorUtilsTest::it_has_from_camel_case_method":0,"Tests\\GeneratorUtilsTest::it_has_set_model_name_method":0,"Tests\\GeneratorUtilsTest::it_has_set_default_image_method":0,"Tests\\GeneratorUtilsTest::it_has_convert_array_sidebar_to_string_method":0,"Tests\\GeneratorUtilsTest::it_has_generator_utils_test_class":0.024,"Tests\\TestCase::it_has_generator_utils_test_class":0.001}} \ No newline at end of file diff --git a/composer.json b/composer.json index 7fa8487e..2008baaf 100644 --- a/composer.json +++ b/composer.json @@ -31,7 +31,7 @@ "yajra/laravel-datatables-oracle": "^11.0" }, "require-dev": { - "orchestra/testbench": "9.0" + "orchestra/testbench": "^9.0" }, "config": { "optimize-autoloader": true, @@ -49,5 +49,32 @@ "DataTables": "Yajra\\DataTables\\Facades\\DataTables" } } + }, + "autoload-dev": { + "psr-4": { + "Workbench\\App\\": "workbench/app/", + "Workbench\\Database\\Factories\\": "workbench/database/factories/", + "Workbench\\Database\\Seeders\\": "workbench/database/seeders/" + } + }, + "scripts": { + "post-autoload-dump": [ + "@clear", + "@prepare" + ], + "clear": "@php vendor/bin/testbench package:purge-skeleton --ansi", + "prepare": "@php vendor/bin/testbench package:discover --ansi", + "build": "@php vendor/bin/testbench workbench:build --ansi", + "serve": [ + "Composer\\Config::disableProcessTimeout", + "@build", + "@php vendor/bin/testbench serve" + ], + "lint": [ + "@php vendor/bin/phpstan analyse" + ], + "test": [ + "@php vendor/bin/phpunit" + ] } -} +} \ No newline at end of file diff --git a/phpunit.xml b/phpunit.xml index 60abb45b..12193912 100644 --- a/phpunit.xml +++ b/phpunit.xml @@ -1,17 +1,12 @@ - - - - ./tests/ - - - \ No newline at end of file + + + + ./tests/ + + + + + + + diff --git a/phpunit.xml.bak b/phpunit.xml.bak new file mode 100644 index 00000000..c508309a --- /dev/null +++ b/phpunit.xml.bak @@ -0,0 +1,21 @@ + + + + + ./tests/ + + + + + + + diff --git a/testbench.yaml b/testbench.yaml new file mode 100644 index 00000000..f056e1e7 --- /dev/null +++ b/testbench.yaml @@ -0,0 +1,22 @@ +providers: + - Workbench\App\Providers\WorkbenchServiceProvider + +migrations: + - workbench/database/migrations + +seeders: + - Workbench\Database\Seeders\DatabaseSeeder + +workbench: + start: '/' + install: true + health: false + discovers: + web: true + api: false + commands: false + components: false + views: false + build: [] + assets: [] + sync: [] diff --git a/tests/BaseTestCase.php b/tests/BaseTestCase.php deleted file mode 100644 index 226f323f..00000000 --- a/tests/BaseTestCase.php +++ /dev/null @@ -1,8 +0,0 @@ -assertTrue(method_exists(GeneratorUtils::class, 'getStub')); } - /** @test */ - public function it_has_check_folder_method() + #[Test] + public function it_has_check_folder_method(): void { $this->assertTrue(method_exists(GeneratorUtils::class, 'checkFolder')); } - /** @test */ - public function it_has_singular_pascal_case_method() + #[Test] + public function it_has_singular_pascal_case_method(): void { $this->assertTrue(method_exists(GeneratorUtils::class, 'singularPascalCase')); } - /** @test */ - public function it_has_plural_pascal_case_method() + #[Test] + public function it_has_plural_pascal_case_method(): void { $this->assertTrue(method_exists(GeneratorUtils::class, 'pluralPascalCase')); } - /** @test */ - public function it_has_plural_snake_case_method() + #[Test] + public function it_has_plural_snake_case_method(): void { $this->assertTrue(method_exists(GeneratorUtils::class, 'pluralSnakeCase')); } - /** @test */ - public function it_has_singular_snake_case_method() + #[Test] + public function it_has_singular_snake_case_method(): void { $this->assertTrue(method_exists(GeneratorUtils::class, 'singularSnakeCase')); } - /** @test */ - public function it_has_plural_camel_case_method() + #[Test] + public function it_has_plural_camel_case_method(): void { $this->assertTrue(method_exists(GeneratorUtils::class, 'pluralCamelCase')); } - /** @test */ - public function it_has_kebab_case_method() + #[Test] + public function it_has_kebab_case_method(): void { $this->assertTrue(method_exists(GeneratorUtils::class, 'kebabCase')); } - /** @test */ - public function it_has_plural_kebab_case_method() + #[Test] + public function it_has_plural_kebab_case_method(): void { $this->assertTrue(method_exists(GeneratorUtils::class, 'pluralKebabCase')); } - /** @test */ - public function it_has_singular_kebab_case_method() + #[Test] + public function it_has_singular_kebab_case_method(): void { $this->assertTrue(method_exists(GeneratorUtils::class, 'singularKebabCase')); } - /** @test */ - public function it_has_singular_camel_case_method() + #[Test] + public function it_has_singular_camel_case_method(): void { $this->assertTrue(method_exists(GeneratorUtils::class, 'singularCamelCase')); } - /** @test */ - public function it_has_clean_lower_case_method() + #[Test] + public function it_has_clean_lower_case_method(): void { $this->assertTrue(method_exists(GeneratorUtils::class, 'cleanLowerCase')); } - /** @test */ - public function it_has_clean_singular_uc_words_method() + #[Test] + public function it_has_clean_singular_uc_words_method(): void { $this->assertTrue(method_exists(GeneratorUtils::class, 'cleanSingularUcWords')); } - /** @test */ - public function it_has_clean_uc_words_method() + #[Test] + public function it_has_clean_uc_words_method(): void { $this->assertTrue(method_exists(GeneratorUtils::class, 'cleanUcWords')); } - /** @test */ - public function it_has_clean_plural_lower_case_method() + #[Test] + public function it_has_clean_plural_lower_case_method(): void { $this->assertTrue(method_exists(GeneratorUtils::class, 'cleanPluralLowerCase')); } - /** @test */ - public function it_has_get_column_after_id_method() + #[Test] + public function it_has_get_column_after_id_method(): void { $this->assertTrue(method_exists(GeneratorUtils::class, 'getColumnAfterId')); } - /** @test */ - public function it_has_select_column_after_id_and_id_itself_method() + #[Test] + public function it_has_select_column_after_id_and_id_itself_method(): void { $this->assertTrue(method_exists(GeneratorUtils::class, 'selectColumnAfterIdAndIdItself')); } - /** @test */ - public function it_has_clean_singular_sower_case_method() + #[Test] + public function it_has_clean_singular_sower_case_method(): void { $this->assertTrue(method_exists(GeneratorUtils::class, 'cleanSingularLowerCase')); } - /** @test */ - public function it_has_get_model_location_method() + #[Test] + public function it_has_get_model_location_method(): void { $this->assertTrue(method_exists(GeneratorUtils::class, 'getModelLocation')); } - /** @test */ - public function it_has_from_camel_case_method() + #[Test] + public function it_has_from_camel_case_method(): void { $this->assertTrue(method_exists(GeneratorUtils::class, 'fromCamelCase')); } - /** @test */ - public function it_has_set_model_name_method() + #[Test] + public function it_has_set_model_name_method(): void { $this->assertTrue(method_exists(GeneratorUtils::class, 'setModelName')); } - /** @test */ - public function it_has_set_default_image_method() + #[Test] + public function it_has_set_default_image_method(): void { $this->assertTrue(method_exists(GeneratorUtils::class, 'setDefaultImage')); } - /** @test */ - public function it_has_convert_array_sidebar_to_string_method() + #[Test] + public function it_has_convert_array_sidebar_to_string_method(): void { $this->assertTrue(method_exists(GeneratorUtils::class, 'convertArraySidebarToString')); } diff --git a/tests/TestCase.php b/tests/TestCase.php new file mode 100644 index 00000000..caace4c2 --- /dev/null +++ b/tests/TestCase.php @@ -0,0 +1,57 @@ +set('database.default', 'testbench'); + // $config->set('database.connections.testbench', [ + // 'driver' => 'sqlite', + // 'database' => ':memory:', + // 'prefix' => '', + // ]); + + // // Setup queue database connections. + // $config([ + // 'queue.batching.database' => 'testbench', + // 'queue.failed.database' => 'testbench', + // ]); + // }); + // } + + #[Test] + public function it_has_generator_utils_test_class() + { + $this->assertTrue(class_exists(GeneratorUtilsTest::class)); + } +} diff --git a/workbench/app/Models/.gitkeep b/workbench/app/Models/.gitkeep new file mode 100644 index 00000000..e69de29b diff --git a/workbench/app/Providers/WorkbenchServiceProvider.php b/workbench/app/Providers/WorkbenchServiceProvider.php new file mode 100644 index 00000000..e8cec9c2 --- /dev/null +++ b/workbench/app/Providers/WorkbenchServiceProvider.php @@ -0,0 +1,24 @@ +comment(Inspiring::quote()); +})->purpose('Display an inspiring quote')->hourly(); diff --git a/workbench/routes/web.php b/workbench/routes/web.php new file mode 100644 index 00000000..86a06c53 --- /dev/null +++ b/workbench/routes/web.php @@ -0,0 +1,7 @@ + Date: Wed, 20 Mar 2024 11:44:01 +0700 Subject: [PATCH 027/105] add github actions --- .github/workflows/test.yml | 42 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 .github/workflows/test.yml diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml new file mode 100644 index 00000000..845811ee --- /dev/null +++ b/.github/workflows/test.yml @@ -0,0 +1,42 @@ +name: "Run Tests - Current" + +on: [push, pull_request] + +jobs: + test: + + runs-on: ubuntu-latest + strategy: + fail-fast: false + matrix: + php: [8.2, 8.1, 8.0, 7.4, 7.3] + laravel: [10.*] + dependency-version: [prefer-lowest, prefer-stable] + include: + - laravel: 10.* + testbench: 8.* + + exclude: + - laravel: 10.* + php: 8.0 + + name: P${{ matrix.php }} - L${{ matrix.laravel }} - ${{ matrix.dependency-version }} + + steps: + - name: Checkout code + uses: actions/checkout@v3 + + - name: Setup PHP + uses: shivammathur/setup-php@v2 + with: + php-version: ${{ matrix.php }} + extensions: curl, mbstring, zip, pcntl, pdo, sqlite, pdo_sqlite, iconv + coverage: none + + - name: Install dependencies + run: | + composer require "laravel/framework:${{ matrix.laravel }}" "orchestra/testbench:${{ matrix.testbench }}" --no-interaction --no-update + composer update --${{ matrix.dependency-version }} --prefer-dist --no-interaction + + - name: Execute tests + run: vendor/bin/phpunit From edde77ad73216ab5ef1be44c60f0ef6b2c65bb10 Mon Sep 17 00:00:00 2001 From: Mohammad Zulfahmi Date: Wed, 20 Mar 2024 11:47:09 +0700 Subject: [PATCH 028/105] Update test.yml --- .github/workflows/test.yml | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 845811ee..c259160a 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -9,18 +9,18 @@ jobs: strategy: fail-fast: false matrix: - php: [8.2, 8.1, 8.0, 7.4, 7.3] + php: [8.2] laravel: [10.*] - dependency-version: [prefer-lowest, prefer-stable] + # dependency-version: [prefer-lowest, prefer-stable] include: - laravel: 10.* testbench: 8.* exclude: - laravel: 10.* - php: 8.0 + php: 8.2 - name: P${{ matrix.php }} - L${{ matrix.laravel }} - ${{ matrix.dependency-version }} + name: P${{ matrix.php }} - L${{ matrix.laravel }} steps: - name: Checkout code From c2f04f8f75492f7113ed33ddb80f2dc63465bd26 Mon Sep 17 00:00:00 2001 From: Mohammad Zulfahmi Date: Wed, 20 Mar 2024 12:03:16 +0700 Subject: [PATCH 029/105] Update test.yml --- .github/workflows/test.yml | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index c259160a..345ae7c9 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -9,12 +9,12 @@ jobs: strategy: fail-fast: false matrix: - php: [8.2] + php: [8.2, 8.3] laravel: [10.*] # dependency-version: [prefer-lowest, prefer-stable] include: - laravel: 10.* - testbench: 8.* + testbench: 9.* exclude: - laravel: 10.* @@ -35,8 +35,9 @@ jobs: - name: Install dependencies run: | - composer require "laravel/framework:${{ matrix.laravel }}" "orchestra/testbench:${{ matrix.testbench }}" --no-interaction --no-update - composer update --${{ matrix.dependency-version }} --prefer-dist --no-interaction + composer require "laravel/framework:${{ matrix.laravel }}" --no-interaction --no-update + composer require "orchestra/testbench:~9.0" --dev --no-interaction --no-update + composer update --prefer-dist --no-interaction - name: Execute tests run: vendor/bin/phpunit From 3f7c9a827f090aeb6b9dd91d59acb74a2f011534 Mon Sep 17 00:00:00 2001 From: Mohammad Zulfahmi Date: Wed, 20 Mar 2024 12:07:44 +0700 Subject: [PATCH 030/105] Update composer.json --- composer.json | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/composer.json b/composer.json index 2008baaf..5e126f21 100644 --- a/composer.json +++ b/composer.json @@ -28,11 +28,10 @@ "require": { "php": "^8.2", "intervention/image-laravel": "^1.1", - "yajra/laravel-datatables-oracle": "^11.0" - }, - "require-dev": { + "yajra/laravel-datatables-oracle": "^11.0", "orchestra/testbench": "^9.0" }, + "require-dev": {}, "config": { "optimize-autoloader": true, "sort-packages": true @@ -77,4 +76,4 @@ "@php vendor/bin/phpunit" ] } -} \ No newline at end of file +} From ca93efc2e45600a985232a00abc6953cd7d235ca Mon Sep 17 00:00:00 2001 From: Mohammad Zulfahmi Date: Wed, 20 Mar 2024 12:10:13 +0700 Subject: [PATCH 031/105] Update test.yml --- .github/workflows/test.yml | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-) diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 345ae7c9..f7f2bae8 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -10,14 +10,14 @@ jobs: fail-fast: false matrix: php: [8.2, 8.3] - laravel: [10.*] + laravel: [11.*] # dependency-version: [prefer-lowest, prefer-stable] include: - - laravel: 10.* + - laravel: 11.* testbench: 9.* exclude: - - laravel: 10.* + - laravel: 11.* php: 8.2 name: P${{ matrix.php }} - L${{ matrix.laravel }} @@ -35,9 +35,8 @@ jobs: - name: Install dependencies run: | - composer require "laravel/framework:${{ matrix.laravel }}" --no-interaction --no-update - composer require "orchestra/testbench:~9.0" --dev --no-interaction --no-update - composer update --prefer-dist --no-interaction + composer require "laravel/framework:${{ matrix.laravel }}" "orchestra/testbench:${{ matrix.testbench }}" --no-interaction --no-update + composer update --${{ matrix.dependency-version }} --prefer-dist --no-interaction - name: Execute tests run: vendor/bin/phpunit From a68531258662df6b4cf2d466ea52d6e9b0b89ae3 Mon Sep 17 00:00:00 2001 From: Mohammad Zulfahmi Date: Wed, 20 Mar 2024 13:55:44 +0700 Subject: [PATCH 032/105] wip :fire: :fire: :fire: --- .github/workflows/test.yml | 35 +++++++++++++++++++++++++---------- .gitignore | 3 +++ .phpunit.cache/test-results | 1 - composer.json | 8 +++++--- 4 files changed, 33 insertions(+), 14 deletions(-) delete mode 100644 .phpunit.cache/test-results diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index c259160a..8ce49992 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -9,22 +9,33 @@ jobs: strategy: fail-fast: false matrix: - php: [8.2] - laravel: [10.*] - # dependency-version: [prefer-lowest, prefer-stable] + php: [8.3, 8.2, 8.1, 8.0] + laravel: ["^11.0", "^10.0", "^9.0", "^8.12"] + dependency-version: [prefer-lowest, prefer-stable] include: - - laravel: 10.* + - laravel: "^11.0" + testbench: 9.* + - laravel: "^10.0" testbench: 8.* - + - laravel: "^9.0" + testbench: 7.* + - laravel: "^8.12" + testbench: "^6.23" exclude: - - laravel: 10.* - php: 8.2 + - laravel: "^11.0" + php: 8.1 + - laravel: "^11.0" + php: 8.0 + - laravel: "^10.0" + php: 8.0 + - laravel: "^8.12" + php: 8.3 - name: P${{ matrix.php }} - L${{ matrix.laravel }} + name: P${{ matrix.php }} - L${{ matrix.laravel }} - ${{ matrix.dependency-version }} steps: - name: Checkout code - uses: actions/checkout@v3 + uses: actions/checkout@v4 - name: Setup PHP uses: shivammathur/setup-php@v2 @@ -33,9 +44,13 @@ jobs: extensions: curl, mbstring, zip, pcntl, pdo, sqlite, pdo_sqlite, iconv coverage: none + - name: Install dependencies (remove passport) + run: composer remove --dev --no-interaction --no-update + if: matrix.laravel == '^8.12' + - name: Install dependencies run: | - composer require "laravel/framework:${{ matrix.laravel }}" "orchestra/testbench:${{ matrix.testbench }}" --no-interaction --no-update + composer require "laravel/framework:${{ matrix.laravel }}" "orchestra/testbench:${{ matrix.testbench }}" "symfony/console:>=4.3.4" "mockery/mockery:^1.3.2" "nesbot/carbon:>=2.62.1" --no-interaction --no-update composer update --${{ matrix.dependency-version }} --prefer-dist --no-interaction - name: Execute tests diff --git a/.gitignore b/.gitignore index dea59cf3..ff3e7f60 100644 --- a/.gitignore +++ b/.gitignore @@ -3,3 +3,6 @@ composer.lock .phpunit.result.cache generator-cache.json +.idea +.phpunit.cache +.phpunit.result.cache diff --git a/.phpunit.cache/test-results b/.phpunit.cache/test-results deleted file mode 100644 index 4bb1b742..00000000 --- a/.phpunit.cache/test-results +++ /dev/null @@ -1 +0,0 @@ -{"version":1,"defects":{"Tests\\GeneratorUtilsTest::it_has_get_template_method":8,"Tests\\GeneratorUtilsTest::it_has_check_folder_method":8,"Tests\\GeneratorUtilsTest::it_has_singular_pascal_case_method":8,"Tests\\GeneratorUtilsTest::it_has_plural_pascal_case_method":8,"Tests\\GeneratorUtilsTest::it_has_plural_snake_case_method":8,"Tests\\GeneratorUtilsTest::it_has_singular_snake_case_method":8,"Tests\\GeneratorUtilsTest::it_has_plural_camel_case_method":8,"Tests\\GeneratorUtilsTest::it_has_kebab_case_method":8,"Tests\\GeneratorUtilsTest::it_has_plural_kebab_case_method":8,"Tests\\GeneratorUtilsTest::it_has_singular_kebab_case_method":8,"Tests\\GeneratorUtilsTest::it_has_singular_camel_case_method":8,"Tests\\GeneratorUtilsTest::it_has_clean_lower_case_method":8,"Tests\\GeneratorUtilsTest::it_has_clean_singular_uc_words_method":8,"Tests\\GeneratorUtilsTest::it_has_clean_uc_words_method":8,"Tests\\GeneratorUtilsTest::it_has_clean_plural_lower_case_method":8,"Tests\\GeneratorUtilsTest::it_has_get_column_after_id_method":8,"Tests\\GeneratorUtilsTest::it_has_select_column_after_id_and_id_itself_method":8,"Tests\\GeneratorUtilsTest::it_has_clean_singular_sower_case_method":8,"Tests\\GeneratorUtilsTest::it_has_get_model_location_method":8,"Tests\\GeneratorUtilsTest::it_has_from_camel_case_method":8,"Tests\\GeneratorUtilsTest::it_has_set_model_name_method":8,"Tests\\GeneratorUtilsTest::it_has_set_default_image_method":8,"Tests\\GeneratorUtilsTest::it_has_convert_array_sidebar_to_string_method":8},"times":{"Tests\\GeneratorUtilsTest::it_has_get_template_method":0.001,"Tests\\GeneratorUtilsTest::it_has_check_folder_method":0,"Tests\\GeneratorUtilsTest::it_has_singular_pascal_case_method":0,"Tests\\GeneratorUtilsTest::it_has_plural_pascal_case_method":0,"Tests\\GeneratorUtilsTest::it_has_plural_snake_case_method":0,"Tests\\GeneratorUtilsTest::it_has_singular_snake_case_method":0,"Tests\\GeneratorUtilsTest::it_has_plural_camel_case_method":0,"Tests\\GeneratorUtilsTest::it_has_kebab_case_method":0,"Tests\\GeneratorUtilsTest::it_has_plural_kebab_case_method":0,"Tests\\GeneratorUtilsTest::it_has_singular_kebab_case_method":0,"Tests\\GeneratorUtilsTest::it_has_singular_camel_case_method":0,"Tests\\GeneratorUtilsTest::it_has_clean_lower_case_method":0,"Tests\\GeneratorUtilsTest::it_has_clean_singular_uc_words_method":0,"Tests\\GeneratorUtilsTest::it_has_clean_uc_words_method":0,"Tests\\GeneratorUtilsTest::it_has_clean_plural_lower_case_method":0,"Tests\\GeneratorUtilsTest::it_has_get_column_after_id_method":0,"Tests\\GeneratorUtilsTest::it_has_select_column_after_id_and_id_itself_method":0,"Tests\\GeneratorUtilsTest::it_has_clean_singular_sower_case_method":0,"Tests\\GeneratorUtilsTest::it_has_get_model_location_method":0,"Tests\\GeneratorUtilsTest::it_has_from_camel_case_method":0,"Tests\\GeneratorUtilsTest::it_has_set_model_name_method":0,"Tests\\GeneratorUtilsTest::it_has_set_default_image_method":0,"Tests\\GeneratorUtilsTest::it_has_convert_array_sidebar_to_string_method":0,"Tests\\GeneratorUtilsTest::it_has_generator_utils_test_class":0.024,"Tests\\TestCase::it_has_generator_utils_test_class":0.001}} \ No newline at end of file diff --git a/composer.json b/composer.json index 2008baaf..7f20dea0 100644 --- a/composer.json +++ b/composer.json @@ -3,6 +3,7 @@ "description": "Laravel starter app & simple crud generator", "type": "library", "license": "MIT", + "homepage": "https://github.com/Evdigi-INA/generator", "keywords": [ "package", "laravel", @@ -22,7 +23,7 @@ { "name": "Mohammad Zulfahmi", "email": "mohammad.zulfahmi03@gmail.com", - "homepage": "https://github.com/Evdigi-INA/generator" + "homepage": "https://github.com/Zzzul" } ], "require": { @@ -31,7 +32,8 @@ "yajra/laravel-datatables-oracle": "^11.0" }, "require-dev": { - "orchestra/testbench": "^9.0" + "orchestra/testbench": "^6.23|^7.0|^8.0|^9.0", + "phpunit/phpunit": "^9.4|^10.1" }, "config": { "optimize-autoloader": true, @@ -77,4 +79,4 @@ "@php vendor/bin/phpunit" ] } -} \ No newline at end of file +} From 7b80f564686cc44b18561d9afa2b8c1c7e3eabdc Mon Sep 17 00:00:00 2001 From: Mohammad Zulfahmi Date: Thu, 21 Mar 2024 08:44:01 +0700 Subject: [PATCH 033/105] update generator cache & actions --- .github/workflows/test.yml | 8 ++------ .gitignore | 1 + composer.json | 5 ++++- src/Commands/PublishAllFiles.php | 2 +- .../Middleware/OnlyAvailableInTheFullVersion.php | 2 +- src/Providers/GeneratorServiceProvider.php | 15 +++++++++------ 6 files changed, 18 insertions(+), 15 deletions(-) diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 8ce49992..422190b4 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -9,8 +9,8 @@ jobs: strategy: fail-fast: false matrix: - php: [8.3, 8.2, 8.1, 8.0] - laravel: ["^11.0", "^10.0", "^9.0", "^8.12"] + php: [8.3, 8.2, 8.1] + laravel: ["^11.0", "^10.0", "^9.0"] dependency-version: [prefer-lowest, prefer-stable] include: - laravel: "^11.0" @@ -19,8 +19,6 @@ jobs: testbench: 8.* - laravel: "^9.0" testbench: 7.* - - laravel: "^8.12" - testbench: "^6.23" exclude: - laravel: "^11.0" php: 8.1 @@ -28,8 +26,6 @@ jobs: php: 8.0 - laravel: "^10.0" php: 8.0 - - laravel: "^8.12" - php: 8.3 name: P${{ matrix.php }} - L${{ matrix.laravel }} - ${{ matrix.dependency-version }} diff --git a/.gitignore b/.gitignore index ff3e7f60..80df86f3 100644 --- a/.gitignore +++ b/.gitignore @@ -3,6 +3,7 @@ composer.lock .phpunit.result.cache generator-cache.json +generator-cache .idea .phpunit.cache .phpunit.result.cache diff --git a/composer.json b/composer.json index 7f20dea0..eb51991a 100644 --- a/composer.json +++ b/composer.json @@ -33,7 +33,10 @@ }, "require-dev": { "orchestra/testbench": "^6.23|^7.0|^8.0|^9.0", - "phpunit/phpunit": "^9.4|^10.1" + "phpunit/phpunit": "^9.4|^10.1", + "illuminate/container": "^9.0|^10.0|^11.0", + "illuminate/contracts": "^9.0|^10.0|^11.0", + "illuminate/database": "^9.0|^10.0|^11.0" }, "config": { "optimize-autoloader": true, diff --git a/src/Commands/PublishAllFiles.php b/src/Commands/PublishAllFiles.php index 4210c238..209cb312 100644 --- a/src/Commands/PublishAllFiles.php +++ b/src/Commands/PublishAllFiles.php @@ -128,7 +128,7 @@ public function handle(): void * */ public function totalRunningCommand(string $type = 'full_version_publish_count'): array { - $dir = __DIR__ . '/../../generator-cache.json'; + $dir = __DIR__ . '/../../generator-cache'; if (!file_exists($dir)) { file_put_contents( diff --git a/src/Http/Middleware/OnlyAvailableInTheFullVersion.php b/src/Http/Middleware/OnlyAvailableInTheFullVersion.php index 2adca586..93995da1 100644 --- a/src/Http/Middleware/OnlyAvailableInTheFullVersion.php +++ b/src/Http/Middleware/OnlyAvailableInTheFullVersion.php @@ -13,7 +13,7 @@ class OnlyAvailableInTheFullVersion */ public function handle(Request $request, Closure $next): mixed { - $dir = __DIR__ . '/../../../generator-cache.json'; + $dir = __DIR__ . '/../../../generator-cache'; abort_if(!file_exists($dir), Response::HTTP_FORBIDDEN, 'You have not yet selected a version, to use this feature, you must be running the artisan command: "php artisan generator:install full", and then you can use the full version.'); diff --git a/src/Providers/GeneratorServiceProvider.php b/src/Providers/GeneratorServiceProvider.php index 0369dd56..2125b4da 100644 --- a/src/Providers/GeneratorServiceProvider.php +++ b/src/Providers/GeneratorServiceProvider.php @@ -91,12 +91,15 @@ public function boot(): void __DIR__ . '/../../stubs/generators/publish/utils' => app_path('Generators') ], 'generator-utils'); - \Illuminate\Foundation\Console\AboutCommand::add('Generator', fn () => [ - 'Version' => '0.3.0', - 'Source' => 'https://github.com/evdigiina/generator', - 'Docs' => 'https://evdigi-ina.github.io/generator-docs', - 'About' => 'Package for building basic CRUD, especially for your main data.' - ]); + if (class_exists(\Illuminate\Foundation\Console\AboutCommand::class)) { + \Illuminate\Foundation\Console\AboutCommand::add('Generator', fn () => [ + 'Version' => '0.3.0', + 'Source' => 'https://github.com/evdigiina/generator', + 'Docs' => 'https://evdigi-ina.github.io/generator-docs', + 'About' => 'Package for building basic CRUD, especially for your main data.' + ]); + } + if ($this->app->runningInConsole()) $this->commands([PublishAllFiles::class]); From fd4e4381324321699650b39588aa064aa2f4b915 Mon Sep 17 00:00:00 2001 From: Mohammad Zulfahmi Date: Thu, 21 Mar 2024 08:47:17 +0700 Subject: [PATCH 034/105] wip --- .github/workflows/test.yml | 10 +++++++--- composer.json | 11 ++++++----- 2 files changed, 13 insertions(+), 8 deletions(-) diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 422190b4..cd56424e 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -9,8 +9,8 @@ jobs: strategy: fail-fast: false matrix: - php: [8.3, 8.2, 8.1] - laravel: ["^11.0", "^10.0", "^9.0"] + php: [8.3, 8.2, 8.1, 8.0] + laravel: ["^11.0", "^10.0", "^9.0", "^8.12"] dependency-version: [prefer-lowest, prefer-stable] include: - laravel: "^11.0" @@ -19,6 +19,8 @@ jobs: testbench: 8.* - laravel: "^9.0" testbench: 7.* + - laravel: "^8.12" + testbench: "^6.23" exclude: - laravel: "^11.0" php: 8.1 @@ -26,6 +28,8 @@ jobs: php: 8.0 - laravel: "^10.0" php: 8.0 + - laravel: "^8.12" + php: 8.3 name: P${{ matrix.php }} - L${{ matrix.laravel }} - ${{ matrix.dependency-version }} @@ -41,7 +45,7 @@ jobs: coverage: none - name: Install dependencies (remove passport) - run: composer remove --dev --no-interaction --no-update + run: composer remove --dev laravel/passport --no-interaction --no-update if: matrix.laravel == '^8.12' - name: Install dependencies diff --git a/composer.json b/composer.json index eb51991a..79319261 100644 --- a/composer.json +++ b/composer.json @@ -29,14 +29,15 @@ "require": { "php": "^8.2", "intervention/image-laravel": "^1.1", - "yajra/laravel-datatables-oracle": "^11.0" + "yajra/laravel-datatables-oracle": "^11.0", + "illuminate/auth": "^8.12|^9.0|^10.0|^11.0", + "illuminate/container": "^8.12|^9.0|^10.0|^11.0", + "illuminate/contracts": "^8.12|^9.0|^10.0|^11.0", + "illuminate/database": "^8.12|^9.0|^10.0|^11.0" }, "require-dev": { "orchestra/testbench": "^6.23|^7.0|^8.0|^9.0", - "phpunit/phpunit": "^9.4|^10.1", - "illuminate/container": "^9.0|^10.0|^11.0", - "illuminate/contracts": "^9.0|^10.0|^11.0", - "illuminate/database": "^9.0|^10.0|^11.0" + "phpunit/phpunit": "^9.4|^10.1" }, "config": { "optimize-autoloader": true, From e534a04e1022f5f4509a5ab24facfd01c67674eb Mon Sep 17 00:00:00 2001 From: Mohammad Zulfahmi Date: Thu, 21 Mar 2024 08:57:42 +0700 Subject: [PATCH 035/105] wip --- .github/workflows/test.yml | 16 ++++------------ composer.json | 14 +++++++------- 2 files changed, 11 insertions(+), 19 deletions(-) diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index cd56424e..a0f3f0c3 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -9,27 +9,19 @@ jobs: strategy: fail-fast: false matrix: - php: [8.3, 8.2, 8.1, 8.0] - laravel: ["^11.0", "^10.0", "^9.0", "^8.12"] + php: [8.3, 8.2] + laravel: ["^11.0", "^10.0"] dependency-version: [prefer-lowest, prefer-stable] include: - laravel: "^11.0" testbench: 9.* - laravel: "^10.0" testbench: 8.* - - laravel: "^9.0" - testbench: 7.* - - laravel: "^8.12" - testbench: "^6.23" exclude: - laravel: "^11.0" php: 8.1 - - laravel: "^11.0" - php: 8.0 - laravel: "^10.0" php: 8.0 - - laravel: "^8.12" - php: 8.3 name: P${{ matrix.php }} - L${{ matrix.laravel }} - ${{ matrix.dependency-version }} @@ -44,8 +36,8 @@ jobs: extensions: curl, mbstring, zip, pcntl, pdo, sqlite, pdo_sqlite, iconv coverage: none - - name: Install dependencies (remove passport) - run: composer remove --dev laravel/passport --no-interaction --no-update + - name: Install dependencies + run: composer remove --dev --no-interaction --no-update if: matrix.laravel == '^8.12' - name: Install dependencies diff --git a/composer.json b/composer.json index 79319261..52bb9913 100644 --- a/composer.json +++ b/composer.json @@ -29,15 +29,15 @@ "require": { "php": "^8.2", "intervention/image-laravel": "^1.1", - "yajra/laravel-datatables-oracle": "^11.0", - "illuminate/auth": "^8.12|^9.0|^10.0|^11.0", - "illuminate/container": "^8.12|^9.0|^10.0|^11.0", - "illuminate/contracts": "^8.12|^9.0|^10.0|^11.0", - "illuminate/database": "^8.12|^9.0|^10.0|^11.0" + "yajra/laravel-datatables-oracle": "^10.0|^11.0" }, "require-dev": { - "orchestra/testbench": "^6.23|^7.0|^8.0|^9.0", - "phpunit/phpunit": "^9.4|^10.1" + "orchestra/testbench": "^7.0|^8.0|^9.0", + "phpunit/phpunit": "^9.4|^10.1", + "illuminate/auth": "^10.0|^11.0", + "illuminate/container": "^10.0|^11.0", + "illuminate/contracts": "^10.0|^11.0", + "illuminate/database": "^10.0|^11.0" }, "config": { "optimize-autoloader": true, From 4663723778882e0de9ce01bcfdcba1f59ffdeda2 Mon Sep 17 00:00:00 2001 From: Mohammad Zulfahmi Date: Thu, 21 Mar 2024 09:00:30 +0700 Subject: [PATCH 036/105] update actions --- .github/workflows/test.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index a0f3f0c3..497a8f07 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -11,7 +11,7 @@ jobs: matrix: php: [8.3, 8.2] laravel: ["^11.0", "^10.0"] - dependency-version: [prefer-lowest, prefer-stable] + dependency-version: [prefer-stable] include: - laravel: "^11.0" testbench: 9.* From 505e5e0fffa076446a96ed49ef51edc5ad82498e Mon Sep 17 00:00:00 2001 From: Mohammad Zulfahmi Date: Thu, 21 Mar 2024 09:05:21 +0700 Subject: [PATCH 037/105] update actions --- .github/workflows/test.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 497a8f07..fd858b8a 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -23,7 +23,7 @@ jobs: - laravel: "^10.0" php: 8.0 - name: P${{ matrix.php }} - L${{ matrix.laravel }} - ${{ matrix.dependency-version }} + name: PHP ${{ matrix.php }} - Laravel ${{ matrix.laravel }} - ${{ matrix.dependency-version }} steps: - name: Checkout code From f6da6a4edad3396fb3b0592abff06af794b2975e Mon Sep 17 00:00:00 2001 From: Mohammad Zulfahmi Date: Thu, 21 Mar 2024 11:08:37 +0700 Subject: [PATCH 038/105] update generatorUtilsTest :fire: --- .../Interfaces/GeneratorUtilsInterface.php | 10 +++ .../Interfaces/GeneratorUtilsInterface.php | 12 ++- .../publish/utils/Services/ImageService.php | 4 +- tests/GeneratorUtilsTest.php | 89 ++++++++++++++++--- 4 files changed, 101 insertions(+), 14 deletions(-) diff --git a/src/Generators/Interfaces/GeneratorUtilsInterface.php b/src/Generators/Interfaces/GeneratorUtilsInterface.php index 2eb93de5..3b4b896b 100644 --- a/src/Generators/Interfaces/GeneratorUtilsInterface.php +++ b/src/Generators/Interfaces/GeneratorUtilsInterface.php @@ -162,4 +162,14 @@ public static function checkPackageVersion(string $name): string; * Check package in composer.json */ public static function getComposerPackage(string $name): string; + + /** + * Set disk code for controller. + */ + public static function setDiskCodeForController(string $name): string; + + /** + * Set disk code for cast an image. + */ + public static function setDiskCodeForCastImage(string $model, string $field): string; } diff --git a/stubs/generators/publish/utils/Interfaces/GeneratorUtilsInterface.php b/stubs/generators/publish/utils/Interfaces/GeneratorUtilsInterface.php index 4950518f..83697553 100644 --- a/stubs/generators/publish/utils/Interfaces/GeneratorUtilsInterface.php +++ b/stubs/generators/publish/utils/Interfaces/GeneratorUtilsInterface.php @@ -4,7 +4,7 @@ interface GeneratorUtilsInterface { - /** + /** * Get template/stub file. */ public static function getStub(string $path): string; @@ -162,4 +162,14 @@ public static function checkPackageVersion(string $name): string; * Check package in composer.json */ public static function getComposerPackage(string $name): string; + + /** + * Set disk code for controller. + */ + public static function setDiskCodeForController(string $name): string; + + /** + * Set disk code for cast an image. + */ + public static function setDiskCodeForCastImage(string $model, string $field): string; } diff --git a/stubs/generators/publish/utils/Services/ImageService.php b/stubs/generators/publish/utils/Services/ImageService.php index bfaf5471..ff9c9f61 100644 --- a/stubs/generators/publish/utils/Services/ImageService.php +++ b/stubs/generators/publish/utils/Services/ImageService.php @@ -27,7 +27,7 @@ public function upload(string $name, string $path, string|null $defaultImage = n // s3 or local switch (config('generator.image.disk', $disk)) { case 's3': - if (str_contains(GeneratorUtils::checkPackageVersion('intervention/image-laravel'), '2')) { + if (class_exists(\Intervention\Image\Facades\Image::class)) { // for intervention v2 $image = \Intervention\Image\Facades\Image::make($file)->resize($width, $height, config('generator.image.crop') ? function ($constraint) { $constraint->aspectRatio(); @@ -54,7 +54,7 @@ public function upload(string $name, string $path, string|null $defaultImage = n if (!file_exists($path)) mkdir($path, 0777, true); // for intervention v2 - if (str_contains(GeneratorUtils::checkPackageVersion('intervention/image-laravel'), '2')) { + if (class_exists(\Intervention\Image\Facades\Image::class)) { \Intervention\Image\Facades\Image::make($file->getRealPath())->resize($width, $height, config('generator.image.crop') ? function ($constraint) { $constraint->aspectRatio(); $constraint->upsize(); diff --git a/tests/GeneratorUtilsTest.php b/tests/GeneratorUtilsTest.php index b2508823..af47d4d5 100644 --- a/tests/GeneratorUtilsTest.php +++ b/tests/GeneratorUtilsTest.php @@ -8,11 +8,17 @@ class GeneratorUtilsTest extends TestCase { #[Test] - public function it_has_get_template_method(): void + public function it_has_get_stub_method(): void { $this->assertTrue(method_exists(GeneratorUtils::class, 'getStub')); } + #[Test] + public function it_has_get_published_files_method(): void + { + $this->assertTrue(method_exists(GeneratorUtils::class, 'getPublishedFiles')); + } + #[Test] public function it_has_check_folder_method(): void { @@ -25,11 +31,18 @@ public function it_has_singular_pascal_case_method(): void $this->assertTrue(method_exists(GeneratorUtils::class, 'singularPascalCase')); } + #[Test] + public function it_has_pascal_case_method(): void + { + $this->assertTrue(method_exists(GeneratorUtils::class, 'pascalCase')); + } + #[Test] public function it_has_plural_pascal_case_method(): void { $this->assertTrue(method_exists(GeneratorUtils::class, 'pluralPascalCase')); } + #[Test] public function it_has_plural_snake_case_method(): void { @@ -49,9 +62,9 @@ public function it_has_plural_camel_case_method(): void } #[Test] - public function it_has_kebab_case_method(): void + public function it_has_singular_camel_case_method(): void { - $this->assertTrue(method_exists(GeneratorUtils::class, 'kebabCase')); + $this->assertTrue(method_exists(GeneratorUtils::class, 'singularCamelCase')); } #[Test] @@ -60,6 +73,12 @@ public function it_has_plural_kebab_case_method(): void $this->assertTrue(method_exists(GeneratorUtils::class, 'pluralKebabCase')); } + #[Test] + public function it_has_kebab_case_method(): void + { + $this->assertTrue(method_exists(GeneratorUtils::class, 'kebabCase')); + } + #[Test] public function it_has_singular_kebab_case_method(): void { @@ -67,9 +86,9 @@ public function it_has_singular_kebab_case_method(): void } #[Test] - public function it_has_singular_camel_case_method(): void + public function it_has_clean_singular_lower_case_method(): void { - $this->assertTrue(method_exists(GeneratorUtils::class, 'singularCamelCase')); + $this->assertTrue(method_exists(GeneratorUtils::class, 'cleanSingularLowerCase')); } #[Test] @@ -78,6 +97,12 @@ public function it_has_clean_lower_case_method(): void $this->assertTrue(method_exists(GeneratorUtils::class, 'cleanLowerCase')); } + #[Test] + public function it_has_clean_plural_uc_words_method(): void + { + $this->assertTrue(method_exists(GeneratorUtils::class, 'cleanPluralUcWords')); + } + #[Test] public function it_has_clean_singular_uc_words_method(): void { @@ -97,21 +122,21 @@ public function it_has_clean_plural_lower_case_method(): void } #[Test] - public function it_has_get_column_after_id_method(): void + public function it_has_check_string_end_with_method(): void { - $this->assertTrue(method_exists(GeneratorUtils::class, 'getColumnAfterId')); + $this->assertTrue(method_exists(GeneratorUtils::class, 'checkStringEndWith')); } #[Test] - public function it_has_select_column_after_id_and_id_itself_method(): void + public function it_has_get_column_after_id_method(): void { - $this->assertTrue(method_exists(GeneratorUtils::class, 'selectColumnAfterIdAndIdItself')); + $this->assertTrue(method_exists(GeneratorUtils::class, 'getColumnAfterId')); } #[Test] - public function it_has_clean_singular_sower_case_method(): void + public function it_has_select_column_after_id_and_id_itself_method(): void { - $this->assertTrue(method_exists(GeneratorUtils::class, 'cleanSingularLowerCase')); + $this->assertTrue(method_exists(GeneratorUtils::class, 'selectColumnAfterIdAndIdItself')); } #[Test] @@ -143,4 +168,46 @@ public function it_has_convert_array_sidebar_to_string_method(): void { $this->assertTrue(method_exists(GeneratorUtils::class, 'convertArraySidebarToString')); } + + #[Test] + public function it_has_is_active_menu_method(): void + { + $this->assertTrue(method_exists(GeneratorUtils::class, 'isActiveMenu')); + } + + #[Test] + public function it_has_is_generate_api_method(): void + { + $this->assertTrue(method_exists(GeneratorUtils::class, 'isGenerateApi')); + } + + #[Test] + public function it_has_check_package_method(): void + { + $this->assertTrue(method_exists(GeneratorUtils::class, 'checkPackage')); + } + + #[Test] + public function it_has_check_package_version_method(): void + { + $this->assertTrue(method_exists(GeneratorUtils::class, 'checkPackageVersion')); + } + + #[Test] + public function it_has_get_composer_package_method(): void + { + $this->assertTrue(method_exists(GeneratorUtils::class, 'getComposerPackage')); + } + + #[Test] + public function it_has_set_disk_code_for_controller_method(): void + { + $this->assertTrue(method_exists(GeneratorUtils::class, 'setDiskCodeForController')); + } + + #[Test] + public function it_has_set_disk_code_for_cast_image_method(): void + { + $this->assertTrue(method_exists(GeneratorUtils::class, 'setDiskCodeForCastImage')); + } } From 51b5a3c3aa2e334dde4580cb29e4946fcd57874d Mon Sep 17 00:00:00 2001 From: Mohammad Zulfahmi Date: Thu, 21 Mar 2024 16:18:26 +0700 Subject: [PATCH 039/105] wip --- phpunit.xml | 1 + src/Http/Controllers/GeneratorController.php | 9 +- .../views/generators/api-create.blade.php | 48 ++++-- .../views/generators/create.blade.php | 43 +++-- src/Routes/generator.php | 2 +- testbench.yaml | 2 + tests/GeneratorTest.php | 33 ++++ tests/TestCase.php | 108 +++++++++---- .../Providers/WorkbenchServiceProvider.php | 3 +- workbench/app/Views/Breadcrumb.php | 20 +++ .../views/components/alert.blade.php | 55 +++++++ .../views/components/breadcrumb.blade.php | 7 + .../resources/views/layouts/app.blade.php | 7 + .../resources/views/layouts/auth.blade.php | 37 +++++ .../resources/views/layouts/footer.blade.php | 22 +++ .../resources/views/layouts/header.blade.php | 100 ++++++++++++ .../resources/views/layouts/sidebar.blade.php | 149 ++++++++++++++++++ 17 files changed, 583 insertions(+), 63 deletions(-) create mode 100644 tests/GeneratorTest.php create mode 100644 workbench/app/Views/Breadcrumb.php create mode 100644 workbench/resources/views/components/alert.blade.php create mode 100644 workbench/resources/views/components/breadcrumb.blade.php create mode 100644 workbench/resources/views/layouts/app.blade.php create mode 100644 workbench/resources/views/layouts/auth.blade.php create mode 100644 workbench/resources/views/layouts/footer.blade.php create mode 100644 workbench/resources/views/layouts/header.blade.php create mode 100644 workbench/resources/views/layouts/sidebar.blade.php diff --git a/phpunit.xml b/phpunit.xml index 12193912..0f1a4678 100644 --- a/phpunit.xml +++ b/phpunit.xml @@ -8,5 +8,6 @@ + diff --git a/src/Http/Controllers/GeneratorController.php b/src/Http/Controllers/GeneratorController.php index 7232f8cd..8b723d58 100644 --- a/src/Http/Controllers/GeneratorController.php +++ b/src/Http/Controllers/GeneratorController.php @@ -2,15 +2,20 @@ namespace EvdigiIna\Generator\Http\Controllers; -use App\Http\Controllers\Controller; use EvdigiIna\Generator\Enums\GeneratorType; use EvdigiIna\Generator\Generators\Services\GeneratorService; use EvdigiIna\Generator\Http\Requests\StoreGeneratorRequest; use Symfony\Component\HttpFoundation\Response; use EvdigiIna\Generator\Generators\GeneratorUtils; +use Illuminate\Foundation\Auth\Access\AuthorizesRequests; +use Illuminate\Foundation\Bus\DispatchesJobs; +use Illuminate\Foundation\Validation\ValidatesRequests; +use Illuminate\Routing\Controller as BaseController; -class GeneratorController extends Controller +class GeneratorController extends BaseController { + use AuthorizesRequests, DispatchesJobs, ValidatesRequests; + public function __construct(protected GeneratorService $generatorService) { // diff --git a/src/Resources/views/generators/api-create.blade.php b/src/Resources/views/generators/api-create.blade.php index afc704e8..92fe160b 100644 --- a/src/Resources/views/generators/api-create.blade.php +++ b/src/Resources/views/generators/api-create.blade.php @@ -3,7 +3,9 @@ @section('title', __('Create Module (API)')) @push('css') - + @endpush @section('content') @@ -17,19 +19,37 @@

- - - - +
+ +
- + @if (session('success')) + + @endif + + @if (session('error')) + + @endif
@@ -41,7 +61,8 @@ @include('generator::include.api-form') - {{ __('Back') }} + {{ __('Back') }} @@ -61,11 +82,12 @@ @endsection @push('js') - + @include('generator::include.js.api-create-js') @include('generator::include.js.function-js') @endpush - diff --git a/src/Resources/views/generators/create.blade.php b/src/Resources/views/generators/create.blade.php index 05f98c27..66521ade 100644 --- a/src/Resources/views/generators/create.blade.php +++ b/src/Resources/views/generators/create.blade.php @@ -3,7 +3,9 @@ @section('title', __('Create Module')) @push('css') - + @endpush @section('content') @@ -17,19 +19,37 @@

- - - - +
+ +
- + @if (session('success')) + + @endif + + @if (session('error')) + + @endif
@@ -41,7 +61,8 @@ @include('generator::include.form') - {{ __('Back') }} + {{ __('Back') }} diff --git a/src/Routes/generator.php b/src/Routes/generator.php index 3ebd79d4..0010cec2 100644 --- a/src/Routes/generator.php +++ b/src/Routes/generator.php @@ -6,7 +6,7 @@ use EvdigiIna\Generator\Http\Middleware\TheGeneratorOnlyWorksInTheLocalEnv; use Illuminate\Support\Facades\Route; -Route::middleware(['web', 'auth', TheGeneratorOnlyWorksInTheLocalEnv::class])->group(function () { +Route::middleware(['web', TheGeneratorOnlyWorksInTheLocalEnv::class])->group(function () { Route::get('/generators/get-sidebar-menus/{index}', [GeneratorController::class, 'getSidebarMenus']) ->name('generators.get-sidebar-menus'); diff --git a/testbench.yaml b/testbench.yaml index f056e1e7..5ada7023 100644 --- a/testbench.yaml +++ b/testbench.yaml @@ -1,5 +1,7 @@ providers: - Workbench\App\Providers\WorkbenchServiceProvider + - EvdigiIna\Generator\Providers\GeneratorServiceProvider + - App\Providers\FortifyServiceProvider migrations: - workbench/database/migrations diff --git a/tests/GeneratorTest.php b/tests/GeneratorTest.php new file mode 100644 index 00000000..d6651a1b --- /dev/null +++ b/tests/GeneratorTest.php @@ -0,0 +1,33 @@ +withoutExceptionHandling(); + + // $this->get('/generators/create')->assertStatus(200); + // } + + #[Test] + public function it_can_render_simple_generator_create_page(): void + { + $this->get('/simple-generators/create')->assertStatus(200); + } + + // #[Test] + // public function it_can_render_api_generator_create_page(): void + // { + // $this->withoutExceptionHandling(); + + // $this->get('/api-generators/create')->assertStatus(200); + // } +} diff --git a/tests/TestCase.php b/tests/TestCase.php index caace4c2..eeb3ab0a 100644 --- a/tests/TestCase.php +++ b/tests/TestCase.php @@ -2,10 +2,12 @@ namespace Tests; +use EvdigiIna\Generator\Http\Controllers\GeneratorController; +use Illuminate\Contracts\Config\Repository; use Orchestra\Testbench\Concerns\WithWorkbench; use Illuminate\Foundation\Testing\Concerns\InteractsWithViews; -use Illuminate\Contracts\Config\Repository; use Illuminate\Foundation\Testing\RefreshDatabase; +use Illuminate\Support\Facades\Artisan; use Orchestra\Testbench\Attributes\WithMigration; use PHPUnit\Framework\Attributes\Test; @@ -14,40 +16,76 @@ class TestCase extends \Orchestra\Testbench\TestCase { use WithWorkbench, InteractsWithViews, RefreshDatabase; - // /** - // * Get package providers. - // */ - // protected function getPackageProviders($app) - // { - // return [ - // 'EvdigiIna\GeneratorServiceProvider', - // ]; - // } - - // /** - // * Define environment setup. - // * - // * @param \Illuminate\Foundation\Application $app - // * @return void - // */ - // protected function defineEnvironment($app) - // { - // // Setup default database to use sqlite :memory: - // tap($app['config'], function (Repository $config) { - // $config->set('database.default', 'testbench'); - // $config->set('database.connections.testbench', [ - // 'driver' => 'sqlite', - // 'database' => ':memory:', - // 'prefix' => '', - // ]); - - // // Setup queue database connections. - // $config([ - // 'queue.batching.database' => 'testbench', - // 'queue.failed.database' => 'testbench', - // ]); - // }); - // } + /** + * Setup the test environment. + */ + protected function setUp(): void + { + // Code before application created. + + $this->afterApplicationCreated(function () { + Artisan::call('view:clear'); + }); + + $this->beforeApplicationDestroyed(function () { + Artisan::call('view:clear'); + }); + + parent::setUp(); + } + + /** + * Get package providers. + * + * @param \Illuminate\Foundation\Application $app + * @return array> + */ + protected function getPackageProviders($app) + { + return [ + \EvdigiIna\Generator\Providers\GeneratorServiceProvider::class, + // \App\Providers\FortifyServiceProvider::class, + ]; + } + + /** + * Define routes setup. + * + * @param \Illuminate\Routing\Router $router + * @return void + */ + protected function defineRoutes($router) + { + // $router->get('/generators/create', [GeneratorController::class, 'create']); + } + + /** + * Define environment setup. + * + * @param \Illuminate\Foundation\Application $app + * @return void + */ + protected function defineEnvironment($app) + { + $app['config']->set('view.paths', [ + __DIR__ . '/views', + resource_path('views'), + ]); + + $app['config']->set('app.key', 'base64:Hupx3yAySikrM2/edkZQNQHslgDWYfiBfCuSThJ5SK8='); + + $app['config']->set('database.default', 'testbench'); + $app['config']->set('database.connections.testbench', [ + 'driver' => 'sqlite', + 'database' => ':memory:', + 'prefix' => '', + ]); + + $app['config']->set('filesystems.disks.unit-downloads', [ + 'driver' => 'local', + 'root' => __DIR__ . '/fixtures', + ]); + } #[Test] public function it_has_generator_utils_test_class() diff --git a/workbench/app/Providers/WorkbenchServiceProvider.php b/workbench/app/Providers/WorkbenchServiceProvider.php index e8cec9c2..1131b13f 100644 --- a/workbench/app/Providers/WorkbenchServiceProvider.php +++ b/workbench/app/Providers/WorkbenchServiceProvider.php @@ -3,6 +3,7 @@ namespace Workbench\App\Providers; use Illuminate\Support\ServiceProvider; +use Illuminate\Support\Facades\Blade; class WorkbenchServiceProvider extends ServiceProvider { @@ -19,6 +20,6 @@ public function register(): void */ public function boot(): void { - // + Blade::component('breadcrumb', \App\View\Components\Breadcrumb::class); } } diff --git a/workbench/app/Views/Breadcrumb.php b/workbench/app/Views/Breadcrumb.php new file mode 100644 index 00000000..c20b3b03 --- /dev/null +++ b/workbench/app/Views/Breadcrumb.php @@ -0,0 +1,20 @@ +breadcrumbs = $breadcrumbs; + } + + public function render() + { + return view('components.breadcrumb'); + } +} diff --git a/workbench/resources/views/components/alert.blade.php b/workbench/resources/views/components/alert.blade.php new file mode 100644 index 00000000..bfb8924f --- /dev/null +++ b/workbench/resources/views/components/alert.blade.php @@ -0,0 +1,55 @@ +@if (session('success')) + +@endif + +@if (session('error')) + +@endif + +@if (session('status') == 'profile-information-updated') +
+ +

{{ __('Success') }}

+

{{ __('Profile information updated successfully.') }}

+
+@endif + +@if (session('status') == 'password-updated') +
+ +

{{ __('Success') }}

+

{{ __('Password updated successfully.') }}

+
+@endif + +@if (session('status') == 'two-factor-authentication-disabled') +
+ +

{{ __('Success') }}

+

{{ __('Two factor Authentication has been disabled.') }}

+
+@endif + +@if (session('status') == 'two-factor-authentication-enabled') +
+ +

{{ __('Success') }}

+

{{ __('Two factor Authentication has been enabled.') }}

+
+@endif + +@if (session('status') == 'recovery-codes-generated') +
+ +

{{ __('Success') }}

+

{{ __('Regenerated Recovery Codes Successfully.') }}

+
+@endif diff --git a/workbench/resources/views/components/breadcrumb.blade.php b/workbench/resources/views/components/breadcrumb.blade.php new file mode 100644 index 00000000..35ab48a2 --- /dev/null +++ b/workbench/resources/views/components/breadcrumb.blade.php @@ -0,0 +1,7 @@ +
+ +
diff --git a/workbench/resources/views/layouts/app.blade.php b/workbench/resources/views/layouts/app.blade.php new file mode 100644 index 00000000..4007f85a --- /dev/null +++ b/workbench/resources/views/layouts/app.blade.php @@ -0,0 +1,7 @@ +@include('layouts.header') + +
+ @yield('content') +
+ +@include('layouts.footer') diff --git a/workbench/resources/views/layouts/auth.blade.php b/workbench/resources/views/layouts/auth.blade.php new file mode 100644 index 00000000..40cf627d --- /dev/null +++ b/workbench/resources/views/layouts/auth.blade.php @@ -0,0 +1,37 @@ + + + + + + + Login - Mazer Admin Dashboard + + + + + + + @stack('css') + + + + + + +
+ @yield('content') +
+ + + + + + diff --git a/workbench/resources/views/layouts/footer.blade.php b/workbench/resources/views/layouts/footer.blade.php new file mode 100644 index 00000000..4aa58bdc --- /dev/null +++ b/workbench/resources/views/layouts/footer.blade.php @@ -0,0 +1,22 @@ +
+ +
+
+ + + + @stack('js') + + + diff --git a/workbench/resources/views/layouts/header.blade.php b/workbench/resources/views/layouts/header.blade.php new file mode 100644 index 00000000..18b123cb --- /dev/null +++ b/workbench/resources/views/layouts/header.blade.php @@ -0,0 +1,100 @@ + + + + + + + @yield('title') - {{ env('APP_NAME') }} + + + + + + @stack('css') + + + + +
+ @include('layouts.sidebar') + + -
- -
+ + + +
- @if (session('success')) - - @endif - - @if (session('error')) - - @endif +
diff --git a/src/Resources/views/generators/create.blade.php b/src/Resources/views/generators/create.blade.php index 66521ade..efd2e476 100644 --- a/src/Resources/views/generators/create.blade.php +++ b/src/Resources/views/generators/create.blade.php @@ -19,37 +19,19 @@

-
- -
+ + + +
- @if (session('success')) - - @endif - - @if (session('error')) - - @endif +
diff --git a/testbench.yaml b/testbench.yaml index 7ae43e93..ce95a19d 100644 --- a/testbench.yaml +++ b/testbench.yaml @@ -15,9 +15,9 @@ workbench: discovers: web: true api: false - commands: false - components: false - views: false + commands: true + components: true + views: true build: [] assets: [] sync: [] diff --git a/tests/GeneratorTest.php b/tests/GeneratorTest.php index d6651a1b..d9626d3b 100644 --- a/tests/GeneratorTest.php +++ b/tests/GeneratorTest.php @@ -9,13 +9,13 @@ class GeneratorTest extends TestCase { use InteractsWithViews; - // #[Test] - // public function it_can_render_generator_create_page(): void - // { - // $this->withoutExceptionHandling(); + #[Test] + public function it_can_render_generator_create_page(): void + { + $this->withoutExceptionHandling(); - // $this->get('/generators/create')->assertStatus(200); - // } + $this->get('/generators/create')->assertStatus(200)->assertSee('Generators'); + } #[Test] public function it_can_render_simple_generator_create_page(): void @@ -23,11 +23,11 @@ public function it_can_render_simple_generator_create_page(): void $this->get('/simple-generators/create')->assertStatus(200); } - // #[Test] - // public function it_can_render_api_generator_create_page(): void - // { - // $this->withoutExceptionHandling(); + #[Test] + public function it_can_render_api_generator_create_page(): void + { + $this->withoutExceptionHandling(); - // $this->get('/api-generators/create')->assertStatus(200); - // } + $this->get('/api-generators/create')->assertStatus(200)->assertSee('API Generators'); + } } diff --git a/tests/TestCase.php b/tests/TestCase.php index 08bb19d0..94686985 100644 --- a/tests/TestCase.php +++ b/tests/TestCase.php @@ -64,24 +64,24 @@ protected function defineRoutes($router) */ protected function defineEnvironment($app) { - $app['config']->set('view.paths', [ - __DIR__ . '/views', - resource_path('views'), - ]); + // $app['config']->set('view.paths', [ + // __DIR__ . '/views', + // resource_path('views'), + // ]); - $app['config']->set('app.key', 'base64:Hupx3yAySikrM2/edkZQNQHslgDWYfiBfCuSThJ5SK8='); + // $app['config']->set('app.key', 'base64:Hupx3yAySikrM2/edkZQNQHslgDWYfiBfCuSThJ5SK8='); - $app['config']->set('database.default', 'testbench'); - $app['config']->set('database.connections.testbench', [ - 'driver' => 'sqlite', - 'database' => ':memory:', - 'prefix' => '', - ]); + // $app['config']->set('database.default', 'testbench'); + // $app['config']->set('database.connections.testbench', [ + // 'driver' => 'sqlite', + // 'database' => ':memory:', + // 'prefix' => '', + // ]); - $app['config']->set('filesystems.disks.unit-downloads', [ - 'driver' => 'local', - 'root' => __DIR__ . '/fixtures', - ]); + // $app['config']->set('filesystems.disks.unit-downloads', [ + // 'driver' => 'local', + // 'root' => __DIR__ . '/fixtures', + // ]); } #[Test] diff --git a/workbench/resources/views/layouts/header.blade.php b/workbench/resources/views/layouts/header.blade.php index 18b123cb..b8983888 100644 --- a/workbench/resources/views/layouts/header.blade.php +++ b/workbench/resources/views/layouts/header.blade.php @@ -44,56 +44,60 @@
  • -
  • {{ __('Indonesia') }}
  • -
  • {{ __('English') }}
  • +
  • {{ __('Indonesia') }}
  • +
  • {{ __('English') }}
  • - diff --git a/workbench/resources/views/layouts/sidebar.blade.php b/workbench/resources/views/layouts/sidebar.blade.php index ba6847c2..cdd840da 100644 --- a/workbench/resources/views/layouts/sidebar.blade.php +++ b/workbench/resources/views/layouts/sidebar.blade.php @@ -50,52 +50,58 @@ - @foreach (config('generator.sidebars') as $sidebar) - @if (isset($sidebar['permissions'])) - @canany($sidebar['permissions']) - + @if(config('generator.sidebars')) + @foreach (config('generator.sidebars') as $sidebar) + @if (isset($sidebar['permissions'])) + @canany($sidebar['permissions']) + - @foreach ($sidebar['menus'] as $menu) - @php - $permissions = empty($menu['permission']) ? $menu['permissions'] : [$menu['permission']]; - @endphp + @foreach ($sidebar['menus'] as $menu) + @php + $permissions = empty($menu['permission']) + ? $menu['permissions'] + : [$menu['permission']]; + @endphp - @canany($permissions) - @if (empty($menu['submenus'])) - @can($menu['permission']) - + @endcan + @else + - @endcan - @else - - @endif - @endcanany - @endforeach - @endcanany - @endif - @endforeach + @endif + @endcanany + @endforeach + @endcanany + @endif + @endforeach + @endif @if (env('APP_ENV') === 'local') @@ -122,26 +128,28 @@ @endif - + @auth + - + - +
    + @csrf +
    + + @endauth
    From e19247766754f8f966fff5183d7644b8cefa01a1 Mon Sep 17 00:00:00 2001 From: Mohammad Zulfahmi Date: Fri, 22 Mar 2024 09:40:15 +0700 Subject: [PATCH 042/105] fix test failed in it_can_render_generator_create_page --- tests/GeneratorTest.php | 15 +++++++++++++-- tests/TestCase.php | 2 -- 2 files changed, 13 insertions(+), 4 deletions(-) diff --git a/tests/GeneratorTest.php b/tests/GeneratorTest.php index d9626d3b..62a81c5c 100644 --- a/tests/GeneratorTest.php +++ b/tests/GeneratorTest.php @@ -9,6 +9,19 @@ class GeneratorTest extends TestCase { use InteractsWithViews; + protected function setUp(): void + { + parent::setUp(); + + $this->afterApplicationCreated(function () { + file_put_contents(__DIR__ . '/../generator-cache', '{"simple_version_publish_count":0,"full_version_publish_count":1}'); + }); + + $this->beforeApplicationDestroyed(function () { + file_put_contents(__DIR__ . '/../generator-cache', '{"simple_version_publish_count":0,"full_version_publish_count":1}'); + }); + } + #[Test] public function it_can_render_generator_create_page(): void { @@ -26,8 +39,6 @@ public function it_can_render_simple_generator_create_page(): void #[Test] public function it_can_render_api_generator_create_page(): void { - $this->withoutExceptionHandling(); - $this->get('/api-generators/create')->assertStatus(200)->assertSee('API Generators'); } } diff --git a/tests/TestCase.php b/tests/TestCase.php index 94686985..6b66c94a 100644 --- a/tests/TestCase.php +++ b/tests/TestCase.php @@ -19,8 +19,6 @@ class TestCase extends \Orchestra\Testbench\TestCase */ protected function setUp(): void { - // Code before application created. - $this->afterApplicationCreated(function () { Artisan::call('view:clear'); }); From 3a9a26cff0ff92ecd2450a8ac6d79fb0841793f5 Mon Sep 17 00:00:00 2001 From: Mohammad Zulfahmi Date: Fri, 22 Mar 2024 10:02:00 +0700 Subject: [PATCH 043/105] wip --- .github/workflows/test.yml | 10 ++++++---- composer.json | 2 +- 2 files changed, 7 insertions(+), 5 deletions(-) diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index fd858b8a..4ce1d79b 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -18,10 +18,12 @@ jobs: - laravel: "^10.0" testbench: 8.* exclude: - - laravel: "^11.0" - php: 8.1 - - laravel: "^10.0" - php: 8.0 + - laravel: "^11.0" + php: 8.1 + - laravel: "^11.0" + php: 8.0 + - laravel: "^10.0" + php: 8.0 name: PHP ${{ matrix.php }} - Laravel ${{ matrix.laravel }} - ${{ matrix.dependency-version }} diff --git a/composer.json b/composer.json index 52bb9913..bcc6f83c 100644 --- a/composer.json +++ b/composer.json @@ -32,7 +32,7 @@ "yajra/laravel-datatables-oracle": "^10.0|^11.0" }, "require-dev": { - "orchestra/testbench": "^7.0|^8.0|^9.0", + "orchestra/testbench": "^8.0|^9.0", "phpunit/phpunit": "^9.4|^10.1", "illuminate/auth": "^10.0|^11.0", "illuminate/container": "^10.0|^11.0", From 23413dc06256a0f71b4110c526035e7e774f76d6 Mon Sep 17 00:00:00 2001 From: Mohammad Zulfahmi Date: Fri, 22 Mar 2024 10:20:23 +0700 Subject: [PATCH 044/105] wip --- .github/workflows/test.yml | 10 ++++------ composer.json | 2 +- tests/TestCase.php | 30 +++++++++++++++--------------- 3 files changed, 20 insertions(+), 22 deletions(-) diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 4ce1d79b..fd858b8a 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -18,12 +18,10 @@ jobs: - laravel: "^10.0" testbench: 8.* exclude: - - laravel: "^11.0" - php: 8.1 - - laravel: "^11.0" - php: 8.0 - - laravel: "^10.0" - php: 8.0 + - laravel: "^11.0" + php: 8.1 + - laravel: "^10.0" + php: 8.0 name: PHP ${{ matrix.php }} - Laravel ${{ matrix.laravel }} - ${{ matrix.dependency-version }} diff --git a/composer.json b/composer.json index bcc6f83c..52bb9913 100644 --- a/composer.json +++ b/composer.json @@ -32,7 +32,7 @@ "yajra/laravel-datatables-oracle": "^10.0|^11.0" }, "require-dev": { - "orchestra/testbench": "^8.0|^9.0", + "orchestra/testbench": "^7.0|^8.0|^9.0", "phpunit/phpunit": "^9.4|^10.1", "illuminate/auth": "^10.0|^11.0", "illuminate/container": "^10.0|^11.0", diff --git a/tests/TestCase.php b/tests/TestCase.php index 6b66c94a..2cacdc07 100644 --- a/tests/TestCase.php +++ b/tests/TestCase.php @@ -62,24 +62,24 @@ protected function defineRoutes($router) */ protected function defineEnvironment($app) { - // $app['config']->set('view.paths', [ - // __DIR__ . '/views', - // resource_path('views'), - // ]); + $app['config']->set('view.paths', [ + __DIR__ . '/views', + resource_path('views'), + ]); - // $app['config']->set('app.key', 'base64:Hupx3yAySikrM2/edkZQNQHslgDWYfiBfCuSThJ5SK8='); + $app['config']->set('app.key', 'base64:Hupx3yAySikrM2/edkZQNQHslgDWYfiBfCuSThJ5SK8='); - // $app['config']->set('database.default', 'testbench'); - // $app['config']->set('database.connections.testbench', [ - // 'driver' => 'sqlite', - // 'database' => ':memory:', - // 'prefix' => '', - // ]); + $app['config']->set('database.default', 'testbench'); + $app['config']->set('database.connections.testbench', [ + 'driver' => 'sqlite', + 'database' => ':memory:', + 'prefix' => '', + ]); - // $app['config']->set('filesystems.disks.unit-downloads', [ - // 'driver' => 'local', - // 'root' => __DIR__ . '/fixtures', - // ]); + $app['config']->set('filesystems.disks.unit-downloads', [ + 'driver' => 'local', + 'root' => __DIR__ . '/fixtures', + ]); } #[Test] From ca2ef290684b4b0a3f977d2485b7dca04abc2b03 Mon Sep 17 00:00:00 2001 From: Mohammad Zulfahmi Date: Fri, 22 Mar 2024 10:32:32 +0700 Subject: [PATCH 045/105] wip - drop laravel 10 support --- .github/workflows/test.yml | 12 ++---------- composer.json | 7 +------ 2 files changed, 3 insertions(+), 16 deletions(-) diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index fd858b8a..0526d0c4 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -10,18 +10,14 @@ jobs: fail-fast: false matrix: php: [8.3, 8.2] - laravel: ["^11.0", "^10.0"] - dependency-version: [prefer-stable] + laravel: ["^11.0"] + dependency-version: [prefer-stable, prefer-lowest] include: - laravel: "^11.0" testbench: 9.* - - laravel: "^10.0" - testbench: 8.* exclude: - laravel: "^11.0" php: 8.1 - - laravel: "^10.0" - php: 8.0 name: PHP ${{ matrix.php }} - Laravel ${{ matrix.laravel }} - ${{ matrix.dependency-version }} @@ -36,10 +32,6 @@ jobs: extensions: curl, mbstring, zip, pcntl, pdo, sqlite, pdo_sqlite, iconv coverage: none - - name: Install dependencies - run: composer remove --dev --no-interaction --no-update - if: matrix.laravel == '^8.12' - - name: Install dependencies run: | composer require "laravel/framework:${{ matrix.laravel }}" "orchestra/testbench:${{ matrix.testbench }}" "symfony/console:>=4.3.4" "mockery/mockery:^1.3.2" "nesbot/carbon:>=2.62.1" --no-interaction --no-update diff --git a/composer.json b/composer.json index 52bb9913..b030123f 100644 --- a/composer.json +++ b/composer.json @@ -32,12 +32,7 @@ "yajra/laravel-datatables-oracle": "^10.0|^11.0" }, "require-dev": { - "orchestra/testbench": "^7.0|^8.0|^9.0", - "phpunit/phpunit": "^9.4|^10.1", - "illuminate/auth": "^10.0|^11.0", - "illuminate/container": "^10.0|^11.0", - "illuminate/contracts": "^10.0|^11.0", - "illuminate/database": "^10.0|^11.0" + "orchestra/testbench": "^9.0" }, "config": { "optimize-autoloader": true, From 0daa79597552034fb083af00ac82e9bda3c872d1 Mon Sep 17 00:00:00 2001 From: Mohammad Zulfahmi Date: Fri, 22 Mar 2024 14:17:18 +0700 Subject: [PATCH 046/105] fix sidebar image not found --- stubs/generators/sidebar-dynamic.stub | 2 +- stubs/generators/sidebar-static.stub | 2 +- tests/GeneratorTest.php | 98 +++++++- tests/TestCase.php | 15 ++ workbench/config/permission.php | 216 ++++++++++++++++++ .../resources/views/layouts/sidebar.blade.php | 2 +- 6 files changed, 330 insertions(+), 5 deletions(-) create mode 100644 workbench/config/permission.php diff --git a/stubs/generators/sidebar-dynamic.stub b/stubs/generators/sidebar-dynamic.stub index 1121238a..c65db2a4 100644 --- a/stubs/generators/sidebar-dynamic.stub +++ b/stubs/generators/sidebar-dynamic.stub @@ -4,7 +4,7 @@
    diff --git a/stubs/generators/sidebar-static.stub b/stubs/generators/sidebar-static.stub index 584f0852..b40fc6ec 100644 --- a/stubs/generators/sidebar-static.stub +++ b/stubs/generators/sidebar-static.stub @@ -4,7 +4,7 @@
    diff --git a/tests/GeneratorTest.php b/tests/GeneratorTest.php index 62a81c5c..2e4eb93a 100644 --- a/tests/GeneratorTest.php +++ b/tests/GeneratorTest.php @@ -3,6 +3,7 @@ namespace Tests; use Illuminate\Foundation\Testing\Concerns\InteractsWithViews; +use Illuminate\Support\Facades\Artisan; use PHPUnit\Framework\Attributes\Test; class GeneratorTest extends TestCase @@ -15,18 +16,20 @@ protected function setUp(): void $this->afterApplicationCreated(function () { file_put_contents(__DIR__ . '/../generator-cache', '{"simple_version_publish_count":0,"full_version_publish_count":1}'); + + Artisan::call('migrate:fresh --seed'); }); $this->beforeApplicationDestroyed(function () { file_put_contents(__DIR__ . '/../generator-cache', '{"simple_version_publish_count":0,"full_version_publish_count":1}'); + + Artisan::call('migrate:fresh --seed'); }); } #[Test] public function it_can_render_generator_create_page(): void { - $this->withoutExceptionHandling(); - $this->get('/generators/create')->assertStatus(200)->assertSee('Generators'); } @@ -41,4 +44,95 @@ public function it_can_render_api_generator_create_page(): void { $this->get('/api-generators/create')->assertStatus(200)->assertSee('API Generators'); } + + // #[Test] + public function it_can_create_new_module_using_a_simple_generator_version(): void + { + $this->withoutExceptionHandling(); + + $modelName = 'Generator' . $this->generateRandomString(); + + $this->post('/simple-generators', json_decode('{ + "requireds": [ + "yes", + "no" + ], + "_token": "mFXgQ36wdxA3tbL0zz74ikc9cUe3z2IWe4YN30zv", + "_method": "POST", + "model": "'. $modelName . '", + "generate_type": "all", + "generate_variant": "default", + "generate_seeder": "on", + "generate_factory": "on", + "fields": [ + "name", + "logo" + ], + "column_types": [ + "string", + "string" + ], + "select_options": [ + null, + null + ], + "constrains": [ + null, + null + ], + "foreign_ids": [ + null, + null + ], + "on_update_foreign": [ + null, + null + ], + "on_delete_foreign": [ + null, + null + ], + "min_lengths": [ + null, + null + ], + "max_lengths": [ + null, + null + ], + "input_types": [ + "text", + "file" + ], + "file_types": [ + null, + "image" + ], + "files_sizes": [ + null, + "1024" + ], + "mimes": [ + null, + null + ], + "steps": [ + null, + null + ], + "default_values": [ + null, + null + ] + }', true))->assertSuccessful(); + } + + function generateRandomString($length = 5): string + { + $characters = 'abcdefghijklmnopqrstuvwxyz'; + $charactersLength = strlen($characters); + $randomString = ''; + for ($i = 0; $i < $length; $i++) $randomString .= $characters[random_int(0, $charactersLength - 1)]; + return $randomString; + } } diff --git a/tests/TestCase.php b/tests/TestCase.php index 2cacdc07..8b48d8a2 100644 --- a/tests/TestCase.php +++ b/tests/TestCase.php @@ -8,6 +8,7 @@ use Illuminate\Support\Facades\Artisan; use Orchestra\Testbench\Attributes\WithMigration; use PHPUnit\Framework\Attributes\Test; +use function Orchestra\Testbench\workbench_path; #[WithMigration] class TestCase extends \Orchestra\Testbench\TestCase @@ -21,10 +22,12 @@ protected function setUp(): void { $this->afterApplicationCreated(function () { Artisan::call('view:clear'); + Artisan::call('migrate:fresh --seed'); }); $this->beforeApplicationDestroyed(function () { Artisan::call('view:clear'); + Artisan::call('migrate:fresh --seed'); }); parent::setUp(); @@ -43,6 +46,16 @@ protected function getPackageProviders($app) ]; } + /** + * Define database migrations. + * + * @return void + */ + protected function defineDatabaseMigrations() + { + $this->loadMigrationsFrom(workbench_path('database/migrations')); + } + /** * Define routes setup. * @@ -85,6 +98,8 @@ protected function defineEnvironment($app) #[Test] public function it_has_generator_utils_test_class() { + $this->withoutExceptionHandling(); + $this->assertTrue(class_exists(GeneratorUtilsTest::class)); } } diff --git a/workbench/config/permission.php b/workbench/config/permission.php new file mode 100644 index 00000000..c89f6ba9 --- /dev/null +++ b/workbench/config/permission.php @@ -0,0 +1,216 @@ + [ + + /* + * When using the "HasPermissions" trait from this package, we need to know which + * Eloquent model should be used to retrieve your permissions. Of course, it + * is often just the "Permission" model but you may use whatever you like. + * + * The model you want to use as a Permission model needs to implement the + * `Spatie\Permission\Contracts\Permission` contract. + */ + + 'permission' => Spatie\Permission\Models\Permission::class, + + /* + * When using the "HasRoles" trait from this package, we need to know which + * Eloquent model should be used to retrieve your roles. Of course, it + * is often just the "Role" model but you may use whatever you like. + * + * The model you want to use as a Role model needs to implement the + * `Spatie\Permission\Contracts\Role` contract. + */ + + 'role' => Spatie\Permission\Models\Role::class, + + ], + + 'table_names' => [ + + /* + * When using the "HasRoles" trait from this package, we need to know which + * table should be used to retrieve your roles. We have chosen a basic + * default value but you may easily change it to any table you like. + */ + + 'roles' => 'roles', + + /* + * When using the "HasPermissions" trait from this package, we need to know which + * table should be used to retrieve your permissions. We have chosen a basic + * default value but you may easily change it to any table you like. + */ + + 'permissions' => 'permissions', + + /* + * When using the "HasPermissions" trait from this package, we need to know which + * table should be used to retrieve your models permissions. We have chosen a + * basic default value but you may easily change it to any table you like. + */ + + 'model_has_permissions' => 'model_has_permissions', + + /* + * When using the "HasRoles" trait from this package, we need to know which + * table should be used to retrieve your models roles. We have chosen a + * basic default value but you may easily change it to any table you like. + */ + + 'model_has_roles' => 'model_has_roles', + + /* + * When using the "HasRoles" trait from this package, we need to know which + * table should be used to retrieve your roles permissions. We have chosen a + * basic default value but you may easily change it to any table you like. + */ + + 'role_has_permissions' => 'role_has_permissions', + ], + + 'column_names' => [ + /* + * Change this if you want to name the related pivots other than defaults + */ + 'role_pivot_key' => null, //default 'role_id', + 'permission_pivot_key' => null, //default 'permission_id', + + /* + * Change this if you want to name the related model primary key other than + * `model_id`. + * + * For example, this would be nice if your primary keys are all UUIDs. In + * that case, name this `model_uuid`. + */ + + 'model_morph_key' => 'model_id', + + /* + * Change this if you want to use the teams feature and your related model's + * foreign key is other than `team_id`. + */ + + 'team_foreign_key' => 'team_id', + ], + + /* + * When set to true, the method for checking permissions will be registered on the gate. + * Set this to false if you want to implement custom logic for checking permissions. + */ + + 'register_permission_check_method' => true, + + /* + * When set to true, Laravel\Octane\Events\OperationTerminated event listener will be registered + * this will refresh permissions on every TickTerminated, TaskTerminated and RequestTerminated + * NOTE: This should not be needed in most cases, but an Octane/Vapor combination benefited from it. + */ + 'register_octane_reset_listener' => false, + + /* + * Teams Feature. + * When set to true the package implements teams using the 'team_foreign_key'. + * If you want the migrations to register the 'team_foreign_key', you must + * set this to true before doing the migration. + * If you already did the migration then you must make a new migration to also + * add 'team_foreign_key' to 'roles', 'model_has_roles', and 'model_has_permissions' + * (view the latest version of this package's migration file) + */ + + 'teams' => false, + + /* + * Passport Client Credentials Grant + * When set to true the package will use Passports Client to check permissions + */ + + 'use_passport_client_credentials' => false, + + /* + * When set to true, the required permission names are added to exception messages. + * This could be considered an information leak in some contexts, so the default + * setting is false here for optimum safety. + */ + + 'display_permission_in_exception' => false, + + /* + * When set to true, the required role names are added to exception messages. + * This could be considered an information leak in some contexts, so the default + * setting is false here for optimum safety. + */ + + 'display_role_in_exception' => false, + + /* + * By default wildcard permission lookups are disabled. + * See documentation to understand supported syntax. + */ + + 'enable_wildcard_permission' => false, + + /* + * The class to use for interpreting wildcard permissions. + * If you need to modify delimiters, override the class and specify its name here. + */ + // 'permission.wildcard_permission' => Spatie\Permission\WildcardPermission::class, + + /* Cache-specific settings */ + + 'cache' => [ + + /* + * By default all permissions are cached for 24 hours to speed up performance. + * When permissions or roles are updated the cache is flushed automatically. + */ + + 'expiration_time' => \DateInterval::createFromDateString('24 hours'), + + /* + * The cache key used to store all permissions. + */ + + 'key' => 'spatie.permission.cache', + + /* + * You may optionally indicate a specific cache driver to use for permission and + * role caching using any of the `store` drivers listed in the cache.php config + * file. Using 'default' here means to use the `default` set in cache.php. + */ + + 'store' => 'default', + ], + + /** + * Below are the permissions generated by the generator and will be inserted into the database. + */ + 'permissions' => [ + [ + 'group' => 'users', + 'access' => [ + 'user view', + 'user create', + 'user edit', + 'user delete', + ] + ], + [ + 'group' => 'roles & permissions', + 'access' => [ + 'role & permission view', + 'role & permission create', + 'role & permission edit', + 'role & permission delete', + ] + ], + [ + 'group' => 'tests', + 'access' => [ + 'test view', + ] + ], + ], +]; diff --git a/workbench/resources/views/layouts/sidebar.blade.php b/workbench/resources/views/layouts/sidebar.blade.php index cdd840da..66db5cd9 100644 --- a/workbench/resources/views/layouts/sidebar.blade.php +++ b/workbench/resources/views/layouts/sidebar.blade.php @@ -4,7 +4,7 @@
    From 19e66f32ffe66d3c28176e0dd922ed4ede018ca5 Mon Sep 17 00:00:00 2001 From: Mohammad Zulfahmi Date: Fri, 22 Mar 2024 14:47:44 +0700 Subject: [PATCH 047/105] fix generatorTest --- tests/GeneratorTest.php | 4 ++-- tests/TestCase.php | 15 --------------- 2 files changed, 2 insertions(+), 17 deletions(-) diff --git a/tests/GeneratorTest.php b/tests/GeneratorTest.php index 2e4eb93a..d840bdb6 100644 --- a/tests/GeneratorTest.php +++ b/tests/GeneratorTest.php @@ -17,13 +17,13 @@ protected function setUp(): void $this->afterApplicationCreated(function () { file_put_contents(__DIR__ . '/../generator-cache', '{"simple_version_publish_count":0,"full_version_publish_count":1}'); - Artisan::call('migrate:fresh --seed'); + // Artisan::call('migrate:fresh --seed'); }); $this->beforeApplicationDestroyed(function () { file_put_contents(__DIR__ . '/../generator-cache', '{"simple_version_publish_count":0,"full_version_publish_count":1}'); - Artisan::call('migrate:fresh --seed'); + // Artisan::call('migrate:fresh --seed'); }); } diff --git a/tests/TestCase.php b/tests/TestCase.php index 8b48d8a2..2cacdc07 100644 --- a/tests/TestCase.php +++ b/tests/TestCase.php @@ -8,7 +8,6 @@ use Illuminate\Support\Facades\Artisan; use Orchestra\Testbench\Attributes\WithMigration; use PHPUnit\Framework\Attributes\Test; -use function Orchestra\Testbench\workbench_path; #[WithMigration] class TestCase extends \Orchestra\Testbench\TestCase @@ -22,12 +21,10 @@ protected function setUp(): void { $this->afterApplicationCreated(function () { Artisan::call('view:clear'); - Artisan::call('migrate:fresh --seed'); }); $this->beforeApplicationDestroyed(function () { Artisan::call('view:clear'); - Artisan::call('migrate:fresh --seed'); }); parent::setUp(); @@ -46,16 +43,6 @@ protected function getPackageProviders($app) ]; } - /** - * Define database migrations. - * - * @return void - */ - protected function defineDatabaseMigrations() - { - $this->loadMigrationsFrom(workbench_path('database/migrations')); - } - /** * Define routes setup. * @@ -98,8 +85,6 @@ protected function defineEnvironment($app) #[Test] public function it_has_generator_utils_test_class() { - $this->withoutExceptionHandling(); - $this->assertTrue(class_exists(GeneratorUtilsTest::class)); } } From 80b437a148a0e3245906bac40ad3649fdddb6955 Mon Sep 17 00:00:00 2001 From: Mohammad Zulfahmi Date: Sat, 23 Mar 2024 09:16:00 +0700 Subject: [PATCH 048/105] update GeneratorTest --- testbench.yaml | 1 + tests/GeneratorTest.php | 86 ++----------------- tests/TestCase.php | 13 +-- .../Providers/ViewComposerServiceProvider.php | 25 ++++++ 4 files changed, 34 insertions(+), 91 deletions(-) create mode 100644 workbench/app/Providers/ViewComposerServiceProvider.php diff --git a/testbench.yaml b/testbench.yaml index ce95a19d..4e2a738d 100644 --- a/testbench.yaml +++ b/testbench.yaml @@ -1,5 +1,6 @@ providers: - Workbench\App\Providers\WorkbenchServiceProvider + - Workbench\App\Providers\ViewComposerServiceProvider - EvdigiIna\Generator\Providers\GeneratorServiceProvider migrations: diff --git a/tests/GeneratorTest.php b/tests/GeneratorTest.php index d840bdb6..cd66e8f2 100644 --- a/tests/GeneratorTest.php +++ b/tests/GeneratorTest.php @@ -2,8 +2,8 @@ namespace Tests; +use EvdigiIna\Generator\Generators\GeneratorUtils; use Illuminate\Foundation\Testing\Concerns\InteractsWithViews; -use Illuminate\Support\Facades\Artisan; use PHPUnit\Framework\Attributes\Test; class GeneratorTest extends TestCase @@ -16,14 +16,10 @@ protected function setUp(): void $this->afterApplicationCreated(function () { file_put_contents(__DIR__ . '/../generator-cache', '{"simple_version_publish_count":0,"full_version_publish_count":1}'); - - // Artisan::call('migrate:fresh --seed'); }); $this->beforeApplicationDestroyed(function () { file_put_contents(__DIR__ . '/../generator-cache', '{"simple_version_publish_count":0,"full_version_publish_count":1}'); - - // Artisan::call('migrate:fresh --seed'); }); } @@ -45,86 +41,14 @@ public function it_can_render_api_generator_create_page(): void $this->get('/api-generators/create')->assertStatus(200)->assertSee('API Generators'); } - // #[Test] - public function it_can_create_new_module_using_a_simple_generator_version(): void + #[Test] + public function it_can_create_new_module(): void { $this->withoutExceptionHandling(); $modelName = 'Generator' . $this->generateRandomString(); - $this->post('/simple-generators', json_decode('{ - "requireds": [ - "yes", - "no" - ], - "_token": "mFXgQ36wdxA3tbL0zz74ikc9cUe3z2IWe4YN30zv", - "_method": "POST", - "model": "'. $modelName . '", - "generate_type": "all", - "generate_variant": "default", - "generate_seeder": "on", - "generate_factory": "on", - "fields": [ - "name", - "logo" - ], - "column_types": [ - "string", - "string" - ], - "select_options": [ - null, - null - ], - "constrains": [ - null, - null - ], - "foreign_ids": [ - null, - null - ], - "on_update_foreign": [ - null, - null - ], - "on_delete_foreign": [ - null, - null - ], - "min_lengths": [ - null, - null - ], - "max_lengths": [ - null, - null - ], - "input_types": [ - "text", - "file" - ], - "file_types": [ - null, - "image" - ], - "files_sizes": [ - null, - "1024" - ], - "mimes": [ - null, - null - ], - "steps": [ - null, - null - ], - "default_values": [ - null, - null - ] - }', true))->assertSuccessful(); + $this->post('/simple-generators', json_decode('{"requireds":["yes","yes","yes","yes","yes","yes","yes","no","no","no","yes","yes","no","no","yes","yes","yes","yes","yes","yes","yes","yes","yes","yes","yes"],"_token":"LIV8Mj4vCRSIGWhbQFVcZax6jwnsZMS7JAWGhdTe","_method":"POST","model":"'. $modelName .'","generate_type":"all","generate_variant":"api","generate_seeder":"on","generate_factory":"on","fields":["q","w","e","r","t","y","u","i","o","p","a","s","d","f","g","h","j","k","l","z","x","c","v","b","n"],"column_types":["string","string","string","string","string","string","string","string","string","string","integer","integer","integer","integer","boolean","boolean","boolean","date","date","time","year","year","dateTime","enum","foreignId"],"select_options":[null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,"PHP|Laravel",null],"constrains":[null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,"User"],"foreign_ids":[null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null],"on_update_foreign":[null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,"0"],"on_delete_foreign":[null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,"0"],"min_lengths":[null,null,null,null,null,null,null,null,null,null,null,"1",null,null,null,null,null,null,null,null,null,null,null,null,null],"max_lengths":[null,null,null,null,null,null,null,null,null,null,null,"100",null,null,null,null,null,null,null,null,null,null,null,null,null],"input_types":["text","textarea","email","tel","password","url","search","file","hidden","no-input","number","range","hidden","no-input","select","radio","datalist","date","month","time","select","datalist","datetime-local","select","select"],"file_types":[null,null,null,null,null,null,null,"image",null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null],"files_sizes":[null,null,null,null,null,null,null,"1024",null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null],"mimes":[null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null],"steps":[null,null,null,null,null,null,null,null,null,null,null,"1",null,null,null,null,null,null,null,null,null,null,null,null,null],"default_values":[null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null]}', true))->assertSuccessful(); } function generateRandomString($length = 5): string @@ -132,7 +56,9 @@ function generateRandomString($length = 5): string $characters = 'abcdefghijklmnopqrstuvwxyz'; $charactersLength = strlen($characters); $randomString = ''; + for ($i = 0; $i < $length; $i++) $randomString .= $characters[random_int(0, $charactersLength - 1)]; + return $randomString; } } diff --git a/tests/TestCase.php b/tests/TestCase.php index 2cacdc07..b38979bf 100644 --- a/tests/TestCase.php +++ b/tests/TestCase.php @@ -40,20 +40,11 @@ protected function getPackageProviders($app) { return [ \EvdigiIna\Generator\Providers\GeneratorServiceProvider::class, + \Yajra\DataTables\DataTablesServiceProvider::class, + \Workbench\App\Providers\ViewComposerServiceProvider::class, ]; } - /** - * Define routes setup. - * - * @param \Illuminate\Routing\Router $router - * @return void - */ - protected function defineRoutes($router) - { - // $router->get('/generators/create', [GeneratorController::class, 'create']); - } - /** * Define environment setup. * diff --git a/workbench/app/Providers/ViewComposerServiceProvider.php b/workbench/app/Providers/ViewComposerServiceProvider.php new file mode 100644 index 00000000..0770cd8b --- /dev/null +++ b/workbench/app/Providers/ViewComposerServiceProvider.php @@ -0,0 +1,25 @@ + Date: Sat, 23 Mar 2024 10:15:43 +0700 Subject: [PATCH 049/105] add larastan & phpinsights --- composer.json | 7 ++++++- phpstan.neon | 19 +++++++++++++++++++ src/Commands/PublishAllFiles.php | 13 ------------- src/Commands/SetSidebarType.php | 18 +++--------------- src/Generators/Views/ActionViewGenerator.php | 2 +- .../publish/controllers/UserController.php | 5 +++-- workbench/app/Views/Breadcrumb.php | 5 ++--- 7 files changed, 34 insertions(+), 35 deletions(-) create mode 100644 phpstan.neon diff --git a/composer.json b/composer.json index b030123f..47251d7d 100644 --- a/composer.json +++ b/composer.json @@ -32,11 +32,16 @@ "yajra/laravel-datatables-oracle": "^10.0|^11.0" }, "require-dev": { + "larastan/larastan": "^2.0", + "nunomaduro/phpinsights": "^2.11", "orchestra/testbench": "^9.0" }, "config": { "optimize-autoloader": true, - "sort-packages": true + "sort-packages": true, + "allow-plugins": { + "dealerdirect/phpcodesniffer-composer-installer": true + } }, "minimum-stability": "dev", "prefer-stable": true, diff --git a/phpstan.neon b/phpstan.neon new file mode 100644 index 00000000..9ec20b7a --- /dev/null +++ b/phpstan.neon @@ -0,0 +1,19 @@ +includes: + - vendor/larastan/larastan/extension.neon + +parameters: + + paths: + - src/ + - tests/ + + # Level 9 is the highest level + level: 5 + +# ignoreErrors: +# - '#PHPDoc tag @var#' +# +# excludePaths: +# - ./*/*/FileToBeExcluded.php +# +# checkMissingIterableValueType: false diff --git a/src/Commands/PublishAllFiles.php b/src/Commands/PublishAllFiles.php index 209cb312..3a41c3ff 100644 --- a/src/Commands/PublishAllFiles.php +++ b/src/Commands/PublishAllFiles.php @@ -23,16 +23,6 @@ class PublishAllFiles extends Command */ protected $description = 'Publish the required file for the generator.'; - /** - * Create a new command instance. - * - * @return void - */ - public function __construct() - { - parent::__construct(); - } - /** * Execute the console command. */ @@ -78,10 +68,8 @@ public function handle(): void switch ($this->confirm('Do you wish to continue? you are already running this command ' . $totalRunningCommand['full_version_publish_count'] . ' times.')) { case true: $this->runPublishAll(); - return; break; default: - return; break; } } @@ -92,7 +80,6 @@ public function handle(): void } break; case 'simple': - $totalRunningCommand = $this->totalRunningCommand('simple_version_publish_count'); if ($totalRunningCommand['full_version_publish_count'] == 1 || $totalRunningCommand['full_version_publish_count'] > 1) { diff --git a/src/Commands/SetSidebarType.php b/src/Commands/SetSidebarType.php index c0961fe3..e042646c 100644 --- a/src/Commands/SetSidebarType.php +++ b/src/Commands/SetSidebarType.php @@ -21,16 +21,6 @@ class SetSidebarType extends Command */ protected $description = 'Set a sidebar menu to fully blade code(static) or use a list from config(dynamic)'; - /** - * Create a new command instance. - * - * @return void - */ - public function __construct() - { - parent::__construct(); - } - /** * Execute the console command. */ @@ -51,20 +41,18 @@ public function handle(): void $sidebarCode .= "])\n\t"; - foreach (config('generator.sidebars') as $i => $sidebar) : + foreach (config('generator.sidebars') as $sidebar) : if (isset($sidebar['permissions'])) { $sidebarCode .= "
  • {{ __('" . $sidebar['header'] . "') }}
  • @canany(["; + $sidebarCode .= "])\n\t"; + foreach ($sidebar['menus'] as $menu) { $permissions = empty($menu['permission']) ? $menu['permissions'] : [$menu['permission']]; $sidebarCode .= GeneratorUtils::convertArraySidebarToString($permissions); - } - - $sidebarCode .= "])\n\t"; - foreach ($sidebar['menus'] as $key => $menu) { if ($menu['submenus'] == []) { $sidebarCode .= " @can('" . $menu['permission'] . "') diff --git a/src/Generators/Views/ActionViewGenerator.php b/src/Generators/Views/ActionViewGenerator.php index 8185596a..975dbc0b 100644 --- a/src/Generators/Views/ActionViewGenerator.php +++ b/src/Generators/Views/ActionViewGenerator.php @@ -39,6 +39,6 @@ public function generate(array $request): void GeneratorUtils::checkFolder(resource_path("/views/$modelNamePluralKebabCase/include")); file_put_contents(resource_path("/views/$modelNamePluralKebabCase/include/action.blade.php"), $template); - }; + } } } diff --git a/stubs/generators/publish/controllers/UserController.php b/stubs/generators/publish/controllers/UserController.php index e60bc27f..5cd88365 100644 --- a/stubs/generators/publish/controllers/UserController.php +++ b/stubs/generators/publish/controllers/UserController.php @@ -129,8 +129,9 @@ public function update(UpdateUserRequest $request, User $user): \Illuminate\Http $constraint->upsize(); })->save(public_path($this->avatarPath) . $filename); - if ($user->avatar != null && file_exists($oldAvatar = public_path($this->avatarPath . - $user->avatar))) { + $oldAvatar = public_path($this->avatarPath . $user->avatar); + + if ($user->avatar != null && file_exists($oldAvatar)) { unlink($oldAvatar); } diff --git a/workbench/app/Views/Breadcrumb.php b/workbench/app/Views/Breadcrumb.php index c20b3b03..4ee05775 100644 --- a/workbench/app/Views/Breadcrumb.php +++ b/workbench/app/Views/Breadcrumb.php @@ -6,11 +6,10 @@ class Breadcrumb extends Component { - public $breadcrumbs; - public function __construct($breadcrumbs) + public function __construct(public $breadcrumbs) { - $this->breadcrumbs = $breadcrumbs; + // } public function render() From 1e33541b5845b67cb8108a8e48dbb27183174f85 Mon Sep 17 00:00:00 2001 From: Mohammad Zulfahmi Date: Mon, 25 Mar 2024 19:44:41 +0700 Subject: [PATCH 050/105] add command & helper test :fire: :rocket: --- src/Commands/SetSidebarType.php | 10 ++++++---- tests/CommandTest.php | 32 ++++++++++++++++++++++++++++++++ tests/GeneratorTest.php | 1 - tests/HelperTest.php | 21 +++++++++++++++++++++ 4 files changed, 59 insertions(+), 5 deletions(-) create mode 100644 tests/CommandTest.php create mode 100644 tests/HelperTest.php diff --git a/src/Commands/SetSidebarType.php b/src/Commands/SetSidebarType.php index e042646c..677703ff 100644 --- a/src/Commands/SetSidebarType.php +++ b/src/Commands/SetSidebarType.php @@ -47,12 +47,14 @@ public function handle(): void
  • {{ __('" . $sidebar['header'] . "') }}
  • @canany(["; - $sidebarCode .= "])\n\t"; - foreach ($sidebar['menus'] as $menu) { $permissions = empty($menu['permission']) ? $menu['permissions'] : [$menu['permission']]; $sidebarCode .= GeneratorUtils::convertArraySidebarToString($permissions); + } + $sidebarCode .= "])\n\t"; + + foreach ($sidebar['menus'] as $menu) { if ($menu['submenus'] == []) { $sidebarCode .= " @can('" . $menu['permission'] . "') @@ -124,14 +126,14 @@ public function checkGeneratorVariant(): void { if (empty(config('generator.sidebars'))) { $this->error("It looks that you are using the simple version, this command is only available in the full version. Please refer to the section on available commands at https://evdigi-ina.github.io/generator-docs/features/"); - die; + return; } $sidebar = file_exists(resource_path('views/layouts/sidebar.blade.php')); if (!$sidebar) { $this->error("We cant find the sidebar view, in views/layouts/sidebar.blade.php."); - die; + return; } } } diff --git a/tests/CommandTest.php b/tests/CommandTest.php new file mode 100644 index 00000000..9ffb00fc --- /dev/null +++ b/tests/CommandTest.php @@ -0,0 +1,32 @@ +withoutExceptionHandling(); + + // $this->artisan('generator:sidebar static')->assertSuccessful(); + // } + + #[Test] + public function it_can_run_generator_install_full_command() + { + $this->withoutExceptionHandling(); + + $this->artisan('generator:install full')->assertSuccessful()->assertExitCode(0); + } + + #[Test] + public function it_can_run_generator_install_simple_command() + { + $this->withoutExceptionHandling(); + + $this->artisan('generator:install simple')->assertSuccessful()->assertExitCode(0); + } +} diff --git a/tests/GeneratorTest.php b/tests/GeneratorTest.php index cd66e8f2..370015a0 100644 --- a/tests/GeneratorTest.php +++ b/tests/GeneratorTest.php @@ -2,7 +2,6 @@ namespace Tests; -use EvdigiIna\Generator\Generators\GeneratorUtils; use Illuminate\Foundation\Testing\Concerns\InteractsWithViews; use PHPUnit\Framework\Attributes\Test; diff --git a/tests/HelperTest.php b/tests/HelperTest.php new file mode 100644 index 00000000..33fd5e81 --- /dev/null +++ b/tests/HelperTest.php @@ -0,0 +1,21 @@ +assertTrue(function_exists(is_active_menu('/generators/create'))); + // } + + #[Test] + public function it_helper_file_exists(): void + { + + $this->assertTrue(file_exists(__DIR__ . '/../src/helper.php')); + } +} From 080e34c02607a27b942d3dfc9a145bb28cdf22b0 Mon Sep 17 00:00:00 2001 From: Mohammad Zulfahmi Date: Tue, 26 Mar 2024 07:59:23 +0700 Subject: [PATCH 051/105] fix sidebnar and header when not logged in :hammer: --- .../generators/include/api-form.blade.php | 4 +- .../publish/views/layouts/header.blade.php | 93 ++++++++++--------- .../publish/views/layouts/sidebar.blade.php | 62 +++++++------ stubs/generators/sidebar-dynamic.stub | 80 ++++++++++------ stubs/generators/sidebar-static.stub | 68 +++++++++----- 5 files changed, 180 insertions(+), 127 deletions(-) diff --git a/src/Resources/views/generators/include/api-form.blade.php b/src/Resources/views/generators/include/api-form.blade.php index 722ed5bc..6e7df4a1 100644 --- a/src/Resources/views/generators/include/api-form.blade.php +++ b/src/Resources/views/generators/include/api-form.blade.php @@ -76,9 +76,9 @@ {{ __('Column Type') }} {{ __('Length') }} - {{ __('Input Type') }} + {{ __('Expected') }}
    - {{ __('Used for validation request') }} + {{ __('Input Type') }} {{ __('Required') }} {{ __('Action') }} diff --git a/stubs/generators/publish/views/layouts/header.blade.php b/stubs/generators/publish/views/layouts/header.blade.php index 18b123cb..76a670d0 100644 --- a/stubs/generators/publish/views/layouts/header.blade.php +++ b/stubs/generators/publish/views/layouts/header.blade.php @@ -44,56 +44,61 @@
  • -
  • {{ __('Indonesia') }}
  • -
  • {{ __('English') }}
  • +
  • {{ __('Indonesia') }}
  • +
  • {{ __('English') }}
  • - diff --git a/stubs/generators/publish/views/layouts/sidebar.blade.php b/stubs/generators/publish/views/layouts/sidebar.blade.php index 36db9b84..4a29d364 100644 --- a/stubs/generators/publish/views/layouts/sidebar.blade.php +++ b/stubs/generators/publish/views/layouts/sidebar.blade.php @@ -43,12 +43,14 @@
    diff --git a/stubs/generators/sidebar-dynamic.stub b/stubs/generators/sidebar-dynamic.stub index c65db2a4..4a29d364 100644 --- a/stubs/generators/sidebar-dynamic.stub +++ b/stubs/generators/sidebar-dynamic.stub @@ -43,12 +43,14 @@
    diff --git a/stubs/generators/sidebar-static.stub b/stubs/generators/sidebar-static.stub index b40fc6ec..3e3ce86b 100644 --- a/stubs/generators/sidebar-static.stub +++ b/stubs/generators/sidebar-static.stub @@ -43,46 +43,64 @@
    From 5c002221f8cdde2a673bf950640d6af32e1216e4 Mon Sep 17 00:00:00 2001 From: Mohammad Zulfahmi Date: Tue, 26 Mar 2024 14:44:10 +0700 Subject: [PATCH 052/105] restructuring resorces folders :sunflower: --- composer.json | 3 +- .../views}/api-create.blade.php | 0 .../views}/create.blade.php | 0 .../views}/include/api-form.blade.php | 0 .../views}/include/form.blade.php | 0 .../views}/include/js/api-create-js.blade.php | 0 .../views}/include/js/create-js.blade.php | 0 .../views}/include/js/function-js.blade.php | 0 .../views}/include/script.blade.php | 0 .../views}/simple-create.blade.php | 0 {src/Routes => routes}/generator.php | 0 src/Facades/Generator.php | 492 ++++++++++++++++++ src/Providers/GeneratorServiceProvider.php | 8 +- .../publish/config/full-version/generator.php | 6 +- .../config/simple-version/generator.php | 86 +-- .../publish/controllers/UserController.php | 59 +-- .../publish/database/seeders/UserSeeder.php | 2 +- tests/{ => Unit}/CommandTest.php | 0 tests/{ => Unit}/GeneratorTest.php | 0 tests/{ => Unit}/GeneratorUtilsTest.php | 0 tests/{ => Unit}/HelperTest.php | 2 +- 21 files changed, 517 insertions(+), 141 deletions(-) rename {src/Resources/views/generators => resources/views}/api-create.blade.php (100%) rename {src/Resources/views/generators => resources/views}/create.blade.php (100%) rename {src/Resources/views/generators => resources/views}/include/api-form.blade.php (100%) rename {src/Resources/views/generators => resources/views}/include/form.blade.php (100%) rename {src/Resources/views/generators => resources/views}/include/js/api-create-js.blade.php (100%) rename {src/Resources/views/generators => resources/views}/include/js/create-js.blade.php (100%) rename {src/Resources/views/generators => resources/views}/include/js/function-js.blade.php (100%) rename {src/Resources/views/generators => resources/views}/include/script.blade.php (100%) rename {src/Resources/views/generators => resources/views}/simple-create.blade.php (100%) rename {src/Routes => routes}/generator.php (100%) create mode 100644 src/Facades/Generator.php rename tests/{ => Unit}/CommandTest.php (100%) rename tests/{ => Unit}/GeneratorTest.php (100%) rename tests/{ => Unit}/GeneratorUtilsTest.php (100%) rename tests/{ => Unit}/HelperTest.php (82%) diff --git a/composer.json b/composer.json index 47251d7d..6a4a8af1 100644 --- a/composer.json +++ b/composer.json @@ -52,7 +52,8 @@ "Yajra\\DataTables\\DataTablesServiceProvider" ], "aliases": { - "DataTables": "Yajra\\DataTables\\Facades\\DataTables" + "DataTables": "Yajra\\DataTables\\Facades\\DataTables", + "Generator": "EvdigiIna\\Generator\\Facades\\Generator" } } }, diff --git a/src/Resources/views/generators/api-create.blade.php b/resources/views/api-create.blade.php similarity index 100% rename from src/Resources/views/generators/api-create.blade.php rename to resources/views/api-create.blade.php diff --git a/src/Resources/views/generators/create.blade.php b/resources/views/create.blade.php similarity index 100% rename from src/Resources/views/generators/create.blade.php rename to resources/views/create.blade.php diff --git a/src/Resources/views/generators/include/api-form.blade.php b/resources/views/include/api-form.blade.php similarity index 100% rename from src/Resources/views/generators/include/api-form.blade.php rename to resources/views/include/api-form.blade.php diff --git a/src/Resources/views/generators/include/form.blade.php b/resources/views/include/form.blade.php similarity index 100% rename from src/Resources/views/generators/include/form.blade.php rename to resources/views/include/form.blade.php diff --git a/src/Resources/views/generators/include/js/api-create-js.blade.php b/resources/views/include/js/api-create-js.blade.php similarity index 100% rename from src/Resources/views/generators/include/js/api-create-js.blade.php rename to resources/views/include/js/api-create-js.blade.php diff --git a/src/Resources/views/generators/include/js/create-js.blade.php b/resources/views/include/js/create-js.blade.php similarity index 100% rename from src/Resources/views/generators/include/js/create-js.blade.php rename to resources/views/include/js/create-js.blade.php diff --git a/src/Resources/views/generators/include/js/function-js.blade.php b/resources/views/include/js/function-js.blade.php similarity index 100% rename from src/Resources/views/generators/include/js/function-js.blade.php rename to resources/views/include/js/function-js.blade.php diff --git a/src/Resources/views/generators/include/script.blade.php b/resources/views/include/script.blade.php similarity index 100% rename from src/Resources/views/generators/include/script.blade.php rename to resources/views/include/script.blade.php diff --git a/src/Resources/views/generators/simple-create.blade.php b/resources/views/simple-create.blade.php similarity index 100% rename from src/Resources/views/generators/simple-create.blade.php rename to resources/views/simple-create.blade.php diff --git a/src/Routes/generator.php b/routes/generator.php similarity index 100% rename from src/Routes/generator.php rename to routes/generator.php diff --git a/src/Facades/Generator.php b/src/Facades/Generator.php new file mode 100644 index 00000000..c0d69047 --- /dev/null +++ b/src/Facades/Generator.php @@ -0,0 +1,492 @@ +camel()); + + return ucfirst(str(self::fromCamelCase($string))->singular()->camel()); + } + + /** + * Convert string to singular pascal case. + */ + public static function pascalCase(string $string): string + { + return ucfirst(str(self::fromCamelCase($string))->camel()); + } + + /** + * Convert string to plural pascal case. + */ + public static function pluralPascalCase(string $string): string + { + /** + * check string ended with 'ia' or 'ium' + */ + if (self::checkStringEndWith($string)) return ucfirst(str(self::fromCamelCase($string))->camel()) . 's'; + + return ucfirst(str(self::fromCamelCase($string))->plural()->camel()); + } + + /** + * Convert string to plural snake case. + */ + public static function pluralSnakeCase(string $string): string + { + /** + * check string ended with 'ia' or 'ium' + */ + if (self::checkStringEndWith($string)) return str(self::fromCamelCase($string))->snake()->lower() . 's'; + + return str(self::fromCamelCase($string))->plural()->snake()->lower(); + } + + /** + * Convert string to singular snake case. + */ + public static function singularSnakeCase(string $string): string + { + /** + * check string ended with 'ia' or 'ium' + */ + if (self::checkStringEndWith($string)) return str(self::fromCamelCase($string))->snake()->lower(); + + return str(self::fromCamelCase($string))->singular()->snake()->lower(); + } + + /** + * Convert string to plural pascal case. + */ + public static function pluralCamelCase(string $string): string + { + /** + * check string ended with 'ia' or 'ium' + */ + if (self::checkStringEndWith($string)) return str(self::fromCamelCase($string))->camel() . 's'; + + return str(self::fromCamelCase($string))->plural()->camel(); + } + + /** + * Convert string to singular pascal case. + */ + public static function singularCamelCase(string $string): string + { + /** + * check string ended with 'ia' or 'ium' + */ + if (self::checkStringEndWith($string)) return str(self::fromCamelCase($string))->camel(); + + return str(self::fromCamelCase($string))->singular()->camel(); + } + + /** + * Convert string to plural, kebab case, and lowercase. + */ + public static function pluralKebabCase(string $string): string + { + /** + * check string ended with 'ia' or 'ium' + */ + if (self::checkStringEndWith($string)) return str(preg_replace('/[^A-Za-z0-9() -]/', ' ', self::fromCamelCase($string)))->kebab()->lower() . 's'; + + return str(preg_replace('/[^A-Za-z0-9() -]/', ' ', self::fromCamelCase($string)))->plural()->kebab()->lower(); + } + + /** + * Convert string to kebab case, and lowercase. + */ + public static function kebabCase(string $string): string + { + return str(preg_replace('/[^A-Za-z0-9() -]/', ' ', self::fromCamelCase($string)))->kebab()->lower(); + } + + /** + * Convert string to singular, kebab case, and lowercase. + */ + public static function singularKebabCase(string $string): string + { + /** + * check string ended with 'ia' or 'ium' + */ + if (self::checkStringEndWith($string)) return str(preg_replace('/[^A-Za-z0-9() -]/', ' ', self::fromCamelCase($string)))->kebab()->lower(); + + return str(preg_replace('/[^A-Za-z0-9() -]/', ' ', self::fromCamelCase($string)))->singular()->kebab()->lower(); + } + + /** + * Convert string to singular, remove special characters, and lowercase. + */ + public static function cleanSingularLowerCase(string $string): string + { + /** + * check string ended with 'ia' or 'ium' + */ + if (self::checkStringEndWith($string)) return str(preg_replace('/[^A-Za-z0-9() -]/', ' ', self::fromCamelCase($string)))->lower(); + + return str(preg_replace('/[^A-Za-z0-9() -]/', ' ', self::fromCamelCase($string)))->singular()->lower(); + } + + /** + * Remove special characters, and lowercase. + */ + public static function cleanLowerCase(string $string): string + { + return str(preg_replace('/[^A-Za-z0-9() -]/', ' ', self::fromCamelCase($string)))->lower(); + } + + /** + * Convert string to plural, remove special characters, and uppercase every first letters. + */ + public static function cleanPluralUcWords(string $string): string + { + /** + * check string ended with 'ia' or 'ium' + */ + if (self::checkStringEndWith($string)) return ucwords(str(preg_replace('/[^A-Za-z0-9() -]/', ' ', self::fromCamelCase($string)))->lower()) . 's'; + + return ucwords(str(preg_replace('/[^A-Za-z0-9() -]/', ' ', self::fromCamelCase($string)))->plural()->lower()); + } + + /** + * Convert string to singular, remove special characters, and uppercase every first letters. + */ + public static function cleanSingularUcWords(string $string): string + { + /** + * check string ended with 'ia' or 'ium' + */ + if (self::checkStringEndWith($string)) return ucwords(str(preg_replace('/[^A-Za-z0-9() -]/', ' ', self::fromCamelCase($string)))->lower()); + + return ucwords(str(preg_replace('/[^A-Za-z0-9() -]/', ' ', self::fromCamelCase($string)))->singular()->lower()); + } + + /** + * Remove special characters, and uppercase every first letters. + */ + public static function cleanUcWords(string $string): string + { + return ucwords(preg_replace('/[^A-Za-z0-9() -]/', ' ', self::fromCamelCase($string))); + } + + /** + * Convert string to plural, remove special characters, and lowercase. + */ + public static function cleanPluralLowerCase(string $string): string + { + /** + * check string ended with 'ia' or 'ium' + */ + if (self::checkStringEndWith($string)) return str(preg_replace('/[^A-Za-z0-9() -]/', ' ', self::fromCamelCase($string)))->lower() . 's'; + + return str(preg_replace('/[^A-Za-z0-9() -]/', ' ', self::fromCamelCase($string)))->plural()->lower(); + } + + /** + * Check if the given string ends with 'ia' or 'ium'. + */ + public static function checkStringEndWith(string $string): bool + { + return str_ends_with($string, 'ia') || str_ends_with($string, 'ium'); + } + + /** + * Get 1 column after id on the table. + */ + public static function getColumnAfterId(string $table): string + { + $table = self::pluralSnakeCase($table); + $allColumns = Schema::getColumnListing($table); + + if (sizeof($allColumns) > 0) { + $column = $allColumns[1]; + } else { + $column = "id"; + } + + return $column; + } + + /** + * Select id and column after id on the table. + */ + public static function selectColumnAfterIdAndIdItself(string $table): string + { + $table = self::pluralSnakeCase($table); + $allColumns = Schema::getColumnListing($table); + + if (sizeof($allColumns) > 0) { + $selectedField = "id,$allColumns[1]"; + } else { + $selectedField = "id"; + } + + return $selectedField; + } + + /** + * Get model location or path if contains '/'. + */ + public static function getModelLocation(string $model): string + { + $arrModel = explode('/', $model); + $totalArrModel = count($arrModel); + + /** + * will generate something like: + * Main\Product + */ + $path = ""; + for ($i = 0; $i < $totalArrModel - 1; $i++) { + $path .= self::pluralPascalCase($arrModel[$i]); + if ($i + 1 != $totalArrModel - 1) $path .= "\\"; + } + + return $path; + } + + /** + * Converts camelCase string to have spaces between each. + */ + public static function fromCamelCase(string $string): string + { + $a = preg_split('/(?<=[a-z])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])/x', $string); + + return trim(implode(' ', $a)); + } + + /** + * Set model name from the latest of array(if exists). + */ + public static function setModelName(string $model, string $style = 'pascal case'): string + { + $arrModel = explode('/', $model); + $totalArrModel = count($arrModel); + + /** + * get the latest index value of array + */ + $actualModelName = $arrModel[$totalArrModel - 1]; + + /** + * check string ended with 'ia' or 'ium' + */ + if (str_ends_with($actualModelName, 'ia') || str_ends_with($actualModelName, 'ium')) return self::pascalCase($actualModelName); + + if ($style == 'pascal case') return self::singularPascalCase($actualModelName); + + return $actualModelName; + } + + /** + * Set default image and code to controller. + */ + public static function setDefaultImage(null|string $default, string $field, string $model): array + { + if ($default) { + return [ + 'image' => $default, + /** + * Generated code: + * + * if (!$generator->image || $generator->image == $defaultImage = 'https://raw.githubusercontent.com/laravel/art/master/logo-lockup/5%20SVG/2%20CMYK/1%20Full%20Color/laravel-logolockup-cmyk-red.svg') return $defaultImage; + */ + 'index_code' => "if (!$" . self::singularCamelCase($model) . "->" . str()->snake($field) . " || $" . self::singularCamelCase($model) . "->" . str()->snake($field) . " == \$defaultImage = '" . $default . "') return \$defaultImage;", + /** + * Generated code: + * !$book->cover || $book->cover == 'https://via.placeholder.com/350?text=No+Image+Avaiable'" + */ + 'form_code' => "!$" . self::singularCamelCase($model) . "->" . str()->snake($field) . " || $" . self::singularCamelCase($model) . "->" . str()->snake($field) . " == '" . $default . "'", + ]; + } + + if (config('generator.image.default')) { + return [ + 'image' => config('generator.image.default'), + /** + * Generated code: + * + * if (!$generator->image == null) return 'https://via.placeholder.com/350?text=No+Image+Avaiable'; + */ + 'index_code' => "if (!\$" . self::singularCamelCase($model) . "->" . str()->snake($field) . ") return '" . config('generator.image.default') . "';", + /** + * Generated code: + * + * !$book->photo + */ + 'form_code' => "!$" . self::singularCamelCase($model) . "->" . str()->snake($field), + ]; + } + + return [ + 'image' => 'https://via.placeholder.com/350?text=No+Image+Avaiable', + 'index_code' => "if (!\$" . self::singularCamelCase($model) . "->" . str()->snake($field) . ") return 'https://via.placeholder.com/350?text=No+Image+Avaiable';", + 'form_code' => "!$" . self::singularCamelCase($model) . "->" . str()->snake($field), + ]; + } + + /** + * Convert array from config to string like array. + */ + public static function convertArraySidebarToString(array $sidebars): string + { + $menu = ""; + + foreach ($sidebars as $sidebar) $menu .= "'" . $sidebar . "', "; + + return $menu; + } + + /** + * Check if menu is active. + */ + public static function isActiveMenu(string|array $route): string + { + $activeClass = ' active'; + + if (is_string($route)) { + if (request()->is(substr($route . '*', 1))) return $activeClass; + + if (request()->is(str($route)->slug() . '*')) return $activeClass; + + if (request()->segment(2) == str($route)->before('/')) return $activeClass; + + if (request()->segment(3) == str($route)->after('/')) return $activeClass; + } + + if (is_array($route)) { + foreach ($route as $value) { + $actualRoute = str($value)->remove(' view')->plural(); + + if (request()->is(substr($actualRoute . '*', 1))) return $activeClass; + + if (request()->is(str($actualRoute)->slug() . '*')) return $activeClass; + + if (request()->segment(2) == $actualRoute) return $activeClass; + + if (request()->segment(3) == $actualRoute) return $activeClass; + } + } + + return ''; + } + + /** + * Check if generate api or blade view. + */ + public static function isGenerateApi(): bool + { + return request()->filled('generate_variant') && request()->get('generate_variant') == 'api'; + } + + /** + * Check if package exist in composer. + */ + public static function checkPackage(string $name): bool + { + if (self::getComposerPackage($name) == '{') return false; + + return true; + } + + /** + * Check if package exist in composer and return version. + * @throws \Exception + */ + public static function checkPackageVersion(string $name, bool $strict = false): string + { + $str = self::getComposerPackage($name); + + if (str_contains($str, '{')) { + $message = 'The package ' . $name . ' is not installed.'; + + if ($strict) throw new \Exception($message); + + return $message; + } + + return $str; + } + + /** + * Check package in composer.json + */ + public static function getComposerPackage(string $name): string + { + $composer = file_get_contents(base_path('composer.json')); + + return str($composer)->after('"' . $name . '": "')->before('"'); + } + + /** + * Set disk code for controller. + */ + public static function setDiskCodeForController(string $name): string + { + return match (config('generator.image.disk')) { + // '/images/'; + 's3' => "'/" . self::pluralKebabCase($name) . "/'", + + // 'public_path('uploads/images/'); + 'public' => "public_path('uploads/" . self::pluralKebabCase($name) . "/')", + + // 'storage_path('app/public/uploads/images/'); + default => "storage_path('app/public/uploads/" . self::pluralKebabCase($name) . "/')", + }; + } + + /** + * Set disk code for cast an image. + */ + public static function setDiskCodeForCastImage(string $model, string $field): string + { + return match (config('generator.image.disk')) { + // \Illuminate\Support\Facades\Storage::disk('s3')->url('images/' . $generator->image); + 's3' => "\Illuminate\Support\Facades\Storage::disk('s3')->url(\$this->" . self::singularCamelCase($field) . "Path . $" . self::singularCamelCase($model) . "->" . str($field)->snake() . ")", + + //asset('/uploads/photos/' . $generator->image); + 'public' => "asset('/uploads/" . self::pluralKebabCase($field) . "/' . $" . self::singularCamelCase($model) . "->" . str($field)->snake() . ")", + + //asset('storage/uploads/images/' . $generator->image) + default => "asset('storage/uploads/" . self::pluralKebabCase($field) . "/' . $" . self::singularCamelCase($model) . "->" . str($field)->snake() . ")", + }; + } +} diff --git a/src/Providers/GeneratorServiceProvider.php b/src/Providers/GeneratorServiceProvider.php index 297d4952..16c253ae 100644 --- a/src/Providers/GeneratorServiceProvider.php +++ b/src/Providers/GeneratorServiceProvider.php @@ -4,6 +4,7 @@ use Illuminate\Support\ServiceProvider; use EvdigiIna\Generator\Commands\{SetSidebarType, PublishAllFiles}; +use Generator; class GeneratorServiceProvider extends ServiceProvider { @@ -20,8 +21,8 @@ public function register(): void */ public function boot(): void { - $this->loadRoutesFrom(__DIR__ . '/../Routes/generator.php'); - $this->loadViewsFrom(__DIR__ . '/../Resources/views/generators', 'generator'); + $this->loadRoutesFrom(__DIR__ . '/../../routes/generator.php'); + $this->loadViewsFrom(__DIR__ . '/../../resources/views', 'generator'); $this->mergeConfigFrom(__DIR__ . '/../../stubs/generators/publish/config/full-version/generator.php', 'generator'); // views @@ -101,6 +102,9 @@ public function boot(): void ]); } + $this->app->bind('generator', function($app) { + return new Generator(); + }); if ($this->app->runningInConsole()) $this->commands([PublishAllFiles::class]); diff --git a/stubs/generators/publish/config/full-version/generator.php b/stubs/generators/publish/config/full-version/generator.php index 4849c41e..6b067cb0 100644 --- a/stubs/generators/publish/config/full-version/generator.php +++ b/stubs/generators/publish/config/full-version/generator.php @@ -23,7 +23,7 @@ /** * Crop the uploaded image using intervention image. */ - "crop" => false, + "crop" => true, /** * When set to true the uploaded image aspect ratio will still original. @@ -51,12 +51,12 @@ * - d F Y * - Y m d */ - "date" => "d/m/Y", + "date" => "Y-m-d", /** * If any input type month will cast and display used this format. */ - "month" => "m/Y", + "month" => "Y/m", /** * If any input type time will cast and display used this format. diff --git a/stubs/generators/publish/config/simple-version/generator.php b/stubs/generators/publish/config/simple-version/generator.php index 4849c41e..a1fc5f3d 100644 --- a/stubs/generators/publish/config/simple-version/generator.php +++ b/stubs/generators/publish/config/simple-version/generator.php @@ -23,7 +23,7 @@ /** * Crop the uploaded image using intervention image. */ - "crop" => false, + "crop" => true, /** * When set to true the uploaded image aspect ratio will still original. @@ -51,12 +51,12 @@ * - d F Y * - Y m d */ - "date" => "d/m/Y", + "date" => "Y-m-d", /** * If any input type month will cast and display used this format. */ - "month" => "m/Y", + "month" => "Y/m", /** * If any input type time will cast and display used this format. @@ -73,84 +73,4 @@ */ "limit_text" => 100, ], - - /** - * It will be used for generator to manage and showing menus on sidebar views. - * - * Example: - * [ - * 'header' => 'Main', - * - * // All permissions in menus[] and submenus[] - * 'permissions' => ['test view'], - * - * menus' => [ - * [ - * 'title' => 'Main Data', - * 'icon' => '', - * 'route' => null, - * - * // permission always null when isset submenus - * 'permission' => null, - * - * // All permissions on submenus[] and will empty[] when submenus equals to [] - * 'permissions' => ['test view'], - * - * 'submenus' => [ - * [ - * 'title' => 'Tests', - * 'route' => '/tests', - * 'permission' => 'test view' - * ] - * ], - * ], - * ], - * ], - * - * This code below always changes when you use a generator, and maybe you must format the code. - */ - "sidebars" => [ - [ - "header" => "Main", - "permissions" => ["test view"], - "menus" => [ - [ - "title" => "Main Data", - "icon" => '', - "route" => null, - "permission" => null, - "permissions" => ["test view"], - "submenus" => [ - [ - "title" => "Tests", - "route" => "/tests", - "permission" => "test view", - ], - ], - ], - ], - ], - [ - "header" => "Users", - "permissions" => ["user view", "role & permission view"], - "menus" => [ - [ - "title" => "Users", - "icon" => '', - "route" => "/users", - "permission" => "user view", - "permissions" => [], - "submenus" => [], - ], - [ - "title" => "Roles & permissions", - "icon" => '', - "route" => "/roles", - "permission" => "role & permission view", - "permissions" => [], - "submenus" => [], - ], - ], - ], - ], ]; diff --git a/stubs/generators/publish/controllers/UserController.php b/stubs/generators/publish/controllers/UserController.php index 5cd88365..b873d62b 100644 --- a/stubs/generators/publish/controllers/UserController.php +++ b/stubs/generators/publish/controllers/UserController.php @@ -2,6 +2,7 @@ namespace App\Http\Controllers; +use App\Generators\Services\ImageService; use App\Http\Requests\Users\{StoreUserRequest, UpdateUserRequest}; use App\Models\User; use Yajra\DataTables\Facades\DataTables; @@ -9,19 +10,13 @@ class UserController extends Controller { - /** - * Path for user avatar file. - * - * @var string - */ - protected $avatarPath = '/uploads/images/avatars/'; - - public function __construct() + public function __construct(public ImageService $imageService, public string $avatarPath = '/uploads/images/avatars/') { - $this->middleware('permission:user view')->only('index', 'show'); - $this->middleware('permission:user create')->only('create', 'store'); - $this->middleware('permission:user edit')->only('edit', 'update'); - $this->middleware('permission:user delete')->only('destroy'); + // TODO: uncomment this code if you are using spatie permission + // $this->middleware('permission:user view')->only('index', 'show'); + // $this->middleware('permission:user create')->only('create', 'store'); + // $this->middleware('permission:user edit')->only('edit', 'update'); + // $this->middleware('permission:user delete')->only('destroy'); } /** @@ -64,21 +59,7 @@ public function store(StoreUserRequest $request): \Illuminate\Http\RedirectRespo { $validated = $request->validated(); - if ($request->file('avatar') && $request->file('avatar')->isValid()) { - - $filename = $request->file('avatar')->hashName(); - - if (!file_exists($folder = public_path($this->avatarPath))) { - mkdir($folder, 0777, true); - } - - Image::make($request->file('avatar')->getRealPath())->resize(500, 500, function ($constraint) { - $constraint->aspectRatio(); - $constraint->upsize(); - })->save($this->avatarPath . $filename); - - $validated['avatar'] = $filename; - } + $validated['avatar'] = $this->imageService->upload(name: 'avatar', path: $this->avatarPath, disk: 's3'); $validated['password'] = bcrypt($request->password); @@ -116,29 +97,7 @@ public function update(UpdateUserRequest $request, User $user): \Illuminate\Http { $validated = $request->validated(); - if ($request->file('avatar') && $request->file('avatar')->isValid()) { - - $filename = $request->file('avatar')->hashName(); - - if (!file_exists($folder = public_path($this->avatarPath))) { - mkdir($folder, 0777, true); - } - - Image::make($request->file('avatar')->getRealPath())->resize(500, 500, function ($constraint) { - $constraint->aspectRatio(); - $constraint->upsize(); - })->save(public_path($this->avatarPath) . $filename); - - $oldAvatar = public_path($this->avatarPath . $user->avatar); - - if ($user->avatar != null && file_exists($oldAvatar)) { - unlink($oldAvatar); - } - - $validated['avatar'] = $filename; - } else { - $validated['avatar'] = $user->avatar; - } + $validated['avatar'] = $this->imageService->upload(name: 'avatar', path: $this->avatarPath, defaultImage: $user->avatar, disk: 's3'); switch (is_null($request->password)) { case true: diff --git a/stubs/generators/publish/database/seeders/UserSeeder.php b/stubs/generators/publish/database/seeders/UserSeeder.php index dcfb61a9..d1880a7b 100644 --- a/stubs/generators/publish/database/seeders/UserSeeder.php +++ b/stubs/generators/publish/database/seeders/UserSeeder.php @@ -21,6 +21,6 @@ public function run(): void 'remember_token' => Str::random(10), ]); - User::factory()->count(50)->create(); + User::factory()->count(10)->create(); } } diff --git a/tests/CommandTest.php b/tests/Unit/CommandTest.php similarity index 100% rename from tests/CommandTest.php rename to tests/Unit/CommandTest.php diff --git a/tests/GeneratorTest.php b/tests/Unit/GeneratorTest.php similarity index 100% rename from tests/GeneratorTest.php rename to tests/Unit/GeneratorTest.php diff --git a/tests/GeneratorUtilsTest.php b/tests/Unit/GeneratorUtilsTest.php similarity index 100% rename from tests/GeneratorUtilsTest.php rename to tests/Unit/GeneratorUtilsTest.php diff --git a/tests/HelperTest.php b/tests/Unit/HelperTest.php similarity index 82% rename from tests/HelperTest.php rename to tests/Unit/HelperTest.php index 33fd5e81..522c2b6f 100644 --- a/tests/HelperTest.php +++ b/tests/Unit/HelperTest.php @@ -16,6 +16,6 @@ class HelperTest extends TestCase public function it_helper_file_exists(): void { - $this->assertTrue(file_exists(__DIR__ . '/../src/helper.php')); + $this->assertTrue(file_exists(__DIR__ . '/../../src/helper.php')); } } From 5808bb13bf28b20d2d74d7b61cbfd4a2b41c9c98 Mon Sep 17 00:00:00 2001 From: Mohammad Zulfahmi Date: Wed, 27 Mar 2024 10:47:28 +0700 Subject: [PATCH 053/105] fix wrong namespace in test --- tests/TestCase.php | 22 ++++++++++++++++++++++ tests/Unit/CommandTest.php | 3 ++- tests/Unit/GeneratorTest.php | 3 ++- tests/Unit/GeneratorUtilsTest.php | 3 ++- tests/Unit/HelperTest.php | 3 ++- 5 files changed, 30 insertions(+), 4 deletions(-) diff --git a/tests/TestCase.php b/tests/TestCase.php index b38979bf..cf1617cb 100644 --- a/tests/TestCase.php +++ b/tests/TestCase.php @@ -8,6 +8,10 @@ use Illuminate\Support\Facades\Artisan; use Orchestra\Testbench\Attributes\WithMigration; use PHPUnit\Framework\Attributes\Test; +use Tests\Unit\CommandTest; +use Tests\Unit\GeneratorTest; +use Tests\Unit\GeneratorUtilsTest; +use Tests\Unit\HelperTest; #[WithMigration] class TestCase extends \Orchestra\Testbench\TestCase @@ -78,4 +82,22 @@ public function it_has_generator_utils_test_class() { $this->assertTrue(class_exists(GeneratorUtilsTest::class)); } + + #[Test] + public function it_has_generator_command_test_class() + { + $this->assertTrue(class_exists(CommandTest::class)); + } + + #[Test] + public function it_has_generator_test_class() + { + $this->assertTrue(class_exists(GeneratorTest::class)); + } + + #[Test] + public function it_has_generator_helper_test_class() + { + $this->assertTrue(class_exists(HelperTest::class)); + } } diff --git a/tests/Unit/CommandTest.php b/tests/Unit/CommandTest.php index 9ffb00fc..4db9f1d8 100644 --- a/tests/Unit/CommandTest.php +++ b/tests/Unit/CommandTest.php @@ -1,8 +1,9 @@ Date: Wed, 27 Mar 2024 10:49:54 +0700 Subject: [PATCH 054/105] Update GeneratorTest.php --- tests/Unit/GeneratorTest.php | 1 + 1 file changed, 1 insertion(+) diff --git a/tests/Unit/GeneratorTest.php b/tests/Unit/GeneratorTest.php index da4b013d..a75dfc13 100644 --- a/tests/Unit/GeneratorTest.php +++ b/tests/Unit/GeneratorTest.php @@ -26,6 +26,7 @@ protected function setUp(): void #[Test] public function it_can_render_generator_create_page(): void { + $this->withoutExceptionHandling(); $this->get('/generators/create')->assertStatus(200)->assertSee('Generators'); } From a967eec79b2aee1a418137f35533c3fdfc4d59f6 Mon Sep 17 00:00:00 2001 From: Mohammad Zulfahmi Date: Wed, 27 Mar 2024 11:02:52 +0700 Subject: [PATCH 055/105] fix generatorTest --- src/Http/Middleware/OnlyAvailableInTheFullVersion.php | 4 ++++ tests/Unit/GeneratorTest.php | 3 ++- 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/src/Http/Middleware/OnlyAvailableInTheFullVersion.php b/src/Http/Middleware/OnlyAvailableInTheFullVersion.php index 93995da1..5a0adece 100644 --- a/src/Http/Middleware/OnlyAvailableInTheFullVersion.php +++ b/src/Http/Middleware/OnlyAvailableInTheFullVersion.php @@ -13,6 +13,10 @@ class OnlyAvailableInTheFullVersion */ public function handle(Request $request, Closure $next): mixed { + if($request->has('for_test')) { + return $next($request); + } + $dir = __DIR__ . '/../../../generator-cache'; abort_if(!file_exists($dir), Response::HTTP_FORBIDDEN, 'You have not yet selected a version, to use this feature, you must be running the artisan command: "php artisan generator:install full", and then you can use the full version.'); diff --git a/tests/Unit/GeneratorTest.php b/tests/Unit/GeneratorTest.php index da4b013d..b620368d 100644 --- a/tests/Unit/GeneratorTest.php +++ b/tests/Unit/GeneratorTest.php @@ -26,7 +26,8 @@ protected function setUp(): void #[Test] public function it_can_render_generator_create_page(): void { - $this->get('/generators/create')->assertStatus(200)->assertSee('Generators'); + $this->withoutExceptionHandling(); + $this->get('/generators/create?for_test=true')->assertStatus(200)->assertSee('Generators'); } #[Test] From d0e66c6e24e72bd0c12d8cecd3eeae6bf4b68339 Mon Sep 17 00:00:00 2001 From: Mohammad Zulfahmi Date: Thu, 28 Mar 2024 15:00:00 +0700 Subject: [PATCH 056/105] fix model generator, role permission seeder, etc --- .../publish/utils/GeneratorUtils.php | 492 ------------------ .../Interfaces/GeneratorUtilsInterface.php | 175 ------- 2 files changed, 667 deletions(-) delete mode 100644 stubs/generators/publish/utils/GeneratorUtils.php delete mode 100644 stubs/generators/publish/utils/Interfaces/GeneratorUtilsInterface.php diff --git a/stubs/generators/publish/utils/GeneratorUtils.php b/stubs/generators/publish/utils/GeneratorUtils.php deleted file mode 100644 index 19843632..00000000 --- a/stubs/generators/publish/utils/GeneratorUtils.php +++ /dev/null @@ -1,492 +0,0 @@ -camel()); - - return ucfirst(str(self::fromCamelCase($string))->singular()->camel()); - } - - /** - * Convert string to singular pascal case. - */ - public static function pascalCase(string $string): string - { - return ucfirst(str(self::fromCamelCase($string))->camel()); - } - - /** - * Convert string to plural pascal case. - */ - public static function pluralPascalCase(string $string): string - { - /** - * check string ended with 'ia' or 'ium' - */ - if (self::checkStringEndWith($string)) return ucfirst(str(self::fromCamelCase($string))->camel()) . 's'; - - return ucfirst(str(self::fromCamelCase($string))->plural()->camel()); - } - - /** - * Convert string to plural snake case. - */ - public static function pluralSnakeCase(string $string): string - { - /** - * check string ended with 'ia' or 'ium' - */ - if (self::checkStringEndWith($string)) return str(self::fromCamelCase($string))->snake()->lower() . 's'; - - return str(self::fromCamelCase($string))->plural()->snake()->lower(); - } - - /** - * Convert string to singular snake case. - */ - public static function singularSnakeCase(string $string): string - { - /** - * check string ended with 'ia' or 'ium' - */ - if (self::checkStringEndWith($string)) return str(self::fromCamelCase($string))->snake()->lower(); - - return str(self::fromCamelCase($string))->singular()->snake()->lower(); - } - - /** - * Convert string to plural pascal case. - */ - public static function pluralCamelCase(string $string): string - { - /** - * check string ended with 'ia' or 'ium' - */ - if (self::checkStringEndWith($string)) return str(self::fromCamelCase($string))->camel() . 's'; - - return str(self::fromCamelCase($string))->plural()->camel(); - } - - /** - * Convert string to singular pascal case. - */ - public static function singularCamelCase(string $string): string - { - /** - * check string ended with 'ia' or 'ium' - */ - if (self::checkStringEndWith($string)) return str(self::fromCamelCase($string))->camel(); - - return str(self::fromCamelCase($string))->singular()->camel(); - } - - /** - * Convert string to plural, kebab case, and lowercase. - */ - public static function pluralKebabCase(string $string): string - { - /** - * check string ended with 'ia' or 'ium' - */ - if (self::checkStringEndWith($string)) return str(preg_replace('/[^A-Za-z0-9() -]/', ' ', self::fromCamelCase($string)))->kebab()->lower() . 's'; - - return str(preg_replace('/[^A-Za-z0-9() -]/', ' ', self::fromCamelCase($string)))->plural()->kebab()->lower(); - } - - /** - * Convert string to kebab case, and lowercase. - */ - public static function kebabCase(string $string): string - { - return str(preg_replace('/[^A-Za-z0-9() -]/', ' ', self::fromCamelCase($string)))->kebab()->lower(); - } - - /** - * Convert string to singular, kebab case, and lowercase. - */ - public static function singularKebabCase(string $string): string - { - /** - * check string ended with 'ia' or 'ium' - */ - if (self::checkStringEndWith($string)) return str(preg_replace('/[^A-Za-z0-9() -]/', ' ', self::fromCamelCase($string)))->kebab()->lower(); - - return str(preg_replace('/[^A-Za-z0-9() -]/', ' ', self::fromCamelCase($string)))->singular()->kebab()->lower(); - } - - /** - * Convert string to singular, remove special characters, and lowercase. - */ - public static function cleanSingularLowerCase(string $string): string - { - /** - * check string ended with 'ia' or 'ium' - */ - if (self::checkStringEndWith($string)) return str(preg_replace('/[^A-Za-z0-9() -]/', ' ', self::fromCamelCase($string)))->lower(); - - return str(preg_replace('/[^A-Za-z0-9() -]/', ' ', self::fromCamelCase($string)))->singular()->lower(); - } - - /** - * Remove special characters, and lowercase. - */ - public static function cleanLowerCase(string $string): string - { - return str(preg_replace('/[^A-Za-z0-9() -]/', ' ', self::fromCamelCase($string)))->lower(); - } - - /** - * Convert string to plural, remove special characters, and uppercase every first letters. - */ - public static function cleanPluralUcWords(string $string): string - { - /** - * check string ended with 'ia' or 'ium' - */ - if (self::checkStringEndWith($string)) return ucwords(str(preg_replace('/[^A-Za-z0-9() -]/', ' ', self::fromCamelCase($string)))->lower()) . 's'; - - return ucwords(str(preg_replace('/[^A-Za-z0-9() -]/', ' ', self::fromCamelCase($string)))->plural()->lower()); - } - - /** - * Convert string to singular, remove special characters, and uppercase every first letters. - */ - public static function cleanSingularUcWords(string $string): string - { - /** - * check string ended with 'ia' or 'ium' - */ - if (self::checkStringEndWith($string)) return ucwords(str(preg_replace('/[^A-Za-z0-9() -]/', ' ', self::fromCamelCase($string)))->lower()); - - return ucwords(str(preg_replace('/[^A-Za-z0-9() -]/', ' ', self::fromCamelCase($string)))->singular()->lower()); - } - - /** - * Remove special characters, and uppercase every first letters. - */ - public static function cleanUcWords(string $string): string - { - return ucwords(preg_replace('/[^A-Za-z0-9() -]/', ' ', self::fromCamelCase($string))); - } - - /** - * Convert string to plural, remove special characters, and lowercase. - */ - public static function cleanPluralLowerCase(string $string): string - { - /** - * check string ended with 'ia' or 'ium' - */ - if (self::checkStringEndWith($string)) return str(preg_replace('/[^A-Za-z0-9() -]/', ' ', self::fromCamelCase($string)))->lower() . 's'; - - return str(preg_replace('/[^A-Za-z0-9() -]/', ' ', self::fromCamelCase($string)))->plural()->lower(); - } - - /** - * Check if the given string ends with 'ia' or 'ium'. - */ - public static function checkStringEndWith(string $string): bool - { - return str_ends_with($string, 'ia') || str_ends_with($string, 'ium'); - } - - /** - * Get 1 column after id on the table. - */ - public static function getColumnAfterId(string $table): string - { - $table = self::pluralSnakeCase($table); - $allColumns = Schema::getColumnListing($table); - - if (sizeof($allColumns) > 0) { - $column = $allColumns[1]; - } else { - $column = "id"; - } - - return $column; - } - - /** - * Select id and column after id on the table. - */ - public static function selectColumnAfterIdAndIdItself(string $table): string - { - $table = self::pluralSnakeCase($table); - $allColumns = Schema::getColumnListing($table); - - if (sizeof($allColumns) > 0) { - $selectedField = "id,$allColumns[1]"; - } else { - $selectedField = "id"; - } - - return $selectedField; - } - - /** - * Get model location or path if contains '/'. - */ - public static function getModelLocation(string $model): string - { - $arrModel = explode('/', $model); - $totalArrModel = count($arrModel); - - /** - * will generate something like: - * Main\Product - */ - $path = ""; - for ($i = 0; $i < $totalArrModel - 1; $i++) { - $path .= self::pluralPascalCase($arrModel[$i]); - if ($i + 1 != $totalArrModel - 1) $path .= "\\"; - } - - return $path; - } - - /** - * Converts camelCase string to have spaces between each. - */ - public static function fromCamelCase(string $string): string - { - $a = preg_split('/(?<=[a-z])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])/x', $string); - - return trim(implode(' ', $a)); - } - - /** - * Set model name from the latest of array(if exists). - */ - public static function setModelName(string $model, string $style = 'pascal case'): string - { - $arrModel = explode('/', $model); - $totalArrModel = count($arrModel); - - /** - * get the latest index value of array - */ - $actualModelName = $arrModel[$totalArrModel - 1]; - - /** - * check string ended with 'ia' or 'ium' - */ - if (str_ends_with($actualModelName, 'ia') || str_ends_with($actualModelName, 'ium')) return self::pascalCase($actualModelName); - - if ($style == 'pascal case') return self::singularPascalCase($actualModelName); - - return $actualModelName; - } - - /** - * Set default image and code to controller. - */ - public static function setDefaultImage(null|string $default, string $field, string $model): array - { - if ($default) { - return [ - 'image' => $default, - /** - * Generated code: - * - * if (!$generator->image || $generator->image == $defaultImage = 'https://raw.githubusercontent.com/laravel/art/master/logo-lockup/5%20SVG/2%20CMYK/1%20Full%20Color/laravel-logolockup-cmyk-red.svg') return $defaultImage; - */ - 'index_code' => "if (!$" . self::singularCamelCase($model) . "->" . str()->snake($field) . " || $" . self::singularCamelCase($model) . "->" . str()->snake($field) . " == \$defaultImage = '" . $default . "') return \$defaultImage;", - /** - * Generated code: - * !$book->cover || $book->cover == 'https://via.placeholder.com/350?text=No+Image+Avaiable'" - */ - 'form_code' => "!$" . self::singularCamelCase($model) . "->" . str()->snake($field) . " || $" . self::singularCamelCase($model) . "->" . str()->snake($field) . " == '" . $default . "'", - ]; - } - - if (config('generator.image.default')) { - return [ - 'image' => config('generator.image.default'), - /** - * Generated code: - * - * if (!$generator->image == null) return 'https://via.placeholder.com/350?text=No+Image+Avaiable'; - */ - 'index_code' => "if (!\$" . self::singularCamelCase($model) . "->" . str()->snake($field) . ") return '" . config('generator.image.default') . "';", - /** - * Generated code: - * - * !$book->photo - */ - 'form_code' => "!$" . self::singularCamelCase($model) . "->" . str()->snake($field), - ]; - } - - return [ - 'image' => 'https://via.placeholder.com/350?text=No+Image+Avaiable', - 'index_code' => "if (!\$" . self::singularCamelCase($model) . "->" . str()->snake($field) . ") return 'https://via.placeholder.com/350?text=No+Image+Avaiable';", - 'form_code' => "!$" . self::singularCamelCase($model) . "->" . str()->snake($field), - ]; - } - - /** - * Convert array from config to string like array. - */ - public static function convertArraySidebarToString(array $sidebars): string - { - $menu = ""; - - foreach ($sidebars as $sidebar) $menu .= "'" . $sidebar . "', "; - - return $menu; - } - - /** - * Check if menu is active. - */ - public static function isActiveMenu(string|array $route): string - { - $activeClass = ' active'; - - if (is_string($route)) { - if (request()->is(substr($route . '*', 1))) return $activeClass; - - if (request()->is(str($route)->slug() . '*')) return $activeClass; - - if (request()->segment(2) == str($route)->before('/')) return $activeClass; - - if (request()->segment(3) == str($route)->after('/')) return $activeClass; - } - - if (is_array($route)) { - foreach ($route as $value) { - $actualRoute = str($value)->remove(' view')->plural(); - - if (request()->is(substr($actualRoute . '*', 1))) return $activeClass; - - if (request()->is(str($actualRoute)->slug() . '*')) return $activeClass; - - if (request()->segment(2) == $actualRoute) return $activeClass; - - if (request()->segment(3) == $actualRoute) return $activeClass; - } - } - - return ''; - } - - /** - * Check if generate api or blade view. - */ - public static function isGenerateApi(): bool - { - return request()->filled('generate_variant') && request()->get('generate_variant') == 'api'; - } - - /** - * Check if package exist in composer. - */ - public static function checkPackage(string $name): bool - { - if (self::getComposerPackage($name) == '{') return false; - - return true; - } - - /** - * Check if package exist in composer and return version. - * @throws \Exception - */ - public static function checkPackageVersion(string $name, bool $strict = false): string - { - $str = self::getComposerPackage($name); - - if (str_contains($str, '{')) { - $message = 'The package ' . $name . ' is not installed.'; - - if ($strict) throw new \Exception($message); - - return $message; - } - - return $str; - } - - /** - * Check package in composer.json - */ - public static function getComposerPackage(string $name): string - { - $composer = file_get_contents(base_path('composer.json')); - - return str($composer)->after('"' . $name . '": "')->before('"'); - } - - /** - * Set disk code for controller. - */ - public static function setDiskCodeForController(string $name): string - { - return match (config('generator.image.disk')) { - // '/images/'; - 's3' => "'/" . self::pluralKebabCase($name) . "/'", - - // 'public_path('uploads/images/'); - 'public' => "public_path('uploads/" . self::pluralKebabCase($name) . "/')", - - // 'storage_path('app/public/uploads/images/'); - default => "storage_path('app/public/uploads/" . self::pluralKebabCase($name) . "/')", - }; - } - - /** - * Set disk code for cast an image. - */ - public static function setDiskCodeForCastImage(string $model, string $field): string - { - return match (config('generator.image.disk')) { - // \Illuminate\Support\Facades\Storage::disk('s3')->url('images/' . $generator->image); - 's3' => "\Illuminate\Support\Facades\Storage::disk('s3')->url(\$this->" . self::singularCamelCase($field) . "Path . $" . self::singularCamelCase($model) . "->" . str($field)->snake() . ")", - - //asset('/uploads/photos/' . $generator->image); - 'public' => "asset('/uploads/" . self::pluralKebabCase($field) . "/' . $" . self::singularCamelCase($model) . "->" . str($field)->snake() . ")", - - //asset('storage/uploads/images/' . $generator->image) - default => "asset('storage/uploads/" . self::pluralKebabCase($field) . "/' . $" . self::singularCamelCase($model) . "->" . str($field)->snake() . ")", - }; - } -} - diff --git a/stubs/generators/publish/utils/Interfaces/GeneratorUtilsInterface.php b/stubs/generators/publish/utils/Interfaces/GeneratorUtilsInterface.php deleted file mode 100644 index 83697553..00000000 --- a/stubs/generators/publish/utils/Interfaces/GeneratorUtilsInterface.php +++ /dev/null @@ -1,175 +0,0 @@ - Date: Thu, 28 Mar 2024 15:00:57 +0700 Subject: [PATCH 057/105] fix model name, role permission seeder, etc --- .gitignore | 2 +- src/Commands/PublishAllFiles.php | 5 +- src/Generators/FactoryGenerator.php | 1 + src/Generators/ModelGenerator.php | 2 +- src/Generators/PermissionGenerator.php | 19 +++---- .../OnlyAvailableInTheFullVersion.php | 2 +- src/Providers/GeneratorServiceProvider.php | 13 +++-- stubs/generators/factory.stub | 3 -- .../publish/models/full-version/User.php | 49 +++++++++++++++++++ .../models/{ => simple-version}/User.php | 10 ---- tests/Unit/GeneratorTest.php | 4 +- 11 files changed, 75 insertions(+), 35 deletions(-) create mode 100644 stubs/generators/publish/models/full-version/User.php rename stubs/generators/publish/models/{ => simple-version}/User.php (74%) diff --git a/.gitignore b/.gitignore index 80df86f3..6e2473e5 100644 --- a/.gitignore +++ b/.gitignore @@ -3,7 +3,7 @@ composer.lock .phpunit.result.cache generator-cache.json -generator-cache +generator.cache .idea .phpunit.cache .phpunit.result.cache diff --git a/src/Commands/PublishAllFiles.php b/src/Commands/PublishAllFiles.php index 3a41c3ff..64d3c4ef 100644 --- a/src/Commands/PublishAllFiles.php +++ b/src/Commands/PublishAllFiles.php @@ -97,6 +97,7 @@ public function handle(): void $this->info('Installing the simple version...'); Artisan::call('vendor:publish --tag=generator-config-simple'); + Artisan::call('vendor:publish --tag=generator-model-simple'); Artisan::call('vendor:publish --tag=generator-view-provider'); Artisan::call('vendor:publish --provider="Intervention\Image\Laravel\ServiceProvider"'); Artisan::call('vendor:publish --tag=datatables'); @@ -115,7 +116,7 @@ public function handle(): void * */ public function totalRunningCommand(string $type = 'full_version_publish_count'): array { - $dir = __DIR__ . '/../../generator-cache'; + $dir = __DIR__ . '/../../generator.cache'; if (!file_exists($dir)) { file_put_contents( @@ -191,7 +192,7 @@ public function runPublishAll(): void Artisan::call('vendor:publish --tag=generator-provider --force'); Artisan::call('vendor:publish --tag=generator-migration --force'); Artisan::call('vendor:publish --tag=generator-seeder --force'); - Artisan::call('vendor:publish --tag=generator-model --force'); + Artisan::call('vendor:publish --tag=generator-model-full --force'); Artisan::call('vendor:publish --tag=generator-assets --force'); Artisan::call('vendor:publish --tag=generator-utils --force'); Artisan::call('vendor:publish --provider="Intervention\Image\Laravel\ServiceProvider"'); diff --git a/src/Generators/FactoryGenerator.php b/src/Generators/FactoryGenerator.php index f5572095..5b8d16e3 100644 --- a/src/Generators/FactoryGenerator.php +++ b/src/Generators/FactoryGenerator.php @@ -12,6 +12,7 @@ public function generate(array $request): void $fields = ""; $totalField = count($request['fields']); + foreach ($request['fields'] as $i => $field) { $fields .= "// '" . $field ."' => "; $fields .= $request['requireds'][$i] == 'yes' ? "\$this->faker->" : "null"; diff --git a/src/Generators/ModelGenerator.php b/src/Generators/ModelGenerator.php index 0ed0dbac..639e93c3 100644 --- a/src/Generators/ModelGenerator.php +++ b/src/Generators/ModelGenerator.php @@ -124,7 +124,7 @@ public function generate(array $request): void } $casts .= << 'datetime:$dateTimeFormat', 'updated_at' => 'datetime:$dateTimeFormat'] + 'created_at' => 'datetime:$dateTimeFormat', 'updated_at' => 'datetime:$dateTimeFormat' PHP; $casts .= "]"; diff --git a/src/Generators/PermissionGenerator.php b/src/Generators/PermissionGenerator.php index 70b4f615..b69229fa 100644 --- a/src/Generators/PermissionGenerator.php +++ b/src/Generators/PermissionGenerator.php @@ -65,29 +65,26 @@ protected function insertRoleAndPermissions(string $model): void $permissions = [ [ 'name' => "$model view", - 'guard_name' => GeneratorUtils::isGenerateApi() ? 'api' : 'web' + 'guard_name' => 'web' ], [ 'name' => "$model create", - 'guard_name' => GeneratorUtils::isGenerateApi() ? 'api' : 'web' + 'guard_name' => 'web' ], [ 'name' => "$model edit", - 'guard_name' => GeneratorUtils::isGenerateApi() ? 'api' : 'web' + 'guard_name' => 'web' ], [ 'name' => "$model delete", - 'guard_name' => GeneratorUtils::isGenerateApi() ? 'api' : 'web' + 'guard_name' => 'web' ] ]; - foreach ($permissions as $permission) Permission::firstOrCreate($permission); + foreach ($permissions as $p) { + $permission = Permission::firstOrCreate($p); - $role->givePermissionTo([ - "$model view", - "$model create", - "$model edit", - "$model delete" - ]); + $role->givePermissionTo($permission); + } } } diff --git a/src/Http/Middleware/OnlyAvailableInTheFullVersion.php b/src/Http/Middleware/OnlyAvailableInTheFullVersion.php index 5a0adece..478b1087 100644 --- a/src/Http/Middleware/OnlyAvailableInTheFullVersion.php +++ b/src/Http/Middleware/OnlyAvailableInTheFullVersion.php @@ -17,7 +17,7 @@ public function handle(Request $request, Closure $next): mixed return $next($request); } - $dir = __DIR__ . '/../../../generator-cache'; + $dir = __DIR__ . '/../../../generator.cache'; abort_if(!file_exists($dir), Response::HTTP_FORBIDDEN, 'You have not yet selected a version, to use this feature, you must be running the artisan command: "php artisan generator:install full", and then you can use the full version.'); diff --git a/src/Providers/GeneratorServiceProvider.php b/src/Providers/GeneratorServiceProvider.php index 16c253ae..78001ff5 100644 --- a/src/Providers/GeneratorServiceProvider.php +++ b/src/Providers/GeneratorServiceProvider.php @@ -81,8 +81,13 @@ public function boot(): void // Model $this->publishes([ - __DIR__ . '/../../stubs/generators/publish/models/User.php' => app_path('Models/User.php') - ], 'generator-model'); + __DIR__ . '/../../stubs/generators/publish/models/full-version/User.php' => app_path('Models/User.php') + ], 'generator-model-full'); + + // Model + $this->publishes([ + __DIR__ . '/../../stubs/generators/publish/models/simple-version/User.php' => app_path('Models/User.php') + ], 'generator-model-simple'); // asset/mazer template $this->publishes([ @@ -98,11 +103,11 @@ public function boot(): void 'Version' => '0.3.0', 'Source' => 'https://github.com/evdigiina/generator', 'Docs' => 'https://evdigi-ina.github.io/generator-docs', - 'About' => 'Package for building basic CRUD, especially for your main data.' + 'About' => 'Package for building basic CRUD, specially for your main data.' ]); } - $this->app->bind('generator', function($app) { + $this->app->bind('generator', function () { return new Generator(); }); diff --git a/stubs/generators/factory.stub b/stubs/generators/factory.stub index 5bc74e6e..d3c0fac2 100644 --- a/stubs/generators/factory.stub +++ b/stubs/generators/factory.stub @@ -5,9 +5,6 @@ namespace Database\Factories; use {{modelPath}}; use Illuminate\Database\Eloquent\Factories\Factory; -/** - * @extends \Illuminate\Database\Eloquent\Factories\Factory<\App\Models\Customer> - */ class {{modelNameSingularPascalCase}}Factory extends Factory { protected $model = {{modelNameSingularPascalCase}}::class; diff --git a/stubs/generators/publish/models/full-version/User.php b/stubs/generators/publish/models/full-version/User.php new file mode 100644 index 00000000..137162a6 --- /dev/null +++ b/stubs/generators/publish/models/full-version/User.php @@ -0,0 +1,49 @@ + 'datetime:d/m/Y H:i', + 'created_at' => 'datetime:d/m/Y H:i', + 'updated_at' => 'datetime:d/m/Y H:i', + ]; +} diff --git a/stubs/generators/publish/models/User.php b/stubs/generators/publish/models/simple-version/User.php similarity index 74% rename from stubs/generators/publish/models/User.php rename to stubs/generators/publish/models/simple-version/User.php index 2ebd4553..f9e3b158 100644 --- a/stubs/generators/publish/models/User.php +++ b/stubs/generators/publish/models/simple-version/User.php @@ -2,25 +2,15 @@ namespace App\Models; -// use Illuminate\Contracts\Auth\MustVerifyEmail; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Foundation\Auth\User as Authenticatable; use Illuminate\Notifications\Notifiable; -// use Laravel\Sanctum\HasApiTokens; use Laravel\Fortify\TwoFactorAuthenticatable; -// use Spatie\Permission\Traits\HasRoles; class User extends Authenticatable { use HasFactory, Notifiable, TwoFactorAuthenticatable; - // for laravel 11 & you want to create an api - // use HasApiTokens; - - // if you are using spatie/permission - // https://laravel.com/docs/11.x/sanctum#introduction - // use HasRoles; - /** * The attributes that are mass assignable. * diff --git a/tests/Unit/GeneratorTest.php b/tests/Unit/GeneratorTest.php index a75dfc13..ae2832a8 100644 --- a/tests/Unit/GeneratorTest.php +++ b/tests/Unit/GeneratorTest.php @@ -15,11 +15,11 @@ protected function setUp(): void parent::setUp(); $this->afterApplicationCreated(function () { - file_put_contents(__DIR__ . '/../generator-cache', '{"simple_version_publish_count":0,"full_version_publish_count":1}'); + file_put_contents(__DIR__ . '/../generator.cache', '{"simple_version_publish_count":0,"full_version_publish_count":1}'); }); $this->beforeApplicationDestroyed(function () { - file_put_contents(__DIR__ . '/../generator-cache', '{"simple_version_publish_count":0,"full_version_publish_count":1}'); + file_put_contents(__DIR__ . '/../generator.cache', '{"simple_version_publish_count":0,"full_version_publish_count":1}'); }); } From 2d078778d73528f5270885fe016489976e5ff800 Mon Sep 17 00:00:00 2001 From: Mohammad Zulfahmi Date: Sat, 30 Mar 2024 08:46:58 +0700 Subject: [PATCH 058/105] move out database folder :hammer: --- ..._add_two_factor_columns_to_users_table.php | 0 ...01_12_072103_add_avatar_to_users_table.php | 0 ..._01_12_130803_create_permission_tables.php | 0 .../seeders/DatabaseSeeder.php | 0 .../seeders/RoleAndPermissionSeeder.php | 0 .../seeders/UserSeeder.php | 0 src/Commands/PublishAllFiles.php | 13 ++-- .../OnlyAvailableInTheFullVersion.php | 2 +- src/Providers/GeneratorServiceProvider.php | 4 +- stubs/generators/publish/Kernel.php | 70 ------------------- .../publish/bootstrap/full-version/app.php | 27 +++++++ .../publish/bootstrap/simple-version/app.php | 22 ++++++ .../publish/models/full-version/User.php | 12 ++-- .../full-version/RouteServiceProvider.php | 34 --------- .../publish/views/layouts/header.blade.php | 2 +- tests/Unit/GeneratorTest.php | 6 +- .../resources/views/layouts/header.blade.php | 15 ++-- 17 files changed, 77 insertions(+), 130 deletions(-) rename {stubs/generators/publish/database => database}/migrations/2014_10_12_200000_add_two_factor_columns_to_users_table.php (100%) rename {stubs/generators/publish/database => database}/migrations/2022_01_12_072103_add_avatar_to_users_table.php (100%) rename {stubs/generators/publish/database => database}/migrations/2022_01_12_130803_create_permission_tables.php (100%) rename {stubs/generators/publish/database => database}/seeders/DatabaseSeeder.php (100%) rename {stubs/generators/publish/database => database}/seeders/RoleAndPermissionSeeder.php (100%) rename {stubs/generators/publish/database => database}/seeders/UserSeeder.php (100%) delete mode 100644 stubs/generators/publish/Kernel.php create mode 100644 stubs/generators/publish/bootstrap/full-version/app.php create mode 100644 stubs/generators/publish/bootstrap/simple-version/app.php delete mode 100644 stubs/generators/publish/providers/full-version/RouteServiceProvider.php diff --git a/stubs/generators/publish/database/migrations/2014_10_12_200000_add_two_factor_columns_to_users_table.php b/database/migrations/2014_10_12_200000_add_two_factor_columns_to_users_table.php similarity index 100% rename from stubs/generators/publish/database/migrations/2014_10_12_200000_add_two_factor_columns_to_users_table.php rename to database/migrations/2014_10_12_200000_add_two_factor_columns_to_users_table.php diff --git a/stubs/generators/publish/database/migrations/2022_01_12_072103_add_avatar_to_users_table.php b/database/migrations/2022_01_12_072103_add_avatar_to_users_table.php similarity index 100% rename from stubs/generators/publish/database/migrations/2022_01_12_072103_add_avatar_to_users_table.php rename to database/migrations/2022_01_12_072103_add_avatar_to_users_table.php diff --git a/stubs/generators/publish/database/migrations/2022_01_12_130803_create_permission_tables.php b/database/migrations/2022_01_12_130803_create_permission_tables.php similarity index 100% rename from stubs/generators/publish/database/migrations/2022_01_12_130803_create_permission_tables.php rename to database/migrations/2022_01_12_130803_create_permission_tables.php diff --git a/stubs/generators/publish/database/seeders/DatabaseSeeder.php b/database/seeders/DatabaseSeeder.php similarity index 100% rename from stubs/generators/publish/database/seeders/DatabaseSeeder.php rename to database/seeders/DatabaseSeeder.php diff --git a/stubs/generators/publish/database/seeders/RoleAndPermissionSeeder.php b/database/seeders/RoleAndPermissionSeeder.php similarity index 100% rename from stubs/generators/publish/database/seeders/RoleAndPermissionSeeder.php rename to database/seeders/RoleAndPermissionSeeder.php diff --git a/stubs/generators/publish/database/seeders/UserSeeder.php b/database/seeders/UserSeeder.php similarity index 100% rename from stubs/generators/publish/database/seeders/UserSeeder.php rename to database/seeders/UserSeeder.php diff --git a/src/Commands/PublishAllFiles.php b/src/Commands/PublishAllFiles.php index 64d3c4ef..fb1ed376 100644 --- a/src/Commands/PublishAllFiles.php +++ b/src/Commands/PublishAllFiles.php @@ -64,14 +64,14 @@ public function handle(): void } if ($this->confirm('Do you wish to continue? This command may overwrite several files.')) { + if ($totalRunningCommand['full_version_publish_count'] == 1 || $totalRunningCommand['full_version_publish_count'] > 1) { - switch ($this->confirm('Do you wish to continue? you are already running this command ' . $totalRunningCommand['full_version_publish_count'] . ' times.')) { - case true: - $this->runPublishAll(); - break; - default: - break; + + if ($this->confirm('Do you wish to continue? you are already running this command ' . $totalRunningCommand['full_version_publish_count'] . ' for times.')) { + $this->runPublishAll(); + return; } + } $this->runPublishAll(); @@ -205,4 +205,3 @@ public function runPublishAll(): void $this->info('Installed successfully.'); } } - diff --git a/src/Http/Middleware/OnlyAvailableInTheFullVersion.php b/src/Http/Middleware/OnlyAvailableInTheFullVersion.php index 478b1087..ed4f4123 100644 --- a/src/Http/Middleware/OnlyAvailableInTheFullVersion.php +++ b/src/Http/Middleware/OnlyAvailableInTheFullVersion.php @@ -13,7 +13,7 @@ class OnlyAvailableInTheFullVersion */ public function handle(Request $request, Closure $next): mixed { - if($request->has('for_test')) { + if($request->has('for_test') || $request->filled('for_test')) { return $next($request); } diff --git a/src/Providers/GeneratorServiceProvider.php b/src/Providers/GeneratorServiceProvider.php index 78001ff5..eebab334 100644 --- a/src/Providers/GeneratorServiceProvider.php +++ b/src/Providers/GeneratorServiceProvider.php @@ -71,12 +71,12 @@ public function boot(): void // Migrations $this->publishes([ - __DIR__ . '/../../stubs/generators/publish/database/migrations' => database_path('migrations') + __DIR__ . '/../../database/migrations' => database_path('migrations') ], 'generator-migration'); // Seeder $this->publishes([ - __DIR__ . '/../../stubs/generators/publish/database/seeders' => database_path('seeders') + __DIR__ . '/../../database/seeders' => database_path('seeders') ], 'generator-seeder'); // Model diff --git a/stubs/generators/publish/Kernel.php b/stubs/generators/publish/Kernel.php deleted file mode 100644 index fccb5c87..00000000 --- a/stubs/generators/publish/Kernel.php +++ /dev/null @@ -1,70 +0,0 @@ - - */ - protected $middleware = [ - // \App\Http\Middleware\TrustHosts::class, - \App\Http\Middleware\TrustProxies::class, - \Illuminate\Http\Middleware\HandleCors::class, - \App\Http\Middleware\PreventRequestsDuringMaintenance::class, - \Illuminate\Foundation\Http\Middleware\ValidatePostSize::class, - \App\Http\Middleware\TrimStrings::class, - \Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class, - ]; - - /** - * The application's route middleware groups. - * - * @var array> - */ - protected $middlewareGroups = [ - 'web' => [ - \App\Http\Middleware\EncryptCookies::class, - \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class, - \Illuminate\Session\Middleware\StartSession::class, - \Illuminate\View\Middleware\ShareErrorsFromSession::class, - \App\Http\Middleware\VerifyCsrfToken::class, - \Illuminate\Routing\Middleware\SubstituteBindings::class, - ], - - 'api' => [ - // \Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class, - 'throttle:api', - \Illuminate\Routing\Middleware\SubstituteBindings::class, - ], - ]; - - /** - * The application's route middleware. - * - * These middleware may be assigned to groups or used individually. - * - * @var array - */ - protected $routeMiddleware = [ - 'auth' => \App\Http\Middleware\Authenticate::class, - 'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class, - 'auth.session' => \Illuminate\Session\Middleware\AuthenticateSession::class, - 'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class, - 'can' => \Illuminate\Auth\Middleware\Authorize::class, - 'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class, - 'password.confirm' => \Illuminate\Auth\Middleware\RequirePassword::class, - 'signed' => \App\Http\Middleware\ValidateSignature::class, - 'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class, - 'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class, - 'role' => \Spatie\Permission\Middleware\RoleMiddleware::class, - 'permission' => \Spatie\Permission\Middleware\PermissionMiddleware::class, - 'role_or_permission' => \Spatie\Permission\Middleware\RoleOrPermissionMiddleware::class, - ]; -} diff --git a/stubs/generators/publish/bootstrap/full-version/app.php b/stubs/generators/publish/bootstrap/full-version/app.php new file mode 100644 index 00000000..bc3ddf27 --- /dev/null +++ b/stubs/generators/publish/bootstrap/full-version/app.php @@ -0,0 +1,27 @@ +withRouting( + web: __DIR__ . '/../routes/web.php', + commands: __DIR__ . '/../routes/console.php', + health: '/up', + ) + ->withProviders([ + FortifyServiceProvider::class, + ViewComposerServiceProvider::class, + ]) + ->withMiddleware(function (Middleware $middleware) { + $middleware->alias([ + 'role' => RoleMiddleware::class, + 'permission' => PermissionMiddleware::class, + 'role_or_permission' => RoleOrPermissionMiddleware::class, + ]); + }) + ->withExceptions(function (Exceptions $exceptions) { + // + })->create(); diff --git a/stubs/generators/publish/bootstrap/simple-version/app.php b/stubs/generators/publish/bootstrap/simple-version/app.php new file mode 100644 index 00000000..eb595f46 --- /dev/null +++ b/stubs/generators/publish/bootstrap/simple-version/app.php @@ -0,0 +1,22 @@ +withRouting( + web: __DIR__ . '/../routes/web.php', + commands: __DIR__ . '/../routes/console.php', + health: '/up', + ) + ->withProviders([ + ViewComposerServiceProvider::class, + ]) + ->withMiddleware(function (Middleware $middleware) { + // + }) + ->withExceptions(function (Exceptions $exceptions) { + // + })->create(); diff --git a/stubs/generators/publish/models/full-version/User.php b/stubs/generators/publish/models/full-version/User.php index 137162a6..d11cfdf0 100644 --- a/stubs/generators/publish/models/full-version/User.php +++ b/stubs/generators/publish/models/full-version/User.php @@ -6,13 +6,15 @@ use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Foundation\Auth\User as Authenticatable; use Illuminate\Notifications\Notifiable; -use Laravel\Sanctum\HasApiTokens; use Laravel\Fortify\TwoFactorAuthenticatable; use Spatie\Permission\Traits\HasRoles; class User extends Authenticatable { - use HasApiTokens, HasFactory, Notifiable, TwoFactorAuthenticatable, HasRoles; + // https://laravel.com/docs/11.x/sanctum#api-token-authentication + // use \Laravel\Sanctum\HasApiTokens; + + use HasFactory, Notifiable, TwoFactorAuthenticatable, HasRoles; /** * The attributes that are mass assignable. @@ -42,8 +44,8 @@ class User extends Authenticatable * @var array */ protected $casts = [ - 'email_verified_at' => 'datetime:d/m/Y H:i', - 'created_at' => 'datetime:d/m/Y H:i', - 'updated_at' => 'datetime:d/m/Y H:i', + 'email_verified_at' => 'datetime:Y-m-d H:i', + 'created_at' => 'datetime:Y-m-d H:i', + 'updated_at' => 'datetime:Y-m-d H:i', ]; } diff --git a/stubs/generators/publish/providers/full-version/RouteServiceProvider.php b/stubs/generators/publish/providers/full-version/RouteServiceProvider.php deleted file mode 100644 index bfaa2fec..00000000 --- a/stubs/generators/publish/providers/full-version/RouteServiceProvider.php +++ /dev/null @@ -1,34 +0,0 @@ - Limit::perMinute(60)->by($request->user()?->id ?: $request->ip())); - - $this->routes(function () { - Route::middleware('api')->prefix('api')->group(base_path('routes/api.php')); - - Route::middleware('web')->group(base_path('routes/web.php')); - }); - } -} diff --git a/stubs/generators/publish/views/layouts/header.blade.php b/stubs/generators/publish/views/layouts/header.blade.php index 76a670d0..d2ccc9fa 100644 --- a/stubs/generators/publish/views/layouts/header.blade.php +++ b/stubs/generators/publish/views/layouts/header.blade.php @@ -58,7 +58,7 @@
    {{ auth()?->user()?->name }}

    - {{ auth()?->user()?->roles[0]->name }} + {{ isset(auth()?->user()?->roles) ? implode(auth()?->user()?->roles?->map(fn ($role) => $role->name)->toArray()) : '-' }}

    diff --git a/tests/Unit/GeneratorTest.php b/tests/Unit/GeneratorTest.php index ae2832a8..201fdc8a 100644 --- a/tests/Unit/GeneratorTest.php +++ b/tests/Unit/GeneratorTest.php @@ -15,11 +15,11 @@ protected function setUp(): void parent::setUp(); $this->afterApplicationCreated(function () { - file_put_contents(__DIR__ . '/../generator.cache', '{"simple_version_publish_count":0,"full_version_publish_count":1}'); + file_put_contents(__DIR__ . '/../generator.cache', '{"simple_version_publish_count":0,"full_version_publish_count":2}'); }); $this->beforeApplicationDestroyed(function () { - file_put_contents(__DIR__ . '/../generator.cache', '{"simple_version_publish_count":0,"full_version_publish_count":1}'); + file_put_contents(__DIR__ . '/../generator.cache', '{"simple_version_publish_count":0,"full_version_publish_count":2}'); }); } @@ -27,7 +27,7 @@ protected function setUp(): void public function it_can_render_generator_create_page(): void { $this->withoutExceptionHandling(); - $this->get('/generators/create')->assertStatus(200)->assertSee('Generators'); + $this->get('/generators/create?for_test=1')->assertStatus(200)->assertSee('Generators'); } #[Test] diff --git a/workbench/resources/views/layouts/header.blade.php b/workbench/resources/views/layouts/header.blade.php index b8983888..d2ccc9fa 100644 --- a/workbench/resources/views/layouts/header.blade.php +++ b/workbench/resources/views/layouts/header.blade.php @@ -56,17 +56,18 @@
    - + diff --git a/stubs/generators/views/simple/edit.stub b/stubs/generators/views/simple/edit.stub index 44251582..cec49e94 100644 --- a/stubs/generators/views/simple/edit.stub +++ b/stubs/generators/views/simple/edit.stub @@ -5,7 +5,9 @@ {{modelNamePluralUcWords}} Edit - {{ config('app.name', 'Laravel') }} - + +
    @@ -28,6 +30,8 @@
    - + diff --git a/stubs/generators/views/simple/index.stub b/stubs/generators/views/simple/index.stub index 34857eee..6c2f170c 100644 --- a/stubs/generators/views/simple/index.stub +++ b/stubs/generators/views/simple/index.stub @@ -5,8 +5,12 @@ {{modelNamePluralUcWords}} - {{ config('app.name', 'Laravel') }} - + + + + @@ -25,7 +29,7 @@ {{ __('Create a new {{modelNameSingularLowerCase}}') }} - +
    @@ -41,9 +45,14 @@ - + + + + + diff --git a/testbench.yaml b/testbench.yaml index 4e2a738d..748545c4 100644 --- a/testbench.yaml +++ b/testbench.yaml @@ -1,6 +1,6 @@ providers: - Workbench\App\Providers\WorkbenchServiceProvider - - Workbench\App\Providers\ViewComposerServiceProvider + # - Workbench\App\Providers\ViewComposerServiceProvider - EvdigiIna\Generator\Providers\GeneratorServiceProvider migrations: @@ -12,10 +12,10 @@ seeders: workbench: start: '/' install: true - health: false + health: true discovers: web: true - api: false + api: true commands: true components: true views: true diff --git a/tests/Feature/.gitkeep b/tests/Feature/.gitkeep new file mode 100644 index 00000000..e69de29b diff --git a/tests/Unit/GeneratorTest.php b/tests/Unit/GeneratorTest.php index 201fdc8a..204ce125 100644 --- a/tests/Unit/GeneratorTest.php +++ b/tests/Unit/GeneratorTest.php @@ -49,7 +49,7 @@ public function it_can_create_new_module(): void $modelName = 'Generator' . $this->generateRandomString(); - $this->post('/simple-generators', json_decode('{"requireds":["yes","yes","yes","yes","yes","yes","yes","no","no","no","yes","yes","no","no","yes","yes","yes","yes","yes","yes","yes","yes","yes","yes","yes"],"_token":"LIV8Mj4vCRSIGWhbQFVcZax6jwnsZMS7JAWGhdTe","_method":"POST","model":"'. $modelName .'","generate_type":"all","generate_variant":"api","generate_seeder":"on","generate_factory":"on","fields":["q","w","e","r","t","y","u","i","o","p","a","s","d","f","g","h","j","k","l","z","x","c","v","b","n"],"column_types":["string","string","string","string","string","string","string","string","string","string","integer","integer","integer","integer","boolean","boolean","boolean","date","date","time","year","year","dateTime","enum","foreignId"],"select_options":[null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,"PHP|Laravel",null],"constrains":[null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,"User"],"foreign_ids":[null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null],"on_update_foreign":[null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,"0"],"on_delete_foreign":[null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,"0"],"min_lengths":[null,null,null,null,null,null,null,null,null,null,null,"1",null,null,null,null,null,null,null,null,null,null,null,null,null],"max_lengths":[null,null,null,null,null,null,null,null,null,null,null,"100",null,null,null,null,null,null,null,null,null,null,null,null,null],"input_types":["text","textarea","email","tel","password","url","search","file","hidden","no-input","number","range","hidden","no-input","select","radio","datalist","date","month","time","select","datalist","datetime-local","select","select"],"file_types":[null,null,null,null,null,null,null,"image",null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null],"files_sizes":[null,null,null,null,null,null,null,"1024",null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null],"mimes":[null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null],"steps":[null,null,null,null,null,null,null,null,null,null,null,"1",null,null,null,null,null,null,null,null,null,null,null,null,null],"default_values":[null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null]}', true))->assertSuccessful(); + $this->post('/simple-generators', json_decode('{"requireds":["yes","yes","yes","yes","yes","yes","yes","no","no","no","yes","yes","no","no","yes","yes","yes","yes","yes","yes","yes","yes","yes","yes","yes"],"_token":"LIV8Mj4vCRSIGWhbQFVcZax6jwnsZMS7JAWGhdTe","_method":"POST","model":"'. $modelName .'","generate_type":"all","generate_variant":"default","generate_seeder":"on","generate_factory":"on","fields":["q","w","e","r","t","y","u","i","o","p","a","s","d","f","g","h","j","k","l","z","x","c","v","b","n"],"column_types":["string","string","string","string","string","string","string","string","string","string","integer","integer","integer","integer","boolean","boolean","boolean","date","date","time","year","year","dateTime","enum","foreignId"],"select_options":[null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,"PHP|Laravel",null],"constrains":[null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,"User"],"foreign_ids":[null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null],"on_update_foreign":[null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,"0"],"on_delete_foreign":[null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,"0"],"min_lengths":[null,null,null,null,null,null,null,null,null,null,null,"1",null,null,null,null,null,null,null,null,null,null,null,null,null],"max_lengths":[null,null,null,null,null,null,null,null,null,null,null,"100",null,null,null,null,null,null,null,null,null,null,null,null,null],"input_types":["text","textarea","email","tel","password","url","search","file","hidden","no-input","number","range","hidden","no-input","select","radio","datalist","date","month","time","select","datalist","datetime-local","select","select"],"file_types":[null,null,null,null,null,null,null,"image",null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null],"files_sizes":[null,null,null,null,null,null,null,"1024",null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null],"mimes":[null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null],"steps":[null,null,null,null,null,null,null,null,null,null,null,"1",null,null,null,null,null,null,null,null,null,null,null,null,null],"default_values":[null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null]}', true))->assertSuccessful(); } function generateRandomString($length = 5): string From 7f84703318d098b54a173c91e8c57dc6e402200e Mon Sep 17 00:00:00 2001 From: Mohammad Zulfahmi Date: Wed, 3 Apr 2024 12:05:27 +0700 Subject: [PATCH 069/105] fix test fail --- tests/{Unit => }/CommandTest.php | 3 +- tests/Feature/.gitkeep | 0 tests/GeneratorTest.php | 64 ++++++++++++++++++ tests/{Unit => }/GeneratorUtilsTest.php | 3 +- tests/{Unit => }/HelperTest.php | 5 +- tests/TestCase.php | 14 ++-- tests/Unit/GeneratorTest.php | 65 ------------------- .../Providers/ViewComposerServiceProvider.php | 25 ------- 8 files changed, 74 insertions(+), 105 deletions(-) rename tests/{Unit => }/CommandTest.php (94%) delete mode 100644 tests/Feature/.gitkeep create mode 100644 tests/GeneratorTest.php rename tests/{Unit => }/GeneratorUtilsTest.php (99%) rename tests/{Unit => }/HelperTest.php (74%) delete mode 100644 tests/Unit/GeneratorTest.php delete mode 100644 workbench/app/Providers/ViewComposerServiceProvider.php diff --git a/tests/Unit/CommandTest.php b/tests/CommandTest.php similarity index 94% rename from tests/Unit/CommandTest.php rename to tests/CommandTest.php index 4db9f1d8..9ffb00fc 100644 --- a/tests/Unit/CommandTest.php +++ b/tests/CommandTest.php @@ -1,9 +1,8 @@ afterApplicationCreated(function () { + file_put_contents(__DIR__ . '/../generator.cache', '{"simple_version_publish_count":0,"full_version_publish_count":2}'); + }); + + $this->beforeApplicationDestroyed(function () { + file_put_contents(__DIR__ . '/../generator.cache', '{"simple_version_publish_count":0,"full_version_publish_count":2}'); + }); + } + + #[Test] + public function it_can_render_generator_create_page(): void + { + $this->withoutExceptionHandling(); + $this->get('/generators/create?for_test=1')->assertStatus(200)->assertSee('Generators'); + } + + #[Test] + public function it_can_render_simple_generator_create_page(): void + { + $this->get('/simple-generators/create')->assertStatus(200); + } + + #[Test] + public function it_can_render_api_generator_create_page(): void + { + $this->get('/api-generators/create')->assertStatus(200)->assertSee('API Generators'); + } + + #[Test] + public function it_can_create_new_module(): void + { + $this->withoutExceptionHandling(); + + $modelName = 'Generator' . $this->generateRandomString(); + + $this->post('/simple-generators', json_decode('{"requireds":["yes","yes","yes","yes","yes","yes","yes","no","no","no","yes","yes","no","no","yes","yes","yes","yes","yes","yes","yes","yes","yes","yes"],"_token":"LIV8Mj4vCRSIGWhbQFVcZax6jwnsZMS7JAWGhdTe","_method":"POST","model":"'. $modelName .'","generate_type":"all","generate_variant":"default","generate_seeder":"on","generate_factory":"on","fields":["q","w","e","r","t","y","u","i","o","p","a","s","d","f","g","h","j","k","l","z","x","c","v","b"],"column_types":["string","string","string","string","string","string","string","string","string","string","integer","integer","integer","integer","boolean","boolean","boolean","date","date","time","year","year","dateTime","enum"],"select_options":[null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,"PHP|Laravel"],"constrains":[null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null],"foreign_ids":[null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null],"on_update_foreign":[null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null],"on_delete_foreign":[null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null],"min_lengths":[null,null,null,null,null,null,null,null,null,null,null,"1",null,null,null,null,null,null,null,null,null,null,null,null],"max_lengths":[null,null,null,null,null,null,null,null,null,null,null,"100",null,null,null,null,null,null,null,null,null,null,null,null],"input_types":["text","textarea","email","tel","password","url","search","file","hidden","no-input","number","range","hidden","no-input","select","radio","datalist","date","month","time","select","datalist","datetime-local","select"],"file_types":[null,null,null,null,null,null,null,"image",null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null],"files_sizes":[null,null,null,null,null,null,null,"1024",null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null],"mimes":[null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null],"steps":[null,null,null,null,null,null,null,null,null,null,null,"1",null,null,null,null,null,null,null,null,null,null,null,null],"default_values":[null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null]}', true))->assertSuccessful(); + } + + function generateRandomString($length = 5): string + { + $characters = 'abcdefghijklmnopqrstuvwxyz'; + $charactersLength = strlen($characters); + $randomString = ''; + + for ($i = 0; $i < $length; $i++) $randomString .= $characters[random_int(0, $charactersLength - 1)]; + + return $randomString; + } +} diff --git a/tests/Unit/GeneratorUtilsTest.php b/tests/GeneratorUtilsTest.php similarity index 99% rename from tests/Unit/GeneratorUtilsTest.php rename to tests/GeneratorUtilsTest.php index 713b0abf..af47d4d5 100644 --- a/tests/Unit/GeneratorUtilsTest.php +++ b/tests/GeneratorUtilsTest.php @@ -1,10 +1,9 @@ assertTrue(file_exists(__DIR__ . '/../../src/helper.php')); + $this->assertTrue(file_exists(__DIR__ . '/../src/helper.php')); } } diff --git a/tests/TestCase.php b/tests/TestCase.php index cf1617cb..51d82d75 100644 --- a/tests/TestCase.php +++ b/tests/TestCase.php @@ -5,13 +5,12 @@ use Orchestra\Testbench\Concerns\WithWorkbench; use Illuminate\Foundation\Testing\Concerns\InteractsWithViews; use Illuminate\Foundation\Testing\RefreshDatabase; -use Illuminate\Support\Facades\Artisan; use Orchestra\Testbench\Attributes\WithMigration; use PHPUnit\Framework\Attributes\Test; -use Tests\Unit\CommandTest; -use Tests\Unit\GeneratorTest; -use Tests\Unit\GeneratorUtilsTest; -use Tests\Unit\HelperTest; +use Tests\CommandTest; +use Tests\GeneratorTest; +use Tests\GeneratorUtilsTest; +use Tests\HelperTest; #[WithMigration] class TestCase extends \Orchestra\Testbench\TestCase @@ -24,11 +23,11 @@ class TestCase extends \Orchestra\Testbench\TestCase protected function setUp(): void { $this->afterApplicationCreated(function () { - Artisan::call('view:clear'); + // Artisan::call('view:clear'); }); $this->beforeApplicationDestroyed(function () { - Artisan::call('view:clear'); + // Artisan::call('view:clear'); }); parent::setUp(); @@ -45,7 +44,6 @@ protected function getPackageProviders($app) return [ \EvdigiIna\Generator\Providers\GeneratorServiceProvider::class, \Yajra\DataTables\DataTablesServiceProvider::class, - \Workbench\App\Providers\ViewComposerServiceProvider::class, ]; } diff --git a/tests/Unit/GeneratorTest.php b/tests/Unit/GeneratorTest.php deleted file mode 100644 index 204ce125..00000000 --- a/tests/Unit/GeneratorTest.php +++ /dev/null @@ -1,65 +0,0 @@ -afterApplicationCreated(function () { - file_put_contents(__DIR__ . '/../generator.cache', '{"simple_version_publish_count":0,"full_version_publish_count":2}'); - }); - - $this->beforeApplicationDestroyed(function () { - file_put_contents(__DIR__ . '/../generator.cache', '{"simple_version_publish_count":0,"full_version_publish_count":2}'); - }); - } - - #[Test] - public function it_can_render_generator_create_page(): void - { - $this->withoutExceptionHandling(); - $this->get('/generators/create?for_test=1')->assertStatus(200)->assertSee('Generators'); - } - - #[Test] - public function it_can_render_simple_generator_create_page(): void - { - $this->get('/simple-generators/create')->assertStatus(200); - } - - #[Test] - public function it_can_render_api_generator_create_page(): void - { - $this->get('/api-generators/create')->assertStatus(200)->assertSee('API Generators'); - } - - #[Test] - public function it_can_create_new_module(): void - { - $this->withoutExceptionHandling(); - - $modelName = 'Generator' . $this->generateRandomString(); - - $this->post('/simple-generators', json_decode('{"requireds":["yes","yes","yes","yes","yes","yes","yes","no","no","no","yes","yes","no","no","yes","yes","yes","yes","yes","yes","yes","yes","yes","yes","yes"],"_token":"LIV8Mj4vCRSIGWhbQFVcZax6jwnsZMS7JAWGhdTe","_method":"POST","model":"'. $modelName .'","generate_type":"all","generate_variant":"default","generate_seeder":"on","generate_factory":"on","fields":["q","w","e","r","t","y","u","i","o","p","a","s","d","f","g","h","j","k","l","z","x","c","v","b","n"],"column_types":["string","string","string","string","string","string","string","string","string","string","integer","integer","integer","integer","boolean","boolean","boolean","date","date","time","year","year","dateTime","enum","foreignId"],"select_options":[null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,"PHP|Laravel",null],"constrains":[null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,"User"],"foreign_ids":[null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null],"on_update_foreign":[null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,"0"],"on_delete_foreign":[null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,"0"],"min_lengths":[null,null,null,null,null,null,null,null,null,null,null,"1",null,null,null,null,null,null,null,null,null,null,null,null,null],"max_lengths":[null,null,null,null,null,null,null,null,null,null,null,"100",null,null,null,null,null,null,null,null,null,null,null,null,null],"input_types":["text","textarea","email","tel","password","url","search","file","hidden","no-input","number","range","hidden","no-input","select","radio","datalist","date","month","time","select","datalist","datetime-local","select","select"],"file_types":[null,null,null,null,null,null,null,"image",null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null],"files_sizes":[null,null,null,null,null,null,null,"1024",null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null],"mimes":[null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null],"steps":[null,null,null,null,null,null,null,null,null,null,null,"1",null,null,null,null,null,null,null,null,null,null,null,null,null],"default_values":[null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null]}', true))->assertSuccessful(); - } - - function generateRandomString($length = 5): string - { - $characters = 'abcdefghijklmnopqrstuvwxyz'; - $charactersLength = strlen($characters); - $randomString = ''; - - for ($i = 0; $i < $length; $i++) $randomString .= $characters[random_int(0, $charactersLength - 1)]; - - return $randomString; - } -} diff --git a/workbench/app/Providers/ViewComposerServiceProvider.php b/workbench/app/Providers/ViewComposerServiceProvider.php deleted file mode 100644 index 0770cd8b..00000000 --- a/workbench/app/Providers/ViewComposerServiceProvider.php +++ /dev/null @@ -1,25 +0,0 @@ - Date: Wed, 3 Apr 2024 14:12:23 +0700 Subject: [PATCH 070/105] update imageService and controller stub :hammer: --- resources/views/simple-create.blade.php | 2 +- src/Generators/ControllerGenerator.php | 8 ++++++-- stubs/generators/publish/utils/Services/ImageService.php | 4 ++-- stubs/generators/views/simple/create.stub | 2 +- stubs/generators/views/simple/edit.stub | 2 +- stubs/generators/views/simple/index.stub | 2 +- stubs/generators/views/simple/show.stub | 2 +- 7 files changed, 13 insertions(+), 9 deletions(-) diff --git a/resources/views/simple-create.blade.php b/resources/views/simple-create.blade.php index 6beb8faf..c8544c38 100644 --- a/resources/views/simple-create.blade.php +++ b/resources/views/simple-create.blade.php @@ -1,5 +1,5 @@ - + diff --git a/src/Generators/ControllerGenerator.php b/src/Generators/ControllerGenerator.php index d9210172..1b76c53b 100644 --- a/src/Generators/ControllerGenerator.php +++ b/src/Generators/ControllerGenerator.php @@ -347,7 +347,8 @@ public function generate(array $request): void '{{castImageFunction}}', '{{castImageIndex}}', '{{castImageShow}}', - '{{castImageDatatable}}' + '{{castImageDatatable}}', + "'auth',", ], [ $modelNameSingularPascalCase, @@ -387,7 +388,8 @@ public function generate(array $request): void // $this->castImages($product); "\n\t\t\$this->castImages($" . $modelNameSingularCamelCase . ");\n", - $castImageDatatable + $castImageDatatable, + GeneratorUtils::isGenerateApi() ? "'auth:sanctum'," : "'auth',", ], GeneratorUtils::isGenerateApi() ? GeneratorUtils::getStub('controllers/controller-api-with-upload-file') : GeneratorUtils::getStub('controllers/controller-with-upload-file') ); @@ -420,6 +422,7 @@ public function generate(array $request): void '{{modelNameCleanPlural}}', '{{relations}}', '{{publicOrStorage}}', + "'auth',", ], [ $modelNameSingularPascalCase, @@ -444,6 +447,7 @@ public function generate(array $request): void $modelNameCleanPlural, $relations, config('generator.image.disk', 'storage'), + GeneratorUtils::isGenerateApi() ? "'auth:sanctum'," : "'auth',", ], GeneratorUtils::isGenerateApi() ? GeneratorUtils::getStub('controllers/controller-api') : GeneratorUtils::getStub('controllers/controller') ); diff --git a/stubs/generators/publish/utils/Services/ImageService.php b/stubs/generators/publish/utils/Services/ImageService.php index 33dd2f44..9f2ce509 100644 --- a/stubs/generators/publish/utils/Services/ImageService.php +++ b/stubs/generators/publish/utils/Services/ImageService.php @@ -3,7 +3,6 @@ namespace App\Generators\Services; use App\Generators\Interfaces\ImageServiceInterface; -use EvdigiIna\Generator\Facades\Generator; use Illuminate\Support\Facades\Storage; class ImageService implements ImageServiceInterface @@ -17,7 +16,7 @@ public function upload(string $name, string $path, string|null $defaultImage = n if (!$isCustomUpload) { $file = request()->file($name); - if (str_contains(Generator::checkPackageVersion('intervention/image'), '2')) { + if (class_exists(\Intervention\Image\Facades\Image::class)) { $filename = $file->hashName(); } else { // set image to webp @@ -35,6 +34,7 @@ public function upload(string $name, string $path, string|null $defaultImage = n } : null)->encode($file->extension()); } else { // for intervention v3 + $imageInstance = \Intervention\Image\Laravel\Facades\Image::read($file); if (config('generator.image.crop')) { diff --git a/stubs/generators/views/simple/create.stub b/stubs/generators/views/simple/create.stub index 0463ad9a..69609d39 100644 --- a/stubs/generators/views/simple/create.stub +++ b/stubs/generators/views/simple/create.stub @@ -9,7 +9,7 @@ - +
    diff --git a/stubs/generators/views/simple/edit.stub b/stubs/generators/views/simple/edit.stub index cec49e94..7cdbcf17 100644 --- a/stubs/generators/views/simple/edit.stub +++ b/stubs/generators/views/simple/edit.stub @@ -9,7 +9,7 @@ - +
    diff --git a/stubs/generators/views/simple/index.stub b/stubs/generators/views/simple/index.stub index 6c2f170c..734fb993 100644 --- a/stubs/generators/views/simple/index.stub +++ b/stubs/generators/views/simple/index.stub @@ -13,7 +13,7 @@ - +
    @if (session('success'))
    - - - "; - } - - switch ($request['column_types'][$i]) { - case 'boolean': - $trs .= " - - - "; - break; - case 'foreignId': - // remove '/' or sub folders - $constrainModel = GeneratorUtils::setModelName($request['constrains'][$i], 'default'); - - $trs .= " - - - "; - break; - case 'date': - $dateFormat = config('generator.format.date') ? config('generator.format.date') : 'd/m/Y'; - - if ($request['input_types'][$i] == 'month') $dateFormat = config('generator.format.month') ? config('generator.format.month') : 'm/Y'; - - $trs .= " - - - "; - break; - case 'dateTime': - $trs .= " - - - "; - break; - case 'time': - $timeFormat = config('generator.format.time') ? config('generator.format.time') : 'H:i'; - - $trs .= " - - - "; - break; - default: - if ($request['file_types'][$i] != 'image') { - $trs .= " - - - "; - } - break; - } - - if ($i + 1 != $totalFields) $trs .= "\n"; - } - } + $trs = $this->generateTableRows($request, $model, $modelNameSingularCamelCase); $template = str_replace( [ @@ -123,21 +34,161 @@ public function generate(array $request): void $modelNamePluralKebabCase, $modelNameSingularCamelCase, $trs, - $dateTimeFormat, + config('generator.format.datetime', 'Y-m-d H:i:s'), ], empty($request['is_simple_generator']) ? GeneratorUtils::getStub('views/show') : GeneratorUtils::getStub('views/simple/show') ); - switch ($path) { - case '': - GeneratorUtils::checkFolder(resource_path("/views/$modelNamePluralKebabCase")); - file_put_contents(resource_path("/views/$modelNamePluralKebabCase/show.blade.php"), $template); - break; - default: - $fullPath = resource_path("/views/" . strtolower($path) . "/$modelNamePluralKebabCase"); - GeneratorUtils::checkFolder($fullPath); - file_put_contents($fullPath . "/show.blade.php", $template); - break; + $this->saveTemplate($template, $path, $modelNamePluralKebabCase); + } + + /** + * Generate table rows for the view. + */ + private function generateTableRows(array $request, string $model, string $modelNameSingularCamelCase): string + { + $trs = ""; + $totalFields = count($request['fields']); + $dateTimeFormat = config('generator.format.datetime', 'Y-m-d H:i:s'); + + foreach ($request['fields'] as $i => $field) { + if ($request['input_types'][$i] !== 'password') { + $trs .= $this->generateTableRow($request, $i, $field, $model, $modelNameSingularCamelCase, $dateTimeFormat); + if ($i + 1 !== $totalFields) { + $trs .= "\n"; + } + } + } + + return $trs; + } + + /** + * Generate a single table row. + */ + private function generateTableRow(array $request, int $i, string $field, string $model, string $modelNameSingularCamelCase, string $dateTimeFormat): string + { + $fieldUcWords = GeneratorUtils::cleanUcWords($field); + $fieldSnakeCase = str($field)->snake(); + $trs = ""; + + if (isset($request['file_types'][$i]) && $request['file_types'][$i] === 'image') { + $trs .= $this->generateImageRow($request, $i, $field, $model, $fieldUcWords); + } else { + $trs .= match ($request['column_types'][$i]) { + 'boolean' => " + + + ", + 'foreignId' => $this->generateForeignIdRow($request, $i, $modelNameSingularCamelCase), + 'date' => $this->generateDateRow($request, $i, $modelNameSingularCamelCase, $fieldUcWords, $fieldSnakeCase), + 'dateTime' => " + + + ", + 'time' => $this->generateTimeRow($modelNameSingularCamelCase, $fieldUcWords, $fieldSnakeCase), + default => $this->generateDefaultRow($request, $i, $modelNameSingularCamelCase, $fieldUcWords, $fieldSnakeCase), + }; + } + + return $trs; + } + + private function generateDefaultRow(array $request, int $i, string $modelNameSingularCamelCase, string $fieldUcWords, string $fieldSnakeCase): string + { + if ($request['input_types'][$i] == 'week') { + $weekFormat = config('generator.format.week', 'Y-\WW'); + + return " + + + "; } + + return " + + + "; + } + + /** + * Generate a row for image fields. + */ + private function generateImageRow(array $request, int $i, string $field, string $model, string $fieldUcWords): string + { + $default = GeneratorUtils::setDefaultImage( + default: $request['default_values'][$i], + field: $request['fields'][$i], + model: $model + ); + + $castImage = str_replace( + "\$this->" . GeneratorUtils::singularCamelCase($field) . "Path", + "'" . GeneratorUtils::pluralKebabCase($field) . "/'", + GeneratorUtils::setDiskCodeForCastImage($model, $field) + ); + + return " + + + "; + } + + /** + * Generate a row for foreign ID fields. + */ + private function generateForeignIdRow(array $request, int $i, string $modelNameSingularCamelCase): string + { + $constrainModel = GeneratorUtils::setModelName($request['constrains'][$i], 'default'); + + return " + + + "; + } + + /** + * Generate a row for date fields. + */ + private function generateDateRow(array $request, int $i, string $modelNameSingularCamelCase, string $fieldUcWords, string $fieldSnakeCase): string + { + $dateFormat = match ($request['input_types'][$i]) { + 'month' => config('generator.format.month', 'Y/m'), + default => config('generator.format.date', 'd/m/Y'), + }; + + return " + + + "; + } + + /** + * Generate a row for time fields. + */ + private function generateTimeRow(string $modelNameSingularCamelCase, string $fieldUcWords, string $fieldSnakeCase): string + { + $timeFormat = config('generator.format.time', 'H:i'); + + return " + + + "; + } + + /** + * Save the generated template to the specified path. + */ + private function saveTemplate(string $template, string $path, string $modelNamePluralKebabCase): void + { + $viewPath = $path ? resource_path("/views/" . strtolower($path) . "/$modelNamePluralKebabCase") : resource_path("/views/$modelNamePluralKebabCase"); + GeneratorUtils::checkFolder($viewPath); + file_put_contents("$viewPath/show.blade.php", $template); } } diff --git a/stubs/generators/views/forms/image.stub b/stubs/generators/views/forms/image.stub index e7930ae3..34e4ab59 100644 --- a/stubs/generators/views/forms/image.stub +++ b/stubs/generators/views/forms/image.stub @@ -3,9 +3,9 @@
    @if ({{defaultImageCodeForm}}) - {{fieldUcWords}} + {{fieldUcWords}} @else - {{fieldUcWords}} + {{fieldUcWords}} @endif
    From 982134ccd5fe7953b6b9dd7b7eda3f68e6535238 Mon Sep 17 00:00:00 2001 From: Zzzul Date: Fri, 28 Jun 2024 17:08:28 +0700 Subject: [PATCH 093/105] update published controller :hammer: --- .../publish/controllers/ProfileController.php | 4 ++- .../RoleAndPermissionController.php | 28 +++++++-------- .../publish/controllers/UserController.php | 35 ++++++++----------- .../fortify/UpdateUserProfileInformation.php | 18 ++-------- 4 files changed, 32 insertions(+), 53 deletions(-) diff --git a/stubs/generators/publish/controllers/ProfileController.php b/stubs/generators/publish/controllers/ProfileController.php index a31dec55..b8192b57 100644 --- a/stubs/generators/publish/controllers/ProfileController.php +++ b/stubs/generators/publish/controllers/ProfileController.php @@ -2,9 +2,11 @@ namespace App\Http\Controllers; +use Illuminate\Contracts\View\View; + class ProfileController extends Controller { - public function __invoke(): \Illuminate\Contracts\View\View + public function __invoke(): View { return view('profile'); } diff --git a/stubs/generators/publish/controllers/RoleAndPermissionController.php b/stubs/generators/publish/controllers/RoleAndPermissionController.php index 49e2d958..0fb3ae3e 100644 --- a/stubs/generators/publish/controllers/RoleAndPermissionController.php +++ b/stubs/generators/publish/controllers/RoleAndPermissionController.php @@ -6,6 +6,9 @@ use Spatie\Permission\Models\Role; use Yajra\DataTables\Facades\DataTables; use Illuminate\Routing\Controllers\{HasMiddleware, Middleware}; +use Illuminate\Contracts\View\View; +use Illuminate\Http\JsonResponse; +use Illuminate\Http\RedirectResponse; class RoleAndPermissionController extends Controller implements HasMiddleware { @@ -27,19 +30,15 @@ public static function middleware(): array * * @return \Illuminate\Http\Response */ - public function index(): \Illuminate\Contracts\View\View|\Illuminate\Http\JsonResponse + public function index(): View|JsonResponse { if (request()->ajax()) { $users = Role::query(); return DataTables::of($users) ->addIndexColumn() - ->addColumn('created_at', function ($row) { - return $row->created_at->format('Y-m-d H:i:s'); - }) - ->addColumn('updated_at', function ($row) { - return $row->updated_at->format('Y-m-d H:i:s'); - }) + ->addColumn('created_at', fn($row) => $row->created_at->format('Y-m-d H:i:s')) + ->addColumn('updated_at',fn($row) => $row->updated_at->format('Y-m-d H:i:s')) ->addColumn('action', 'roles.include.action') ->toJson(); } @@ -50,7 +49,7 @@ public function index(): \Illuminate\Contracts\View\View|\Illuminate\Http\JsonRe /** * Show the form for creating a new resource. */ - public function create(): \Illuminate\Contracts\View\View + public function create(): View { return view('roles.create'); } @@ -58,10 +57,9 @@ public function create(): \Illuminate\Contracts\View\View /** * Store a newly created resource in storage. */ - public function store(StoreRoleRequest $request): \Illuminate\Http\RedirectResponse + public function store(StoreRoleRequest $request): RedirectResponse { $role = Role::create(['name' => $request->name]); - $role->givePermissionTo($request->permissions); return to_route('roles.index')->with('success', __('The role was created successfully.')); @@ -70,7 +68,7 @@ public function store(StoreRoleRequest $request): \Illuminate\Http\RedirectRespo /** * Display the specified resource. */ - public function show(int $id): \Illuminate\Contracts\View\View + public function show(int $id): View { $role = Role::with('permissions')->findOrFail($id); @@ -80,7 +78,7 @@ public function show(int $id): \Illuminate\Contracts\View\View /** * Show the form for editing the specified resource. */ - public function edit(int $id): \Illuminate\Contracts\View\View + public function edit(int $id): View { $role = Role::with('permissions')->findOrFail($id); @@ -90,12 +88,10 @@ public function edit(int $id): \Illuminate\Contracts\View\View /** * Update the specified resource in storage. */ - public function update(UpdateRoleRequest $request, string $id): \Illuminate\Http\RedirectResponse + public function update(UpdateRoleRequest $request, string $id): RedirectResponse { $role = Role::findOrFail($id); - $role->update(['name' => $request->name]); - $role->syncPermissions($request->permissions); return to_route('roles.index')->with('success', __('The role was updated successfully.')); @@ -104,7 +100,7 @@ public function update(UpdateRoleRequest $request, string $id): \Illuminate\Http /** * Remove the specified resource from storage. */ - public function destroy(string $id): \Illuminate\Http\RedirectResponse + public function destroy(string $id): RedirectResponse { $role = Role::withCount('users')->findOrFail($id); diff --git a/stubs/generators/publish/controllers/UserController.php b/stubs/generators/publish/controllers/UserController.php index bcabfaca..06c57efb 100644 --- a/stubs/generators/publish/controllers/UserController.php +++ b/stubs/generators/publish/controllers/UserController.php @@ -9,6 +9,9 @@ use Illuminate\Routing\Controllers\{HasMiddleware, Middleware}; use App\Http\Requests\Users\{StoreUserRequest, UpdateUserRequest}; use Illuminate\Support\Facades\DB; +use Illuminate\Contracts\View\View; +use Illuminate\Http\JsonResponse; +use Illuminate\Http\RedirectResponse; class UserController extends Controller implements HasMiddleware { @@ -33,16 +36,14 @@ public static function middleware(): array /** * Display a listing of the resource. */ - public function index(): \Illuminate\Contracts\View\View|\Illuminate\Http\JsonResponse + public function index(): View|JsonResponse { if (request()->ajax()) { $users = User::with('roles:id,name'); return Datatables::of($users) ->addColumn('action', 'users.include.action') - ->addColumn('role', function ($row) { - return $row->getRoleNames()->toArray() !== [] ? $row->getRoleNames()[0] : '-'; - }) + ->addColumn('role', fn($row) => $row->getRoleNames()->toArray() !== [] ? $row->getRoleNames()[0] : '-') ->addColumn('avatar', function ($row) { if ($row->avatar == null) { return 'https://www.gravatar.com/avatar/' . md5(strtolower(trim($row->email))) . '&s=500'; @@ -58,7 +59,7 @@ public function index(): \Illuminate\Contracts\View\View|\Illuminate\Http\JsonRe /** * Show the form for creating a new resource. */ - public function create(): \Illuminate\Contracts\View\View + public function create(): View { return view('users.create'); } @@ -66,13 +67,11 @@ public function create(): \Illuminate\Contracts\View\View /** * Store a newly created resource in storage. */ - public function store(StoreUserRequest $request): \Illuminate\Http\RedirectResponse + public function store(StoreUserRequest $request): RedirectResponse { return DB::transaction(function () use ($request) { $validated = $request->validated(); - $validated['avatar'] = $this->imageService->upload(name: 'avatar', path: $this->avatarPath); - $validated['password'] = bcrypt($request->password); $user = User::create($validated); @@ -88,7 +87,7 @@ public function store(StoreUserRequest $request): \Illuminate\Http\RedirectRespo /** * Display the specified resource. */ - public function show(User $user): \Illuminate\Contracts\View\View + public function show(User $user): View { $user->load('roles:id,name'); @@ -98,7 +97,7 @@ public function show(User $user): \Illuminate\Contracts\View\View /** * Show the form for editing the specified resource. */ - public function edit(User $user): \Illuminate\Contracts\View\View + public function edit(User $user): View { $user->load('roles:id,name'); @@ -108,20 +107,16 @@ public function edit(User $user): \Illuminate\Contracts\View\View /** * Update the specified resource in storage. */ - public function update(UpdateUserRequest $request, User $user): \Illuminate\Http\RedirectResponse + public function update(UpdateUserRequest $request, User $user): RedirectResponse { return DB::transaction(function () use ($request, $user) { $validated = $request->validated(); - $validated['avatar'] = $this->imageService->upload(name: 'avatar', path: $this->avatarPath, defaultImage: $user->avatar); - switch (is_null($request->password)) { - case true: - unset($validated['password']); - break; - default: - $validated['password'] = bcrypt($request->password); - break; + if (is_null($request->password)) { + unset($validated['password']); + } else { + $validated['password'] = bcrypt($request->password); } $user->update($validated); @@ -137,7 +132,7 @@ public function update(UpdateUserRequest $request, User $user): \Illuminate\Http /** * Remove the specified resource from storage. */ - public function destroy(User $user): \Illuminate\Http\RedirectResponse + public function destroy(User $user): RedirectResponse { if ($user->avatar != null && file_exists($oldAvatar = public_path($this->avatarPath . $user->avatar))) { unlink($oldAvatar); diff --git a/stubs/generators/publish/fortify/UpdateUserProfileInformation.php b/stubs/generators/publish/fortify/UpdateUserProfileInformation.php index d0e9735c..457c9816 100644 --- a/stubs/generators/publish/fortify/UpdateUserProfileInformation.php +++ b/stubs/generators/publish/fortify/UpdateUserProfileInformation.php @@ -2,12 +2,12 @@ namespace App\Actions\Fortify; +use App\Generators\Services\ImageService; use App\Models\User; use Illuminate\Contracts\Auth\MustVerifyEmail; use Illuminate\Support\Facades\Validator; use Illuminate\Validation\Rule; use Laravel\Fortify\Contracts\UpdatesUserProfileInformation; -use Image; class UpdateUserProfileInformation implements UpdatesUserProfileInformation { @@ -37,21 +37,7 @@ public function update(User $user, array $input) if (isset($input['avatar']) && $input['avatar']->isValid()) { - $filename = $input['avatar']->hashName(); - - if (!file_exists($path = public_path($this->avatarPath))) { - mkdir($path, 0777, true); - } - - Image::make($input['avatar']->getRealPath())->resize(500, 500, function ($constraint) { - $constraint->aspectRatio(); - $constraint->upsize(); - })->save(public_path($this->avatarPath) . $filename); - - // delete old avatar from storage - if ($user->avatar != null && file_exists(public_path($this->avatarPath . $user->avatar))) { - unlink(public_path($this->avatarPath . $user->avatar)); - } + $filename = (new ImageService)->upload(name: 'avatar', path: $this->avatarPath, defaultImage: $user->avatar); $user->forceFill([ 'avatar' => $filename, From d209b67475d36777cf4895df324ac5e7387c1ca5 Mon Sep 17 00:00:00 2001 From: Zzzul Date: Mon, 1 Jul 2024 16:57:04 +0700 Subject: [PATCH 094/105] wip: publish command and generator cache :hammer: --- src/Commands/PublishAllFiles.php | 80 +++++++++++-------- .../OnlyAvailableInTheFullVersion.php | 3 +- tests/GeneratorTest.php | 4 +- 3 files changed, 51 insertions(+), 36 deletions(-) diff --git a/src/Commands/PublishAllFiles.php b/src/Commands/PublishAllFiles.php index edff8a2f..2dcec4ef 100644 --- a/src/Commands/PublishAllFiles.php +++ b/src/Commands/PublishAllFiles.php @@ -56,9 +56,9 @@ public function handle(): void $totalRunningCommand = $this->totalRunningCommand('full_version_publish_count'); if ( - $totalRunningCommand['simple_version_publish_count'] == 1 || $totalRunningCommand['simple_version_publish_count'] > 1 + $totalRunningCommand['full_version_publish_count'] == 1 || $totalRunningCommand['full_version_publish_count'] > 1 ) { - if (!$this->confirm('Do you wish to continue? You are already using the simple version.')) { + if (!$this->confirm('Do you wish to continue? You are already using the full version.')) { return; } } @@ -68,11 +68,13 @@ public function handle(): void if ($totalRunningCommand['full_version_publish_count'] == 1 || $totalRunningCommand['full_version_publish_count'] > 1) { if ($this->confirm('Do you wish to continue? you are already running this command ' . $totalRunningCommand['full_version_publish_count'] . ' for times.')) { + $this->totalRunningCommand('full_version_publish_count', true); $this->runPublishAll(); return; } } + $this->totalRunningCommand('full_version_publish_count', true); $this->runPublishAll(); return; @@ -82,7 +84,7 @@ public function handle(): void $totalRunningCommand = $this->totalRunningCommand('simple_version_publish_count'); if ($totalRunningCommand['full_version_publish_count'] == 1 || $totalRunningCommand['full_version_publish_count'] > 1) { - $this->info('You are using the full version, which already includes the simple version. So this command may not be affected.'); + $this->info('You are using the full version, which already includes the simple version. This command may not be affected.'); return; } @@ -93,6 +95,9 @@ public function handle(): void return; } + $this->totalRunningCommand('simple_version_publish_count', true); + + $this->info('Installing the simple version...'); $this->info('Please wait a bit, this process may take several minutes.'); @@ -137,9 +142,10 @@ public function handle(): void /** * Check total running of generator:publish all command. * */ - public function totalRunningCommand(string $type = 'full_version_publish_count'): array + public function totalRunningCommand(string $type = 'full_version_publish_count', bool $increment = false): array { - $dir = __DIR__ . '/../../generator.cache'; + // $dir = __DIR__ . '/../../generator.cache'; + $dir = storage_path('generator.cache'); if (!file_exists($dir)) { file_put_contents( @@ -158,40 +164,48 @@ public function totalRunningCommand(string $type = 'full_version_publish_count') switch ($type) { case 'full_version_publish_count': if ($totalRunningCommand['full_version_publish_count'] == 0) { - file_put_contents( - $dir, - json_encode([ - 'simple_version_publish_count' => $totalRunningCommand['simple_version_publish_count'], - 'full_version_publish_count' => 1 - ]) - ); + if ($increment) { + file_put_contents( + $dir, + json_encode([ + 'simple_version_publish_count' => $totalRunningCommand['simple_version_publish_count'], + 'full_version_publish_count' => 1 + ]) + ); + } } else { - file_put_contents( - $dir, - json_encode([ - 'simple_version_publish_count' => $totalRunningCommand['simple_version_publish_count'], - 'full_version_publish_count' => $totalRunningCommand['full_version_publish_count'] + 1 - ]) - ); + if ($increment) { + file_put_contents( + $dir, + json_encode([ + 'simple_version_publish_count' => $totalRunningCommand['simple_version_publish_count'], + 'full_version_publish_count' => $totalRunningCommand['full_version_publish_count'] + 1 + ]) + ); + } } break; default: if ($totalRunningCommand['simple_version_publish_count'] == 0) { - file_put_contents( - $dir, - json_encode([ - 'simple_version_publish_count' => 1, - 'full_version_publish_count' => $totalRunningCommand['full_version_publish_count'] - ]) - ); + if ($increment) { + file_put_contents( + $dir, + json_encode([ + 'simple_version_publish_count' => 1, + 'full_version_publish_count' => $totalRunningCommand['full_version_publish_count'] + ]) + ); + } } else { - file_put_contents( - $dir, - json_encode([ - 'simple_version_publish_count' => $totalRunningCommand['simple_version_publish_count'] + 1, - 'full_version_publish_count' => $totalRunningCommand['full_version_publish_count'] - ]) - ); + if ($increment) { + file_put_contents( + $dir, + json_encode([ + 'simple_version_publish_count' => $totalRunningCommand['simple_version_publish_count'] + 1, + 'full_version_publish_count' => $totalRunningCommand['full_version_publish_count'] + ]) + ); + } } break; } diff --git a/src/Http/Middleware/OnlyAvailableInTheFullVersion.php b/src/Http/Middleware/OnlyAvailableInTheFullVersion.php index ed4f4123..c5e313d2 100644 --- a/src/Http/Middleware/OnlyAvailableInTheFullVersion.php +++ b/src/Http/Middleware/OnlyAvailableInTheFullVersion.php @@ -17,7 +17,8 @@ public function handle(Request $request, Closure $next): mixed return $next($request); } - $dir = __DIR__ . '/../../../generator.cache'; + // $dir = __DIR__ . '/../../../generator.cache'; + $dir = storage_path('generator.cache'); abort_if(!file_exists($dir), Response::HTTP_FORBIDDEN, 'You have not yet selected a version, to use this feature, you must be running the artisan command: "php artisan generator:install full", and then you can use the full version.'); diff --git a/tests/GeneratorTest.php b/tests/GeneratorTest.php index fdc21d45..21b5ce9d 100644 --- a/tests/GeneratorTest.php +++ b/tests/GeneratorTest.php @@ -14,11 +14,11 @@ protected function setUp(): void parent::setUp(); $this->afterApplicationCreated(function () { - file_put_contents(__DIR__ . '/../generator.cache', '{"simple_version_publish_count":0,"full_version_publish_count":2}'); + file_put_contents(storage_path('generator.cache'), '{"simple_version_publish_count":0,"full_version_publish_count":2}'); }); $this->beforeApplicationDestroyed(function () { - file_put_contents(__DIR__ . '/../generator.cache', '{"simple_version_publish_count":0,"full_version_publish_count":2}'); + file_put_contents(storage_path('generator.cache'), '{"simple_version_publish_count":0,"full_version_publish_count":2}'); }); } From c9a8413d8f286ac60d672361aec300730f9f0deb Mon Sep 17 00:00:00 2001 From: Zzzul Date: Tue, 2 Jul 2024 11:21:38 +0700 Subject: [PATCH 095/105] fix middleware for check api sanctum :fire: --- src/Generators/Services/GeneratorService.php | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/src/Generators/Services/GeneratorService.php b/src/Generators/Services/GeneratorService.php index 14901a79..6a275913 100644 --- a/src/Generators/Services/GeneratorService.php +++ b/src/Generators/Services/GeneratorService.php @@ -117,9 +117,13 @@ public function apiRouteAlreadyExists(): bool { $bootstrapApp = file_get_contents(base_path("/bootstrap/app.php")); - $checkApiRoute = (bool) str_contains($bootstrapApp, "api") || str_contains($bootstrapApp, "api.php") || str_contains($bootstrapApp, "api:"); + $checkApiRoute = (bool) str_contains($bootstrapApp, "api") && str_contains($bootstrapApp, "api.php") && str_contains($bootstrapApp, "api:"); - return $checkApiRoute || file_exists(base_path("/routes/api.php")) || class_exists(\Laravel\Sanctum\HasApiTokens::class); + $composerJson = file_get_contents(base_path("/composer.json")); + + $checkLaravelSanctum = str_contains($composerJson, "sanctum"); + + return $checkApiRoute && file_exists(base_path("/routes/api.php")) && $checkLaravelSanctum; } /** From bd4255f4b30d2ec2fd9b4305fa6eb870e82536c0 Mon Sep 17 00:00:00 2001 From: Zzzul Date: Tue, 2 Jul 2024 14:21:30 +0700 Subject: [PATCH 096/105] fix update profile action, profile view, image service and change to storage :sunflower: --- src/Generators/Services/GeneratorService.php | 36 +++- .../OnlyAvailableInTheFullVersion.php | 5 +- .../fortify/PasswordValidationRules.php | 20 +- .../fortify/UpdateUserProfileInformation.php | 21 ++- .../publish/utils/Services/ImageService.php | 173 ++++++++++-------- .../publish/views/profile.blade.php | 66 +++---- 6 files changed, 191 insertions(+), 130 deletions(-) diff --git a/src/Generators/Services/GeneratorService.php b/src/Generators/Services/GeneratorService.php index 6a275913..8a1d307f 100644 --- a/src/Generators/Services/GeneratorService.php +++ b/src/Generators/Services/GeneratorService.php @@ -40,7 +40,9 @@ public function generate(array $request): void abort(Response::HTTP_FORBIDDEN, 'You have not yet installed the API, to use this feature, you must be running the artisan command: "php artisan install:api".'); } - if (empty($request['is_simple_generator'])) (new PermissionGenerator)->generate($request); + if (empty($request['is_simple_generator'])) { + (new PermissionGenerator)->generate($request); + } (new ModelGenerator)->generate($request); (new MigrationGenerator)->generate($request); @@ -48,33 +50,45 @@ public function generate(array $request): void (new RequestGenerator)->generate($request); // blade template - if (isset($request['generate_variant']) || $request['generate_variant'] != 'api') { + if (isset($request['generate_variant']) || $request['generate_variant'] !== 'api') { // for single form (new CreateViewGenerator)->generate($request); (new FormViewGenerator)->generate($request); // for full CRUD - if ($request['generate_variant'] == GeneratorVariant::DEFAULT->value) { + if ($request['generate_variant'] === GeneratorVariant::DEFAULT->value) { (new IndexViewGenerator)->generate($request); (new ShowViewGenerator)->generate($request); (new EditViewGenerator)->generate($request); (new ActionViewGenerator)->generate($request); } - if (empty($request['is_simple_generator']) && !GeneratorUtils::isGenerateApi()) (new MenuGenerator)->generate($request); + if (empty($request['is_simple_generator']) && !GeneratorUtils::isGenerateApi()) { + (new MenuGenerator)->generate($request); + } - if (in_array('foreignId', $request['column_types'])) (new ViewComposerGenerator)->generate($request); + if (in_array('foreignId', $request['column_types'], true)) { + (new ViewComposerGenerator)->generate($request); + } } (new RouteGenerator)->generate($request); - if (isset($request['generate_seeder']) && $request['generate_seeder'] != null) (new SeederGenerator)->generate($request); + if (isset($request['generate_seeder'])) { + (new SeederGenerator)->generate($request); + } - if (isset($request['generate_factory']) && $request['generate_factory'] != null) (new FactoryGenerator)->generate($request); + if (isset($request['generate_factory'])) { + (new FactoryGenerator)->generate($request); + } - if (GeneratorUtils::isGenerateApi()) (new ResourceApiGenerator)->generate($request); + if (GeneratorUtils::isGenerateApi()) { + (new ResourceApiGenerator)->generate($request); + } - if (empty($request['generate_variant']) && $request['generate_variant'] != 'api' || empty($request['is_simple_generator'])) $this->checkSidebarType(); + if ((empty($request['generate_variant']) && $request['generate_variant'] !== 'api') || empty($request['is_simple_generator'])) { + $this->checkSidebarType(); + } Artisan::call('migrate'); } @@ -107,7 +121,9 @@ public function checkSidebarType(): void $sidebar = file_get_contents(resource_path('views/layouts/sidebar.blade.php')); /** if the sidebar is static, then must be regenerated to update new menus */ - if (!str($sidebar)->contains("\$permissions = empty(\$menu['permission'])")) Artisan::call('generator:sidebar dynamic'); + if (!str($sidebar)->contains("\$permissions = empty(\$menu['permission'])")) { + Artisan::call('generator:sidebar dynamic'); + } } /** diff --git a/src/Http/Middleware/OnlyAvailableInTheFullVersion.php b/src/Http/Middleware/OnlyAvailableInTheFullVersion.php index c5e313d2..c9bb2259 100644 --- a/src/Http/Middleware/OnlyAvailableInTheFullVersion.php +++ b/src/Http/Middleware/OnlyAvailableInTheFullVersion.php @@ -10,6 +10,7 @@ class OnlyAvailableInTheFullVersion { /** * Handle an incoming request. + * @throws \JsonException */ public function handle(Request $request, Closure $next): mixed { @@ -24,9 +25,9 @@ public function handle(Request $request, Closure $next): mixed $cache = file_get_contents($dir); - $selectedVersion = collect(json_decode($cache))->toArray(); + $selectedVersion = collect(json_decode($cache, false, 512, JSON_THROW_ON_ERROR))->toArray(); - if ($selectedVersion['full_version_publish_count'] == null || $selectedVersion['full_version_publish_count'] < 1) { + if ($selectedVersion['full_version_publish_count'] === null || $selectedVersion['full_version_publish_count'] < 1) { abort(Response::HTTP_FORBIDDEN, 'You are using the simple version, to use this feature, you must be running the artisan command: "php artisan generator:install full", and then you can use the full version.'); } diff --git a/stubs/generators/publish/fortify/PasswordValidationRules.php b/stubs/generators/publish/fortify/PasswordValidationRules.php index e357cefd..69e0fdbe 100644 --- a/stubs/generators/publish/fortify/PasswordValidationRules.php +++ b/stubs/generators/publish/fortify/PasswordValidationRules.php @@ -12,16 +12,24 @@ trait PasswordValidationRules */ protected function passwordRules(): array { + if(strtolower(env('APP_ENV')) === 'production') { + return [ + 'required', + 'string', + 'confirmed', + Password::min(8) + ->letters() + ->mixedCase() + ->numbers() + ->symbols() + ->uncompromised() + ]; + } + return [ 'required', 'string', 'confirmed', - Password::min(8) - ->letters() - ->mixedCase() - ->numbers() - ->symbols() - ->uncompromised() ]; } } diff --git a/stubs/generators/publish/fortify/UpdateUserProfileInformation.php b/stubs/generators/publish/fortify/UpdateUserProfileInformation.php index 457c9816..3efb499d 100644 --- a/stubs/generators/publish/fortify/UpdateUserProfileInformation.php +++ b/stubs/generators/publish/fortify/UpdateUserProfileInformation.php @@ -11,12 +11,17 @@ class UpdateUserProfileInformation implements UpdatesUserProfileInformation { - /** - * Path for user avatar file. - * - * @var string - */ - protected $avatarPath = '/uploads/images/avatars/'; + public function __construct(public string $avatarPath = '') + { + // storage + $this->avatarPath = storage_path('app/public/uploads/avatars/'); + + // public + // $this->avatarPath = public_path('uploads/avatars/'); + + // s3 + // $this->avatarPath = '/avatars/'; + } /** * Validate and update the given user's profile information. @@ -39,9 +44,7 @@ public function update(User $user, array $input) $filename = (new ImageService)->upload(name: 'avatar', path: $this->avatarPath, defaultImage: $user->avatar); - $user->forceFill([ - 'avatar' => $filename, - ])->save(); + $user->forceFill(['avatar' => $filename])->save(); } if ($input['email'] !== $user->email && $user instanceof MustVerifyEmail) { diff --git a/stubs/generators/publish/utils/Services/ImageService.php b/stubs/generators/publish/utils/Services/ImageService.php index 9f2ce509..eca1ee55 100644 --- a/stubs/generators/publish/utils/Services/ImageService.php +++ b/stubs/generators/publish/utils/Services/ImageService.php @@ -2,100 +2,129 @@ namespace App\Generators\Services; -use App\Generators\Interfaces\ImageServiceInterface; use Illuminate\Support\Facades\Storage; +use App\Generators\Interfaces\ImageServiceInterface; class ImageService implements ImageServiceInterface { /** - * @throws \Exception + * Upload an image to disk and return the image path. */ - public function upload(string $name, string $path, string|null $defaultImage = null, string $disk = 'local', int $width = 500, int $height = 500, bool $isCustomUpload = false): string|null + public function upload(string $name, string $path, ?string $defaultImage = null, ?string $disk = null, int $width = 500, int $height = 500, ?bool $crop = null, ?bool $aspectRatio = null, ?bool $isCustomUpload = false): ?string { - if (request()->file($name) && request()->file($name)->isValid()) { + $crop = $crop ?? config('generator.image.crop') ?? true; + $aspectRatio = $aspectRatio ?? config('generator.image.aspect_ratio') ?? true; + $disk = $disk ?? config('generator.image.disk') ?? 'storage'; + + $file = request()->file($name); + + if ($file && $file->isValid()) { if (!$isCustomUpload) { - $file = request()->file($name); + return $this->handleFileUpload(file: $file, path: $path, defaultImage: $defaultImage, disk: $disk, width: $width, height: $height, crop: $crop, aspectRatio: $aspectRatio); + } else { + // TODO: implement custom upload + } + } - if (class_exists(\Intervention\Image\Facades\Image::class)) { - $filename = $file->hashName(); - } else { - // set image to webp - $filename = str()->random(30) . '.webp'; - } + return $defaultImage; + } - // s3 or local - switch (config('generator.image.disk', $disk)) { - case 's3': - if (class_exists(\Intervention\Image\Facades\Image::class)) { - // for intervention v2 - $image = \Intervention\Image\Facades\Image::make($file)->resize($width, $height, config('generator.image.crop') ? function ($constraint) { - $constraint->aspectRatio(); - $constraint->upsize(); - } : null)->encode($file->extension()); - } else { - // for intervention v3 - - $imageInstance = \Intervention\Image\Laravel\Facades\Image::read($file); - - if (config('generator.image.crop')) { - // constraint aspect ratio - $image = $imageInstance->resizeDown($width, $height)->encode(new \Intervention\Image\Encoders\WebpEncoder(quality: 65)); - } else { - $image = $imageInstance->encode(new \Intervention\Image\Encoders\WebpEncoder(quality: 65)); - } - } + /** + * Handle the file upload process. + */ + private function handleFileUpload(mixed $file, string $path, ?string $defaultImage, string $disk, int $width, int $height, bool $crop, bool $aspectRatio): string + { + $filename = $this->generateFilename($file); + + $image = $this->processImage(file: $file, width: $width, height: $height, crop: $crop, aspectRatio: $aspectRatio); + + if ($disk === 's3') { + Storage::disk('s3')->put($path . '/' . $filename, (string) $image, 'public'); + } else { + $this->saveToLocal(image: $image, path: $path, filename: $filename); + } + + if ($defaultImage) { + $this->delete(image: $path . $defaultImage, disk: $disk); + } + + return $filename; + } + + /** + * Generate a filename for the uploaded image. + */ + private function generateFilename(mixed $file): string + { + if (class_exists(\Intervention\Image\Facades\Image::class)) { // v2 + return $file->hashName(); + } - Storage::disk('s3')->put($path . '/' . $filename, $image); - - // remove old image - if ($defaultImage) $this->delete($path . $defaultImage, 's3'); - break; - default: - if (!file_exists($path)) mkdir($path, 0777, true); - - // for intervention v2 - if (class_exists(\Intervention\Image\Facades\Image::class)) { - \Intervention\Image\Facades\Image::make($file->getRealPath())->resize($width, $height, config('generator.image.crop') ? function ($constraint) { - $constraint->aspectRatio(); - $constraint->upsize(); - } : null)->save($path . $filename); - } else { - // for intervention v3 - $image = \Intervention\Image\Laravel\Facades\Image::read($file); - - if (config('generator.image.crop')) { - // constraint aspect ratio - $image->resizeDown($width, $height)->toWebp()->save($path . $filename); - } else { - $image->toWebp()->save($path . $filename); - } + return str()->random(30) . '.webp'; // v3 + } + + /** + * Process the image using the appropriate version of the Intervention/Image library. + */ + private function processImage(mixed $file, int $width, int $height, bool $crop, bool $aspectRatio): mixed + { + if (class_exists(\Intervention\Image\Facades\Image::class)) { // v2 + return \Intervention\Image\Facades\Image::make($file) + ->resize($width, $height, function ($constraint) use ($crop, $aspectRatio) { + if ($crop) { + if ($aspectRatio) { + $constraint->aspectRatio(); } + $constraint->upsize(); + } + }) + ->encode('webp'); + } - // remove old image - if ($defaultImage) $this->delete($path . $defaultImage); - break; + if (class_exists(\Intervention\Image\Laravel\Facades\Image::class)) { // v3 + $imageInstance = \Intervention\Image\Laravel\Facades\Image::read($file); + $encode = new \Intervention\Image\Encoders\WebpEncoder(65); + + if ($crop) { + if ($aspectRatio) { + return $imageInstance->scaleDown(width: $width, height: $height)->encode($encode); } - return $filename; - } else { - // TODO: write your logic here - return 'something'; + return $imageInstance->resizeDown(width: $width, height: $height)->encode($encode); } + + return $imageInstance->encode($encode); } - return $defaultImage; + return null; } - public function delete(string|null $image, string $disk = 'local'): void + /** + * Save the processed image to local storage. + */ + private function saveToLocal(mixed $image, string $path, string $filename): void + { + if (!file_exists($path) && !mkdir($path, 0777, true) && !is_dir($path)) { + throw new \RuntimeException(sprintf('Directory "%s" was not created', $path)); + } + + if (class_exists(\Intervention\Image\Facades\Image::class)) { // v2 + $image->save($path . $filename); + } elseif (class_exists(\Intervention\Image\Laravel\Facades\Image::class)) { // v3 + $image->save($path . $filename); + } + } + + /** + * Delete an image from the specified disk. + */ + public function delete(?string $image, string $disk = 'local'): void { if ($image) { - switch ($disk) { - case 's3': - Storage::disk('s3')->delete($image); - break; - default: - if (file_exists($image)) unlink($image); - break; + if ($disk === 's3') { + Storage::disk('s3')->delete($image); + } else if (file_exists($image)) { + unlink($image); } } } diff --git a/stubs/generators/publish/views/profile.blade.php b/stubs/generators/publish/views/profile.blade.php index dd7f8114..c7b3d8e5 100644 --- a/stubs/generators/publish/views/profile.blade.php +++ b/stubs/generators/publish/views/profile.blade.php @@ -35,19 +35,19 @@
    + enctype="multipart/form-data"> @csrf @method('PUT')
    + class="form-control @error('email', 'updateProfileInformation') is-invalid @enderror" + id="email" placeholder="{{ __('E-mail Address') }}" + value="{{ old('email') ?? auth()?->user()?->email }}" required> @error('email', 'updateProfileInformation') - + {{ $message }} @enderror @@ -56,11 +56,11 @@ class="form-control @error('email', 'updateProfileInformation') is-invalid @ende
    + class="form-control @error('name', 'updateProfileInformation') is-invalid @enderror" + id="name" placeholder="{{ __('Name') }}" + value="{{ old('name') ?? auth()?->user()?->name }}" required> @error('name', 'updateProfileInformation') - + {{ $message }} @enderror @@ -69,12 +69,18 @@ class="form-control @error('name', 'updateProfileInformation') is-invalid @ende
    - @if (auth()->user()->avatar == null) - Avatar + @if (auth()?->user()?->avatar ) + Avatar @else - Avatar + {{-- storage --}} + Avatar + + {{-- public --}} + {{-- Avatar--}} + + {{-- s3 --}} + {{-- Avatar--}} @endif
    @@ -82,12 +88,10 @@ class="form-control @error('name', 'updateProfileInformation') is-invalid @ende
    - + @error('avatar', 'updateProfileInformation') - + {{ $message }} @enderror @@ -121,10 +125,10 @@ class="form-control @error('avatar', 'updateProfileInformation') is-invalid @end
    + class="form-control @error('current_password', 'updatePassword') is-invalid @enderror" + id="password" placeholder="Current Password" required> @error('current_password', 'updatePassword') - + {{ $message }} @enderror @@ -133,10 +137,10 @@ class="form-control @error('current_password', 'updatePassword') is-invalid @end
    + class="form-control @error('password', 'updatePassword') is-invalid @enderror" + id="password" placeholder="New Password" required> @error('password', 'updatePassword') - + {{ $message }} @enderror @@ -145,7 +149,7 @@ class="form-control @error('password', 'updatePassword') is-invalid @enderror"
    + name="password_confirmation" placeholder="Confirm Password" required>
    @@ -170,19 +174,19 @@ class="form-control @error('password', 'updatePassword') is-invalid @enderror" @csrf {{-- if user activate two factor authentication --}} - @if (auth()->user()->two_factor_secret) + @if (auth()?->user()?->two_factor_secret) @method('delete')

    {{ __('Scan the following QR Code into your authentication application.') }}

    - {!! auth()->user()->twoFactorQrcodeSvg() !!} + {!! auth()?->user()?->twoFactorQrcodeSvg() !!}

    {{ __('Save these Recovery Codes in a secure location.') }}

      - @foreach (json_decode(decrypt(auth()->user()->two_factor_recovery_codes)) as $code) + @foreach (json_decode(decrypt(auth()?->user()?->two_factor_recovery_codes)) as $code)
    • {{ $code }}
    • @endforeach
    @@ -190,15 +194,15 @@ class="form-control @error('password', 'updatePassword') is-invalid @enderror"
    + type="submit">{{ __('Disable Two Factor Authentication') }} @else + type="submit">{{ __('Enable Two Factor Authentication') }} @endif {{-- generate recovery codes --}} - @if (auth()->user()->two_factor_secret) + @if (auth()?->user()?->two_factor_secret)
    @csrf
    "; // create a blade file - switch ($path) { - case '': - GeneratorUtils::checkFolder(resource_path("/views/$modelNamePluralKebabCase/include")); - file_put_contents(resource_path("/views/$modelNamePluralKebabCase/include/form.blade.php"), $template); - break; - default: - $fullPath = resource_path("/views/" . strtolower($path) . "/$modelNamePluralKebabCase/include"); - GeneratorUtils::checkFolder($fullPath); - file_put_contents($fullPath . "/form.blade.php", $template); - break; + if($path) { + $fullPath = resource_path("/views/" . strtolower($path) . "/$modelNamePluralKebabCase/include"); + GeneratorUtils::checkFolder($fullPath); + file_put_contents($fullPath . "/form.blade.php", $template); + }else{ + GeneratorUtils::checkFolder(resource_path("/views/$modelNamePluralKebabCase/include")); + file_put_contents(resource_path("/views/$modelNamePluralKebabCase/include/form.blade.php"), $template); } } diff --git a/src/Providers/GeneratorServiceProvider.php b/src/Providers/GeneratorServiceProvider.php index b7d251b8..405fb629 100644 --- a/src/Providers/GeneratorServiceProvider.php +++ b/src/Providers/GeneratorServiceProvider.php @@ -60,7 +60,7 @@ public function boot(): void // Api Auth Controller $this->publishes([ - __DIR__ . '/../../stubs/generators/publish/AuthController.php' => app_path('Http/Controllers/Api/AuthController.php') + __DIR__ . '/../../stubs/generators/publish/controllers/AuthController.php' => app_path('Http/Controllers/Api/AuthController.php') ], 'generator-controller-api'); // Actions fortify diff --git a/stubs/generators/api.stub b/stubs/generators/api.stub index 28f73a9d..a3e770e7 100644 --- a/stubs/generators/api.stub +++ b/stubs/generators/api.stub @@ -1,4 +1,5 @@ + Route::group(['prefix' => 'auth'], function () { Route::post('/login', [\App\Http\Controllers\Api\AuthController::class, 'login']); Route::post('/register', [\App\Http\Controllers\Api\AuthController::class, 'register']); diff --git a/stubs/generators/publish/AuthController.php b/stubs/generators/publish/controllers/AuthController.php similarity index 95% rename from stubs/generators/publish/AuthController.php rename to stubs/generators/publish/controllers/AuthController.php index 806ee443..7f449562 100644 --- a/stubs/generators/publish/AuthController.php +++ b/stubs/generators/publish/controllers/AuthController.php @@ -29,7 +29,7 @@ public function login(LoginRequest $request): JsonResponse 'message' => 'Successfully logged in', 'token' => $token, 'user' => $user, - ]); + ], Response::HTTP_OK); } public function register(RegisterRequest $request): JsonResponse @@ -48,14 +48,14 @@ public function register(RegisterRequest $request): JsonResponse 'message' => 'Successfully registered', 'token' => $token, 'user' => $user, - ]); + ], Response::HTTP_OK); } public function logout(): JsonResponse { auth()->user()->tokens()->delete(); - return response()->json(['message' => 'Successfully logged out']); + return response()->json(['message' => 'Successfully logged out'], Response::HTTP_OK); } public function me(): JsonResponse diff --git a/stubs/generators/publish/controllers/UserController.php b/stubs/generators/publish/controllers/UserController.php index 06c57efb..2c5b9379 100644 --- a/stubs/generators/publish/controllers/UserController.php +++ b/stubs/generators/publish/controllers/UserController.php @@ -15,9 +15,10 @@ class UserController extends Controller implements HasMiddleware { - public function __construct(public ImageService $imageService, public string $avatarPath = '/uploads/images/avatars/') + public function __construct(public ImageService $imageService, public string $avatarPath = '') { - // + $this->avatarPath = storage_path('app/public/uploads/avatars/'); + } /** @@ -44,11 +45,12 @@ public function index(): View|JsonResponse return Datatables::of($users) ->addColumn('action', 'users.include.action') ->addColumn('role', fn($row) => $row->getRoleNames()->toArray() !== [] ? $row->getRoleNames()[0] : '-') - ->addColumn('avatar', function ($row) { - if ($row->avatar == null) { - return 'https://www.gravatar.com/avatar/' . md5(strtolower(trim($row->email))) . '&s=500'; + ->addColumn('avatar', function ($user) { + if (!$user->avatar) { + return 'https://via.placeholder.com/350?text=No+Image+Avaiable'; } - return asset($this->avatarPath . $row->avatar); + + return asset('storage/uploads/avatars/' . $user->avatar); }) ->toJson(); } @@ -111,7 +113,7 @@ public function update(UpdateUserRequest $request, User $user): RedirectResponse { return DB::transaction(function () use ($request, $user) { $validated = $request->validated(); - $validated['avatar'] = $this->imageService->upload(name: 'avatar', path: $this->avatarPath, defaultImage: $user->avatar); + $validated['avatar'] = $this->imageService->upload(name: 'avatar', path: $this->avatarPath, defaultImage: $user?->avatar); if (is_null($request->password)) { unset($validated['password']); @@ -134,12 +136,16 @@ public function update(UpdateUserRequest $request, User $user): RedirectResponse */ public function destroy(User $user): RedirectResponse { - if ($user->avatar != null && file_exists($oldAvatar = public_path($this->avatarPath . $user->avatar))) { - unlink($oldAvatar); - } + try { + $avatar = $user->avatar; - $user->delete(); + $user->delete(); - return to_route('users.index')->with('success', __('The user was deleted successfully.')); + $this->imageService->delete(image: $this->avatarPath . $avatar); + + return to_route('users.index')->with('success', __('The user was deleted successfully.')); + } catch (\Exception $e) { + return to_route('users.index')->with('error', __("The user can't be deleted because it's related to another table.")); + } } } diff --git a/stubs/generators/publish/requests/Users/StoreUserRequest.php b/stubs/generators/publish/requests/Users/StoreUserRequest.php index 43376cbb..6af7406a 100644 --- a/stubs/generators/publish/requests/Users/StoreUserRequest.php +++ b/stubs/generators/publish/requests/Users/StoreUserRequest.php @@ -2,11 +2,12 @@ namespace App\Http\Requests\Users; +use App\Actions\Fortify\PasswordValidationRules; use Illuminate\Foundation\Http\FormRequest; -use Illuminate\Validation\Rules\Password; class StoreUserRequest extends FormRequest { + use PasswordValidationRules; /** * Determine if the user is authorized to make this request. */ @@ -25,16 +26,7 @@ public function rules(): array 'email' => ['required', 'email', 'unique:users,email'], 'avatar' => ['nullable', 'image', 'max:1024'], 'role' => ['required', 'exists:roles,id'], - 'password' => [ - 'required', - 'confirmed', - // Password::min(8) - // ->letters() - // ->mixedCase() - // ->numbers() - // ->symbols() - // ->uncompromised() - ] + 'password' => $this->passwordRules() ]; } } diff --git a/stubs/generators/publish/requests/Users/UpdateUserRequest.php b/stubs/generators/publish/requests/Users/UpdateUserRequest.php index dc40e94b..c4ba7e80 100644 --- a/stubs/generators/publish/requests/Users/UpdateUserRequest.php +++ b/stubs/generators/publish/requests/Users/UpdateUserRequest.php @@ -2,11 +2,13 @@ namespace App\Http\Requests\Users; +use App\Actions\Fortify\PasswordValidationRules; use Illuminate\Foundation\Http\FormRequest; -use Illuminate\Validation\Rules\Password; class UpdateUserRequest extends FormRequest { + use PasswordValidationRules; + /** * Determine if the user is authorized to make this request. */ @@ -22,19 +24,10 @@ public function rules(): array { return [ 'name' => ['required', 'min:3', 'max:255'], - 'email' => ['required', 'email', 'unique:users,email,' . $this->user->id], + 'email' => ['required', 'email', 'unique:users,email,' . $this?->user?->id ?? request()->segment(2)], 'avatar' => ['nullable', 'image', 'max:1024'], 'role' => ['required', 'exists:roles,id'], - 'password' => [ - 'nullable', - 'confirmed', - // Password::min(8) - // ->letters() - // ->mixedCase() - // ->numbers() - // ->symbols() - // ->uncompromised() - ] + 'password' => $this->passwordRules() ]; } } diff --git a/stubs/generators/publish/utils/Interfaces/ImageServiceInterface.php b/stubs/generators/publish/utils/Interfaces/ImageServiceInterface.php index be7282bc..441e3d10 100644 --- a/stubs/generators/publish/utils/Interfaces/ImageServiceInterface.php +++ b/stubs/generators/publish/utils/Interfaces/ImageServiceInterface.php @@ -4,7 +4,7 @@ interface ImageServiceInterface { - public function upload(string $name, string $path, string|null $defaultImage = null, string $disk = 'local', int $width = 500, int $height = 500, bool $isCustomUpload = false): string|null; + public function upload(string $name, string $path, ?string $defaultImage = null, ?string $disk = null, int $width = 500, int $height = 500, ?bool $crop = null, ?bool $aspectRatio = null, ?bool $isCustomUpload = false): ?string; - public function delete(string|null $image, string $disk = 'local'): void; + public function delete(?string $image, string $disk = 'local'): void; } diff --git a/stubs/generators/publish/utils/Services/ImageService.php b/stubs/generators/publish/utils/Services/ImageService.php index eca1ee55..314026f3 100644 --- a/stubs/generators/publish/utils/Services/ImageService.php +++ b/stubs/generators/publish/utils/Services/ImageService.php @@ -12,15 +12,20 @@ class ImageService implements ImageServiceInterface */ public function upload(string $name, string $path, ?string $defaultImage = null, ?string $disk = null, int $width = 500, int $height = 500, ?bool $crop = null, ?bool $aspectRatio = null, ?bool $isCustomUpload = false): ?string { - $crop = $crop ?? config('generator.image.crop') ?? true; - $aspectRatio = $aspectRatio ?? config('generator.image.aspect_ratio') ?? true; - $disk = $disk ?? config('generator.image.disk') ?? 'storage'; - $file = request()->file($name); if ($file && $file->isValid()) { if (!$isCustomUpload) { - return $this->handleFileUpload(file: $file, path: $path, defaultImage: $defaultImage, disk: $disk, width: $width, height: $height, crop: $crop, aspectRatio: $aspectRatio); + return $this->handleFileUpload([ + 'file' => $file, + 'path' => $path, + 'default_image' => $defaultImage, + 'disk' => $disk ?? config('generator.image.disk') ?? 'storage', + 'width' => $width, + 'height' => $height, + 'crop' => $crop ?? config('generator.image.crop') ?? true, + 'aspect_ratio' => $aspectRatio ?? config('generator.image.aspect_ratio') ?? true, + ]); } else { // TODO: implement custom upload } @@ -32,20 +37,20 @@ public function upload(string $name, string $path, ?string $defaultImage = null, /** * Handle the file upload process. */ - private function handleFileUpload(mixed $file, string $path, ?string $defaultImage, string $disk, int $width, int $height, bool $crop, bool $aspectRatio): string + private function handleFileUpload(array $options): string { - $filename = $this->generateFilename($file); + $filename = $this->generateFilename($options['file']); - $image = $this->processImage(file: $file, width: $width, height: $height, crop: $crop, aspectRatio: $aspectRatio); + $image = $this->processImage($options); - if ($disk === 's3') { - Storage::disk('s3')->put($path . '/' . $filename, (string) $image, 'public'); + if ($options['disk'] === 's3') { + Storage::disk('s3')->put($options['path'] . '/' . $filename, (string) $image, 'public'); } else { - $this->saveToLocal(image: $image, path: $path, filename: $filename); + $this->saveToLocal(image: $image, path: $options['path'], filename: $filename); } - if ($defaultImage) { - $this->delete(image: $path . $defaultImage, disk: $disk); + if ($options['default_image']) { + $this->delete(image: $options['path'] . $options['default_image'], disk: $options['disk']); } return $filename; @@ -66,13 +71,13 @@ private function generateFilename(mixed $file): string /** * Process the image using the appropriate version of the Intervention/Image library. */ - private function processImage(mixed $file, int $width, int $height, bool $crop, bool $aspectRatio): mixed + private function processImage(array $options): mixed { if (class_exists(\Intervention\Image\Facades\Image::class)) { // v2 - return \Intervention\Image\Facades\Image::make($file) - ->resize($width, $height, function ($constraint) use ($crop, $aspectRatio) { - if ($crop) { - if ($aspectRatio) { + return \Intervention\Image\Facades\Image::make($options['file']) + ->resize($options['width'], $options['height'], function ($constraint) use ($options) { + if ($options['crop']) { + if ($options['aspect_ratio']) { $constraint->aspectRatio(); } $constraint->upsize(); @@ -82,15 +87,15 @@ private function processImage(mixed $file, int $width, int $height, bool $crop, } if (class_exists(\Intervention\Image\Laravel\Facades\Image::class)) { // v3 - $imageInstance = \Intervention\Image\Laravel\Facades\Image::read($file); + $imageInstance = \Intervention\Image\Laravel\Facades\Image::read($options['file']); $encode = new \Intervention\Image\Encoders\WebpEncoder(65); - if ($crop) { - if ($aspectRatio) { - return $imageInstance->scaleDown(width: $width, height: $height)->encode($encode); + if ($options['crop']) { + if ($options['aspect_ratio']) { + return $imageInstance->scaleDown(width: $options['width'], height: $options['height'])->encode($encode); } - return $imageInstance->resizeDown(width: $width, height: $height)->encode($encode); + return $imageInstance->resizeDown(width: $options['width'], height: $options['height'])->encode($encode); } return $imageInstance->encode($encode); @@ -108,11 +113,7 @@ private function saveToLocal(mixed $image, string $path, string $filename): void throw new \RuntimeException(sprintf('Directory "%s" was not created', $path)); } - if (class_exists(\Intervention\Image\Facades\Image::class)) { // v2 - $image->save($path . $filename); - } elseif (class_exists(\Intervention\Image\Laravel\Facades\Image::class)) { // v3 - $image->save($path . $filename); - } + $image->save($path . $filename); } /** diff --git a/stubs/generators/publish/utils/helper.php b/stubs/generators/publish/utils/helper.php index fc2c0e28..cf6d27d3 100644 --- a/stubs/generators/publish/utils/helper.php +++ b/stubs/generators/publish/utils/helper.php @@ -9,26 +9,42 @@ function is_active_menu(string|array $route): string $activeClass = ' active'; if (is_string($route)) { - if (request()->is(substr($route . '*', 1))) return $activeClass; + if (request()->is(substr($route . '*', 1))) { + return $activeClass; + } - if (request()->is(str($route)->slug() . '*')) return $activeClass; + if (request()->is(str($route)->slug() . '*')) { + return $activeClass; + } - if (request()->segment(2) == str($route)->before('/')) return $activeClass; + if (request()->segment(2) === str($route)->before('/')) { + return $activeClass; + } - if (request()->segment(3) == str($route)->after('/')) return $activeClass; + if (request()->segment(3) === str($route)->after('/')) { + return $activeClass; + } } if (is_array($route)) { foreach ($route as $value) { $actualRoute = str($value)->remove(' view')->plural(); - if (request()->is(substr($actualRoute . '*', 1))) return $activeClass; + if (request()->is(substr($actualRoute . '*', 1))) { + return $activeClass; + } - if (request()->is(str($actualRoute)->slug() . '*')) return $activeClass; + if (request()->is(str($actualRoute)->slug() . '*')) { + return $activeClass; + } - if (request()->segment(2) == $actualRoute) return $activeClass; + if (request()->segment(2) === $actualRoute) { + return $activeClass; + } - if (request()->segment(3) == $actualRoute) return $activeClass; + if (request()->segment(3) === $actualRoute) { + return $activeClass; + } } } diff --git a/stubs/generators/publish/views/profile.blade.php b/stubs/generators/publish/views/profile.blade.php index c7b3d8e5..34d6f4f8 100644 --- a/stubs/generators/publish/views/profile.blade.php +++ b/stubs/generators/publish/views/profile.blade.php @@ -35,19 +35,19 @@
    + enctype="multipart/form-data"> @csrf @method('PUT')
    + class="form-control @error('email', 'updateProfileInformation') is-invalid @enderror" + id="email" placeholder="{{ __('E-mail Address') }}" + value="{{ old('email') ?? auth()?->user()?->email }}" required> @error('email', 'updateProfileInformation') - + {{ $message }} @enderror @@ -56,11 +56,11 @@ class="form-control @error('email', 'updateProfileInformation') is-invalid @ende
    + class="form-control @error('name', 'updateProfileInformation') is-invalid @enderror" + id="name" placeholder="{{ __('Name') }}" + value="{{ old('name') ?? auth()?->user()?->name }}" required> @error('name', 'updateProfileInformation') - + {{ $message }} @enderror @@ -69,18 +69,19 @@ class="form-control @error('name', 'updateProfileInformation') is-invalid @ende
    - @if (auth()?->user()?->avatar ) + @if (auth()?->user()?->avatar) Avatar + alt="Avatar"> @else {{-- storage --}} - Avatar + Avatar {{-- public --}} - {{-- Avatar--}} + {{-- Avatar --}} {{-- s3 --}} - {{-- Avatar--}} + {{-- Avatar --}} @endif
    @@ -88,10 +89,12 @@ class="form-control @error('name', 'updateProfileInformation') is-invalid @ende
    - + @error('avatar', 'updateProfileInformation') - + {{ $message }} @enderror @@ -125,10 +128,10 @@ class="form-control @error('name', 'updateProfileInformation') is-invalid @ende
    + class="form-control @error('current_password', 'updatePassword') is-invalid @enderror" + id="password" placeholder="Current Password" required> @error('current_password', 'updatePassword') - + {{ $message }} @enderror @@ -137,10 +140,10 @@ class="form-control @error('current_password', 'updatePassword') is-invalid @end
    + class="form-control @error('password', 'updatePassword') is-invalid @enderror" + id="password" placeholder="New Password" required> @error('password', 'updatePassword') - + {{ $message }} @enderror @@ -149,7 +152,7 @@ class="form-control @error('password', 'updatePassword') is-invalid @enderror"
    + name="password_confirmation" placeholder="Confirm Password" required>
    @@ -194,10 +197,10 @@ class="form-control @error('password', 'updatePassword') is-invalid @enderror"
    + type="submit">{{ __('Disable Two Factor Authentication') }} @else + type="submit">{{ __('Enable Two Factor Authentication') }} @endif diff --git a/stubs/generators/publish/views/users/include/form.blade.php b/stubs/generators/publish/views/users/include/form.blade.php index 7894e8d4..e10cb906 100644 --- a/stubs/generators/publish/views/users/include/form.blade.php +++ b/stubs/generators/publish/views/users/include/form.blade.php @@ -109,11 +109,10 @@ class="form-control @error('avatar') is-invalid @enderror">
    - @if ($user->avatar == null) - avatar + @if (!$user->avatar) + Avatar @else - avatar") }}" alt="avatar"> + Avatar @endif
    diff --git a/stubs/generators/publish/views/users/show.blade.php b/stubs/generators/publish/views/users/show.blade.php index 8351ff00..6e1ee921 100644 --- a/stubs/generators/publish/views/users/show.blade.php +++ b/stubs/generators/publish/views/users/show.blade.php @@ -37,11 +37,10 @@
    diff --git a/stubs/generators/views/forms/image.stub b/stubs/generators/views/forms/image.stub index 34e4ab59..d80b3070 100644 --- a/stubs/generators/views/forms/image.stub +++ b/stubs/generators/views/forms/image.stub @@ -3,7 +3,7 @@
    @if ({{defaultImageCodeForm}}) - {{fieldUcWords}} + {{fieldUcWords}} @else {{fieldUcWords}} @endif diff --git a/tests/GeneratorTest.php b/tests/GeneratorTest.php index 21b5ce9d..b7374d71 100644 --- a/tests/GeneratorTest.php +++ b/tests/GeneratorTest.php @@ -4,6 +4,7 @@ use Illuminate\Foundation\Testing\Concerns\InteractsWithViews; use PHPUnit\Framework\Attributes\Test; +use Random\RandomException; class GeneratorTest extends TestCase { @@ -41,6 +42,9 @@ public function it_can_render_api_generator_create_page(): void $this->get('/api-generators/create')->assertStatus(200)->assertSee('API Generators'); } + /** + * @throws RandomException + */ #[Test] public function it_can_create_new_module(): void { @@ -51,13 +55,18 @@ public function it_can_create_new_module(): void $this->post('/simple-generators', json_decode('{"requireds":["yes","yes","yes","yes","yes","yes","yes","no","no","no","yes","yes","no","no","yes","yes","yes","yes","yes","yes","yes","yes","yes","yes"],"_token":"LIV8Mj4vCRSIGWhbQFVcZax6jwnsZMS7JAWGhdTe","_method":"POST","model":"'. $modelName .'","generate_type":"all","generate_variant":"default","generate_seeder":"on","generate_factory":"on","fields":["q","w","e","r","t","y","u","i","o","p","a","s","d","f","g","h","j","k","l","z","x","c","v","b"],"column_types":["string","string","string","string","string","string","string","string","string","string","integer","integer","integer","integer","boolean","boolean","boolean","date","date","time","year","year","dateTime","enum"],"select_options":[null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,"PHP|Laravel"],"constrains":[null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null],"foreign_ids":[null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null],"on_update_foreign":[null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null],"on_delete_foreign":[null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null],"min_lengths":[null,null,null,null,null,null,null,null,null,null,null,"1",null,null,null,null,null,null,null,null,null,null,null,null],"max_lengths":[null,null,null,null,null,null,null,null,null,null,null,"100",null,null,null,null,null,null,null,null,null,null,null,null],"input_types":["text","textarea","email","tel","password","url","search","file","hidden","no-input","number","range","hidden","no-input","select","radio","datalist","date","month","time","select","datalist","datetime-local","select"],"file_types":[null,null,null,null,null,null,null,"image",null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null],"files_sizes":[null,null,null,null,null,null,null,"1024",null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null],"mimes":[null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null],"steps":[null,null,null,null,null,null,null,null,null,null,null,"1",null,null,null,null,null,null,null,null,null,null,null,null],"default_values":[null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null]}', true))->assertSuccessful(); } - function generateRandomString($length = 5): string + /** + * @throws RandomException + */ + public function generateRandomString($length = 5): string { $characters = 'abcdefghijklmnopqrstuvwxyz'; $charactersLength = strlen($characters); $randomString = ''; - for ($i = 0; $i < $length; $i++) $randomString .= $characters[random_int(0, $charactersLength - 1)]; + for ($i = 0; $i < $length; $i++) { + $randomString .= $characters[random_int(0, $charactersLength - 1)]; + } return $randomString; } From 59b6adce8a523b39203c615b7a12583310154f27 Mon Sep 17 00:00:00 2001 From: Zzzul Date: Thu, 11 Jul 2024 08:52:34 +0700 Subject: [PATCH 098/105] fix select type year and avatar not show in profile page :sunflower: --- resources/views/include/form.blade.php | 4 ++-- resources/views/simple-create.blade.php | 2 +- src/Generators/Views/FormViewGenerator.php | 2 +- stubs/generators/publish/views/layouts/header.blade.php | 2 +- stubs/generators/publish/views/profile.blade.php | 2 +- stubs/generators/views/forms/image.stub | 2 +- 6 files changed, 7 insertions(+), 7 deletions(-) diff --git a/resources/views/include/form.blade.php b/resources/views/include/form.blade.php index 73af955b..91566ab6 100644 --- a/resources/views/include/form.blade.php +++ b/resources/views/include/form.blade.php @@ -17,7 +17,7 @@ {{-- generate type --}}
    -

    {{ __('Generate Type') }}

    +

    {{ __('Generator Type') }}

    @@ -38,7 +38,7 @@ {{-- generate variant --}}
    -

    {{ __('Generate Variant') }}

    +

    {{ __('Generator Variant') }}

    diff --git a/resources/views/simple-create.blade.php b/resources/views/simple-create.blade.php index aeecafdc..7cfc6a37 100644 --- a/resources/views/simple-create.blade.php +++ b/resources/views/simple-create.blade.php @@ -45,7 +45,7 @@ class="text-secondary">{{ __("Use '/' for generate a sub folder. e.g.: Main/Prod {{-- generate type --}}
    -

    Generate Type

    +

    {{ __('Generator Type') }}

    */ $options = " - @foreach (range($firstYear, hrtime(\"%Y\", time())) as \$year) + @foreach (range($firstYear, date('Y')) as \$year) diff --git a/stubs/generators/publish/views/layouts/header.blade.php b/stubs/generators/publish/views/layouts/header.blade.php index d2ccc9fa..5d9b7840 100644 --- a/stubs/generators/publish/views/layouts/header.blade.php +++ b/stubs/generators/publish/views/layouts/header.blade.php @@ -63,7 +63,7 @@
    - @if (auth()?->user()?->avatar == null) + @if (!auth()?->user()?->avatar) Avatar @else diff --git a/stubs/generators/publish/views/profile.blade.php b/stubs/generators/publish/views/profile.blade.php index 34d6f4f8..250dbe83 100644 --- a/stubs/generators/publish/views/profile.blade.php +++ b/stubs/generators/publish/views/profile.blade.php @@ -69,7 +69,7 @@ class="form-control @error('name', 'updateProfileInformation') is-invalid @ende
    - @if (auth()?->user()?->avatar) + @if (!auth()?->user()?->avatar) Avatar @else diff --git a/stubs/generators/views/forms/image.stub b/stubs/generators/views/forms/image.stub index d80b3070..db25f591 100644 --- a/stubs/generators/views/forms/image.stub +++ b/stubs/generators/views/forms/image.stub @@ -19,7 +19,7 @@ {{ $message }} @enderror -
    +
    {{ __('Leave the {{fieldLowercase}} blank if you don`t want to change it.') }}
    From 5a0a4790709bff17815470d9889ca7b7274cc577 Mon Sep 17 00:00:00 2001 From: Zzzul Date: Wed, 17 Jul 2024 11:50:53 +0700 Subject: [PATCH 099/105] remove unused variable in generator api controller, update stub, and register request :sunflower: --- src/Generators/ControllerGenerator.php | 30 +++++++++---------- .../controller-api-with-upload-file.stub | 13 ++++---- .../controllers/controller-api.stub | 10 +++---- stubs/generators/controllers/controller.stub | 2 +- .../publish/requests/Auth/RegisterRequest.php | 26 +++++++++++++++- 5 files changed, 52 insertions(+), 29 deletions(-) diff --git a/src/Generators/ControllerGenerator.php b/src/Generators/ControllerGenerator.php index ed69d242..f8756ee2 100644 --- a/src/Generators/ControllerGenerator.php +++ b/src/Generators/ControllerGenerator.php @@ -122,11 +122,11 @@ public function generate(array $request): void $relations .= "])->"; $relations = str_replace("', ])->", "'])->", $relations); } else { - $relations .= "$" . $modelNameSingularCamelCase . "->load("; + $relations .= "$" . $modelNameSingularCamelCase . "->load(["; $countForeignId = count(array_keys($request['column_types'], 'foreignId')); - $query = "$modelNameSingularPascalCase::with("; + $query = "$modelNameSingularPascalCase::with(["; foreach ($request['constrains'] as $i => $constrain) { if ($constrain != null) { @@ -158,8 +158,8 @@ public function generate(array $request): void } } - $query .= ")"; - $relations .= ");\n\n\t\t"; + $query .= "])"; + $relations .= "]);\n\n\t\t"; $query = str_replace("''", "', '", $query); $relations = str_replace("''", "', '", $relations); @@ -172,7 +172,15 @@ public function generate(array $request): void * User::create($request->validated()); * $user->update($request->validated()); */ - $insertDataAction = "$$modelNameSingularCamelCase = " . $modelNameSingularPascalCase . "::create(\$request->validated());"; + + if (GeneratorUtils::isGenerateApi()) { + // remove unused variable + // $user = User::create($request->validated()); + $insertDataAction = "$$modelNameSingularCamelCase = $modelNameSingularPascalCase::create(\$request->validated());"; + }else{ + $insertDataAction = "$modelNameSingularPascalCase::create(\$request->validated());"; + } + $updateDataAction = "\$" . $modelNameSingularCamelCase . "->update(\$request->validated());"; $requestValidatedAttr = ""; @@ -183,7 +191,7 @@ public function generate(array $request): void * User::create($validated); * $user->update($validated); */ - $insertDataAction = "$$modelNameSingularCamelCase = " . $modelNameSingularPascalCase . "::create(\$validated);"; + $insertDataAction = "$modelNameSingularPascalCase::create(\$validated);"; $updateDataAction = "\$" . $modelNameSingularCamelCase . "->update(\$validated);"; $requestValidatedAttr = "\$validated = \$request->validated();\n"; } @@ -436,16 +444,6 @@ public function generate(array $request): void $updateDataAction = $singleFormUpdateDataAction; } - if (!GeneratorUtils::isGenerateApi()) { - // remove unused variable - // $user = User::create($request->validated()); - $insertDataAction = str_replace( - "$$modelNameSingularCamelCase = " . $modelNameSingularPascalCase . "::create(\$request->validated());", - $modelNameSingularPascalCase . "::create(\$request->validated());", - $insertDataAction - ); - } - /** * default controller */ diff --git a/stubs/generators/controllers/controller-api-with-upload-file.stub b/stubs/generators/controllers/controller-api-with-upload-file.stub index 352699c7..fcc15892 100644 --- a/stubs/generators/controllers/controller-api-with-upload-file.stub +++ b/stubs/generators/controllers/controller-api-with-upload-file.stub @@ -43,7 +43,7 @@ class {{modelNameSingularPascalCase}}Controller extends Controller implements Ha return (new {{modelNameSingularPascalCase}}Collection(${{modelNamePluralCamelCase}})) ->additional([ 'message' => 'The {{modelNameCleanPlural}} was received successfully.', - 'success' => true, + // 'success' => true, // 'status_code' => Response::HTTP_OK ]); } @@ -61,7 +61,7 @@ class {{modelNameSingularPascalCase}}Controller extends Controller implements Ha return (new {{modelNameSingularPascalCase}}Resource(${{modelNameSingularCamelCase}})) ->additional([ 'message' => 'The {{modelNameCleanSingular}} was created successfully.', - 'success' => true, + // 'success' => true, // 'status_code' => Response::HTTP_CREATED ]) ->response() @@ -78,7 +78,7 @@ class {{modelNameSingularPascalCase}}Controller extends Controller implements Ha return (new {{modelNameSingularPascalCase}}Resource(${{modelNameSingularCamelCase}})) ->additional([ 'message' => 'The {{modelNameCleanSingular}} was received successfully.', - 'success' => true, + // 'success' => true, // 'status_code' => Response::HTTP_OK ]); } @@ -97,7 +97,7 @@ class {{modelNameSingularPascalCase}}Controller extends Controller implements Ha return (new {{modelNameSingularPascalCase}}Resource(${{modelNameSingularCamelCase}})) ->additional([ 'message' => 'The {{modelNameCleanSingular}} was updated successfully.', - 'success' => true, + // 'success' => true, // 'status_code' => Response::HTTP_OK ]); } @@ -117,14 +117,14 @@ class {{modelNameSingularPascalCase}}Controller extends Controller implements Ha return (new {{modelNameSingularPascalCase}}Resource(null)) ->additional([ 'message' => 'The {{modelNameCleanSingular}} was deleted successfully.', - 'success' => true, + // 'success' => true, // 'status_code' => Response::HTTP_OK ]); } catch (\Exception $e) { return (new {{modelNameSingularPascalCase}}Resource(null)) ->additional([ 'message' => $e->getMessage(), - 'success' => false, + // 'success' => false, // 'status_code' => Response::HTTP_INTERNAL_SERVER_ERROR ]) ->response() @@ -134,6 +134,7 @@ class {{modelNameSingularPascalCase}}Controller extends Controller implements Ha /** * Casting all images + * * TODO: casting image in model (soon) */ public function castImages({{modelNameSingularPascalCase}} ${{modelNameSingularCamelCase}}): void diff --git a/stubs/generators/controllers/controller-api.stub b/stubs/generators/controllers/controller-api.stub index 170b488b..2cf832c4 100644 --- a/stubs/generators/controllers/controller-api.stub +++ b/stubs/generators/controllers/controller-api.stub @@ -35,7 +35,7 @@ class {{modelNameSingularPascalCase}}Controller extends Controller implements Ha return (new {{modelNameSingularPascalCase}}Collection({{modelNameSingularPascalCase}}::{{relations}}latest()->paginate(request()->query('per_page', 10)))) ->additional([ 'message' => 'The {{modelNameCleanPlural}} was received successfully.', - 'success' => true, + // 'success' => true, // 'status_code' => Response::HTTP_OK ]); } @@ -51,7 +51,7 @@ class {{modelNameSingularPascalCase}}Controller extends Controller implements Ha return (new {{modelNameSingularPascalCase}}Resource(${{modelNameSingularCamelCase}})) ->additional([ 'message' => 'The {{modelNameCleanSingular}} was created successfully.', - 'success' => true, + // 'success' => true, // 'status_code' => Response::HTTP_CREATED ]) ->response() @@ -66,7 +66,7 @@ class {{modelNameSingularPascalCase}}Controller extends Controller implements Ha return (new {{modelNameSingularPascalCase}}Resource({{modelNameSingularPascalCase}}::{{relations}}findOrFail($id))) ->additional([ 'message' => 'The {{modelNameCleanSingular}} was received successfully.', - 'success' => true, + // 'success' => true, // 'status_code' => Response::HTTP_OK ]); } @@ -83,7 +83,7 @@ class {{modelNameSingularPascalCase}}Controller extends Controller implements Ha return (new {{modelNameSingularPascalCase}}Resource(${{modelNameSingularCamelCase}})) ->additional([ 'message' => 'The {{modelNameCleanSingular}} was updated successfully.', - 'success' => true, + // 'success' => true, // 'status_code' => Response::HTTP_OK ]); } @@ -99,7 +99,7 @@ class {{modelNameSingularPascalCase}}Controller extends Controller implements Ha return (new {{modelNameSingularPascalCase}}Resource(null)) ->additional([ 'message' => 'The {{modelNameCleanSingular}} was deleted successfully.', - 'success' => true, + // 'success' => true, // 'status_code' => Response::HTTP_OK ]); } catch (\Exception $e) { diff --git a/stubs/generators/controllers/controller.stub b/stubs/generators/controllers/controller.stub index af60f257..a5bf8f05 100644 --- a/stubs/generators/controllers/controller.stub +++ b/stubs/generators/controllers/controller.stub @@ -97,7 +97,7 @@ class {{modelNameSingularPascalCase}}Controller extends Controller implements Ha ${{modelNameSingularCamelCase}}->delete(); return to_route('{{modelNamePluralKebabCase}}.index')->with('success', __('The {{modelNameCleanSingular}} was deleted successfully.')); - } catch (\Throwable $th) { + } catch (\Exception $e) { return to_route('{{modelNamePluralKebabCase}}.index')->with('error', __("The {{modelNameCleanSingular}} can't be deleted because it's related to another table.")); } } diff --git a/stubs/generators/publish/requests/Auth/RegisterRequest.php b/stubs/generators/publish/requests/Auth/RegisterRequest.php index e9ca3536..5d8897db 100644 --- a/stubs/generators/publish/requests/Auth/RegisterRequest.php +++ b/stubs/generators/publish/requests/Auth/RegisterRequest.php @@ -3,6 +3,7 @@ namespace App\Http\Requests\Auth; use Illuminate\Foundation\Http\FormRequest; +use Illuminate\Validation\Rules\Password; class RegisterRequest extends FormRequest { @@ -24,7 +25,30 @@ public function rules(): array return [ 'email' => ['required', 'string', 'email', 'max:255', 'unique:users,email'], 'name' => ['required', 'string', 'max:255'], - 'password' => ['required', 'string', 'min:8', 'confirmed'], + 'password' => $this->passwordRules(), + ]; + } + + protected function passwordRules(): array + { + if (app()->isProduction()) { + return [ + 'required', + 'string', + 'confirmed', + Password::min(8) + ->letters() + ->mixedCase() + ->numbers() + ->symbols() + ->uncompromised() + ]; + } + + return [ + 'required', + 'string', + 'confirmed', ]; } } From acd81ac0381bbcfa2357fbd9a21e43a381e5f56c Mon Sep 17 00:00:00 2001 From: Zzzul Date: Thu, 25 Jul 2024 14:03:03 +0700 Subject: [PATCH 100/105] fix menu generator in permission name :hammer: --- src/Generators/MenuGenerator.php | 80 +++++++++++++++----------------- 1 file changed, 38 insertions(+), 42 deletions(-) diff --git a/src/Generators/MenuGenerator.php b/src/Generators/MenuGenerator.php index 76115139..aa1273f3 100644 --- a/src/Generators/MenuGenerator.php +++ b/src/Generators/MenuGenerator.php @@ -48,7 +48,7 @@ protected function generateNewAllMenu(array $request, string $model, array $conf title: GeneratorUtils::cleanPluralUcWords($request['new_menu'] ?? $model), icon: $request['new_icon'], route: '/' . GeneratorUtils::pluralKebabCase($model), - submenu: isset($request['new_submenu']) ? $request['new_submenu'] : null, + submenu: $request['new_submenu'] ?? null, model: $model ); @@ -103,22 +103,22 @@ protected function generateNewSubMenu(array $menu, string $model, array $configS /** * If submenus[] is empty, move menu at this index into the submenus[] and make route and permission to null */ - if ($configSidebar[$indexSidebar]['menus'][$indexMenu]['submenus'] == []) { - $configSidebar[$indexSidebar]['menus'][$indexMenu]['submenus'][] = [ - 'title' => $configSidebar[$indexSidebar]['menus'][$indexMenu]['title'], - 'route' => '/' . GeneratorUtils::pluralKebabCase($model), - 'permission' => [GeneratorUtils::cleanSingularLowerCase($model) . ' view'], - ]; - - /** - * Push to permissions on menus - */ - $configSidebar[$indexSidebar]['menus'][$indexMenu]['permissions'][] = [GeneratorUtils::cleanSingularLowerCase($model) . ' view'] . "', '" . $newPermission; - - $configSidebar[$indexSidebar]['menus'][$indexMenu]['route'] = null; - $configSidebar[$indexSidebar]['menus'][$indexMenu]['permission'] = null; - } else { - $configSidebar[$indexSidebar]['menus'][$indexMenu]['permissions'][] = $newPermission; + switch (count($configSidebar[$indexSidebar]['menus'][$indexMenu]['submenus'])) { + case 0: + $configSidebar[$indexSidebar]['menus'][$indexMenu]['submenus'][] = [ + 'title' => $configSidebar[$indexSidebar]['menus'][$indexMenu]['title'], + 'route' => '/' . GeneratorUtils::pluralKebabCase($model), + 'permission' => [GeneratorUtils::cleanSingularLowerCase($model) . ' view'], + ]; + + $configSidebar[$indexSidebar]['menus'][$indexMenu]['permissions'][] = [GeneratorUtils::cleanSingularLowerCase($model) . ' view'] . "', '" . $newPermission; + + $configSidebar[$indexSidebar]['menus'][$indexMenu]['route'] = null; + $configSidebar[$indexSidebar]['menus'][$indexMenu]['permission'] = null; + break; + default: + $configSidebar[$indexSidebar]['menus'][$indexMenu]['permissions'][] = $newPermission; + break; } /** @@ -150,7 +150,7 @@ protected function generateFile(string $jsonToArrayString): void $stringConfigCode = $stringConfig->before($search); } - $template = $stringConfigCode . $search . $jsonToArrayString . "\n];"; + $template = "{$stringConfigCode}{$search}{$jsonToArrayString}\n];"; file_put_contents(base_path('config/generator.php'), $template); } @@ -160,31 +160,27 @@ protected function generateFile(string $jsonToArrayString): void */ protected function setNewMenu(string $title, string $icon, string $route, string|null $submenu = null, string $model): array { - if (isset($submenu)) { - $newMenu = [ - 'title' => GeneratorUtils::cleanPluralUcWords($title), - 'icon' => $icon, - 'route' => null, - 'permission' => null, - 'permissions' => [GeneratorUtils::cleanSingularLowerCase($model) . ' view'], - 'submenus' => [ - [ - 'title' => GeneratorUtils::cleanPluralUcWords($submenu), - 'route' => '/' . str(GeneratorUtils::pluralKebabCase($model))->remove('/'), - 'permission' => GeneratorUtils::cleanSingularLowerCase($model) . ' view', - ] + $newMenu = $submenu ? [ + 'title' => GeneratorUtils::cleanPluralUcWords($title), + 'icon' => $icon, + 'route' => null, + 'permission' => null, + 'permissions' => [GeneratorUtils::cleanSingularLowerCase($model) . ' view'], + 'submenus' => [ + [ + 'title' => GeneratorUtils::cleanPluralUcWords($submenu), + 'route' => '/' . str(GeneratorUtils::pluralKebabCase($model))->remove('/'), + 'permission' => GeneratorUtils::cleanSingularLowerCase($model) . ' view', ] - ]; - } else { - $newMenu = [ - 'title' => GeneratorUtils::cleanPluralUcWords($title), - 'icon' => $icon, - 'route' => '/' . str(GeneratorUtils::pluralKebabCase($route))->remove('/'), - 'permission' => GeneratorUtils::cleanSingularLowerCase($title) . ' view', - 'permissions' => [], - 'submenus' => [] - ]; - } + ] + ] : [ + 'title' => GeneratorUtils::cleanPluralUcWords($title), + 'icon' => $icon, + 'route' => '/' . str(GeneratorUtils::pluralKebabCase($route))->remove('/'), + 'permission' => GeneratorUtils::cleanSingularLowerCase($model) . ' view', + 'permissions' => [], + 'submenus' => [] + ]; return $newMenu; } From b4935abfc67347e549158a29b1b2663cbb4f4c95 Mon Sep 17 00:00:00 2001 From: Zzzul Date: Thu, 25 Jul 2024 14:10:58 +0700 Subject: [PATCH 101/105] fix publish controller in full version :sunflower: --- src/Providers/GeneratorServiceProvider.php | 11 ++++++++++- .../generators/publish/controllers/UserController.php | 4 ++-- 2 files changed, 12 insertions(+), 3 deletions(-) diff --git a/src/Providers/GeneratorServiceProvider.php b/src/Providers/GeneratorServiceProvider.php index 405fb629..1221dfe6 100644 --- a/src/Providers/GeneratorServiceProvider.php +++ b/src/Providers/GeneratorServiceProvider.php @@ -42,7 +42,16 @@ public function boot(): void // Controllers $this->publishes([ - __DIR__ . '/../../stubs/generators/publish/controllers' => app_path('Http/Controllers') + __DIR__ . '/../../stubs/generators/publish/controllers/ProfileController.php' => app_path('Http/Controllers/ProfileController.php') + ], 'generator-controller'); + + $this->publishes([ + __DIR__ . '/../../stubs/generators/publish/controllers/RoleAndPermissionController.php' => app_path('Http/Controllers/RoleAndPermissionController.php') + ], 'generator-controller'); + + + $this->publishes([ + __DIR__ . '/../../stubs/generators/publish/controllers/UserController.php' => app_path('Http/Controllers/UserController.php') ], 'generator-controller'); // Requests diff --git a/stubs/generators/publish/controllers/UserController.php b/stubs/generators/publish/controllers/UserController.php index 2c5b9379..a53f2e14 100644 --- a/stubs/generators/publish/controllers/UserController.php +++ b/stubs/generators/publish/controllers/UserController.php @@ -115,7 +115,7 @@ public function update(UpdateUserRequest $request, User $user): RedirectResponse $validated = $request->validated(); $validated['avatar'] = $this->imageService->upload(name: 'avatar', path: $this->avatarPath, defaultImage: $user?->avatar); - if (is_null($request->password)) { + if (!$request->password) { unset($validated['password']); } else { $validated['password'] = bcrypt($request->password); @@ -141,7 +141,7 @@ public function destroy(User $user): RedirectResponse $user->delete(); - $this->imageService->delete(image: $this->avatarPath . $avatar); + $this->imageService->delete(image: "{$this->avatarPath}{$avatar}"); return to_route('users.index')->with('success', __('The user was deleted successfully.')); } catch (\Exception $e) { From 3281d798e9c71347c1e044f75fdca4a8f92660ee Mon Sep 17 00:00:00 2001 From: Zzzul Date: Thu, 25 Jul 2024 15:00:29 +0700 Subject: [PATCH 102/105] fix validation for generate model & migration :rocket: --- src/Generators/Services/GeneratorService.php | 8 ++++++ src/Http/Controllers/GeneratorController.php | 22 ++++++++-------- .../Controllers/SimpleGeneratorController.php | 26 ++++++++++++------- src/Http/Requests/StoreGeneratorRequest.php | 4 ++- .../controllers/controller-api.stub | 2 +- 5 files changed, 39 insertions(+), 23 deletions(-) diff --git a/src/Generators/Services/GeneratorService.php b/src/Generators/Services/GeneratorService.php index 8a1d307f..87e5b2a6 100644 --- a/src/Generators/Services/GeneratorService.php +++ b/src/Generators/Services/GeneratorService.php @@ -101,6 +101,14 @@ public function onlyGenerateModelAndMigration(array $request): void (new ModelGenerator)->generate($request); (new MigrationGenerator)->generate($request); + + if (isset($request['generate_seeder'])) { + (new SeederGenerator)->generate($request); + } + + if (isset($request['generate_factory'])) { + (new FactoryGenerator)->generate($request); + } } /** diff --git a/src/Http/Controllers/GeneratorController.php b/src/Http/Controllers/GeneratorController.php index 99cf3b43..a95015d1 100644 --- a/src/Http/Controllers/GeneratorController.php +++ b/src/Http/Controllers/GeneratorController.php @@ -18,7 +18,7 @@ class GeneratorController extends BaseController { use AuthorizesRequests, DispatchesJobs, ValidatesRequests; - public function __construct(protected GeneratorService $generatorService) + public function __construct(public GeneratorService $generatorService) { // } @@ -36,20 +36,20 @@ public function create(): View */ public function store(StoreGeneratorRequest $request): JsonResponse { - if ($request->generate_type == GeneratorType::ALL->value) { - $this->generatorService->generate($request->validated()); - } else { - $this->generatorService->onlyGenerateModelAndMigration($request->validated()); + switch ($request->generate_type) { + case GeneratorType::ALL->value: + $this->generatorService->generate($request->validated()); + break; + default: + $this->generatorService->onlyGenerateModelAndMigration($request->validated()); + break; } $model = GeneratorUtils::setModelName($request->model, 'default'); - if ($request->generate_type == GeneratorType::ALL->value) { - // go to new route - $route = GeneratorUtils::isGenerateApi() ? 'api/' . GeneratorUtils::pluralKebabCase($model) : GeneratorUtils::pluralKebabCase($model); - } else { - $route = request()->path() . '/create'; - } + $route = $request->generate_type == GeneratorType::ALL->value + ? (GeneratorUtils::isGenerateApi() ? 'api/' . GeneratorUtils::pluralKebabCase($model) : GeneratorUtils::pluralKebabCase($model)) + : request()->path() . '/create'; return response()->json([ 'message' => 'success', diff --git a/src/Http/Controllers/SimpleGeneratorController.php b/src/Http/Controllers/SimpleGeneratorController.php index 13acf03d..21b22ff9 100644 --- a/src/Http/Controllers/SimpleGeneratorController.php +++ b/src/Http/Controllers/SimpleGeneratorController.php @@ -2,8 +2,7 @@ namespace EvdigiIna\Generator\Http\Controllers; -use EvdigiIna\Generator\Enums\GeneratorType; -use EvdigiIna\Generator\Enums\GeneratorVariant; +use EvdigiIna\Generator\Enums\{GeneratorType, GeneratorVariant}; use EvdigiIna\Generator\Generators\Services\GeneratorService; use Symfony\Component\HttpFoundation\Response; use EvdigiIna\Generator\Http\Requests\StoreSimpleGeneratorRequest; @@ -34,7 +33,7 @@ public function store(StoreSimpleGeneratorRequest $request): \Illuminate\Http\Js $validated['generate_variant'] = GeneratorVariant::DEFAULT->value; /** - * will added in next realease + * will added in next release * now it's not working, because it's not implemented * only focus to fix the bug */ @@ -44,17 +43,24 @@ public function store(StoreSimpleGeneratorRequest $request): \Illuminate\Http\Js // return response()->json($checkFile, 403); // } - if ($request->generate_type == GeneratorType::ALL->value) { - $this->generatorService->generate($validated); - } else { - $this->generatorService->onlyGenerateModelAndMigration($validated); + switch ($request->generate_type) { + case GeneratorType::ALL->value: + $this->generatorService->generate($validated); + break; + default: + $this->generatorService->onlyGenerateModelAndMigration($validated); + break; } - $model = GeneratorUtils::setModelName($validated['model'], 'default'); + $model = GeneratorUtils::setModelName($request->model, 'default'); + + $route = $request->generate_type == GeneratorType::ALL->value + ? (GeneratorUtils::isGenerateApi() ? 'api/' . GeneratorUtils::pluralKebabCase($model) : GeneratorUtils::pluralKebabCase($model)) + : request()->path() . '/create'; return response()->json([ - 'message' => 'Success', - 'route' => GeneratorUtils::isGenerateApi() ? 'api/' . GeneratorUtils::pluralKebabCase($model) : GeneratorUtils::pluralKebabCase($model) + 'message' => 'success', + 'route' => $route ], Response::HTTP_CREATED); } } diff --git a/src/Http/Requests/StoreGeneratorRequest.php b/src/Http/Requests/StoreGeneratorRequest.php index 20e0582d..e3ba2e0c 100644 --- a/src/Http/Requests/StoreGeneratorRequest.php +++ b/src/Http/Requests/StoreGeneratorRequest.php @@ -58,7 +58,9 @@ public function rules(): array 'generate_variant' => ['required'], ]; - if(GeneratorUtils::isGenerateApi()) return $validations; + if(GeneratorUtils::isGenerateApi() || request()->input('generate_type') == GeneratorType::ONLY_MODEL_AND_MIGRATION->value) { + return $validations; + } return [...$validations, ...$menuValidations]; } diff --git a/stubs/generators/controllers/controller-api.stub b/stubs/generators/controllers/controller-api.stub index 2cf832c4..4ed75efc 100644 --- a/stubs/generators/controllers/controller-api.stub +++ b/stubs/generators/controllers/controller-api.stub @@ -106,7 +106,7 @@ class {{modelNameSingularPascalCase}}Controller extends Controller implements Ha return (new {{modelNameSingularPascalCase}}Resource(null)) ->additional([ 'message' => $e->getMessage(), - 'success' => false, + // 'success' => false, // 'status_code' => Response::HTTP_INTERNAL_SERVER_ERROR ]) ->response() From e455325842870892134ce76f0793b8632f56a9bd Mon Sep 17 00:00:00 2001 From: Zzzul Date: Thu, 25 Jul 2024 16:40:09 +0700 Subject: [PATCH 103/105] fix cant delete user :fire: --- .../publish/controllers/UserController.php | 10 ++++---- .../fortify/PasswordValidationRules.php | 24 ++++++++++++------- .../publish/utils/Services/ImageService.php | 15 +++++++----- 3 files changed, 30 insertions(+), 19 deletions(-) diff --git a/stubs/generators/publish/controllers/UserController.php b/stubs/generators/publish/controllers/UserController.php index a53f2e14..7628cab5 100644 --- a/stubs/generators/publish/controllers/UserController.php +++ b/stubs/generators/publish/controllers/UserController.php @@ -137,13 +137,15 @@ public function update(UpdateUserRequest $request, User $user): RedirectResponse public function destroy(User $user): RedirectResponse { try { - $avatar = $user->avatar; + return DB::transaction(function () use ($user) { + $avatar = $user->avatar; - $user->delete(); + $user->delete(); - $this->imageService->delete(image: "{$this->avatarPath}{$avatar}"); + $this->imageService->delete(image: $this->avatarPath . $avatar); - return to_route('users.index')->with('success', __('The user was deleted successfully.')); + return to_route('users.index')->with('success', __('The user was deleted successfully.')); + }); } catch (\Exception $e) { return to_route('users.index')->with('error', __("The user can't be deleted because it's related to another table.")); } diff --git a/stubs/generators/publish/fortify/PasswordValidationRules.php b/stubs/generators/publish/fortify/PasswordValidationRules.php index 69e0fdbe..0bc04ff2 100644 --- a/stubs/generators/publish/fortify/PasswordValidationRules.php +++ b/stubs/generators/publish/fortify/PasswordValidationRules.php @@ -12,11 +12,21 @@ trait PasswordValidationRules */ protected function passwordRules(): array { - if(strtolower(env('APP_ENV')) === 'production') { - return [ + $validations = []; + + if (str_contains(request()->url(), 'edit')) { + $validations[] = [ + 'nullable', + ]; + } else { + $validations[] = [ 'required', - 'string', - 'confirmed', + 'confirmed' + ]; + } + + if (app()->isProduction()) { + $validations[] = [ Password::min(8) ->letters() ->mixedCase() @@ -26,10 +36,6 @@ protected function passwordRules(): array ]; } - return [ - 'required', - 'string', - 'confirmed', - ]; + return $validations; } } diff --git a/stubs/generators/publish/utils/Services/ImageService.php b/stubs/generators/publish/utils/Services/ImageService.php index 314026f3..17a92819 100644 --- a/stubs/generators/publish/utils/Services/ImageService.php +++ b/stubs/generators/publish/utils/Services/ImageService.php @@ -119,14 +119,17 @@ private function saveToLocal(mixed $image, string $path, string $filename): void /** * Delete an image from the specified disk. */ - public function delete(?string $image, string $disk = 'local'): void + public function delete(string|null $image = null, string $disk = 'local'): void { - if ($image) { - if ($disk === 's3') { + switch ($disk) { + case 's3': Storage::disk('s3')->delete($image); - } else if (file_exists($image)) { - unlink($image); - } + break; + default: + if ($image) { + @unlink($image); + } + break; } } } From fb6ffe29c6f81ec30491baa876fce93130fde9c4 Mon Sep 17 00:00:00 2001 From: Zzzul Date: Fri, 26 Jul 2024 15:27:49 +0700 Subject: [PATCH 104/105] fix password validation required in update user --- .../publish/fortify/PasswordValidationRules.php | 14 +------------- 1 file changed, 1 insertion(+), 13 deletions(-) diff --git a/stubs/generators/publish/fortify/PasswordValidationRules.php b/stubs/generators/publish/fortify/PasswordValidationRules.php index 0bc04ff2..b381fecc 100644 --- a/stubs/generators/publish/fortify/PasswordValidationRules.php +++ b/stubs/generators/publish/fortify/PasswordValidationRules.php @@ -2,7 +2,6 @@ namespace App\Actions\Fortify; -// use Laravel\Fortify\Rules\Password; use Illuminate\Validation\Rules\Password; trait PasswordValidationRules @@ -12,18 +11,7 @@ trait PasswordValidationRules */ protected function passwordRules(): array { - $validations = []; - - if (str_contains(request()->url(), 'edit')) { - $validations[] = [ - 'nullable', - ]; - } else { - $validations[] = [ - 'required', - 'confirmed' - ]; - } + $validations = in_array(request()->method(), ['PUT', 'PATCH']) ? ['nullable', 'min:5'] : ['required', 'confirmed']; if (app()->isProduction()) { $validations[] = [ From e38a38455b7e97abc772c1b225e4c4e5f7f7c200 Mon Sep 17 00:00:00 2001 From: Zzzul Date: Sat, 27 Jul 2024 08:52:45 +0700 Subject: [PATCH 105/105] wip input type password in null --- src/Generators/Views/FormViewGenerator.php | 6 ++++-- stubs/generators/views/forms/input-password.stub | 4 ++-- 2 files changed, 6 insertions(+), 4 deletions(-) diff --git a/src/Generators/Views/FormViewGenerator.php b/src/Generators/Views/FormViewGenerator.php index 360c615a..9fbdcf78 100644 --- a/src/Generators/Views/FormViewGenerator.php +++ b/src/Generators/Views/FormViewGenerator.php @@ -510,13 +510,15 @@ public function generate(array $request): void '{{fieldUcWords}}', '{{fieldSnakeCase}}', '{{fieldKebabCase}}', - '{{model}}' + '{{model}}', + '{{isNullable}}' ], [ $fieldUcWords, $fieldSnakeCase, GeneratorUtils::singularKebabCase($field), - $modelNameSingularCamelCase + $modelNameSingularCamelCase, + $request['requireds'][$i] == 'yes' ? "{{ empty(" . GeneratorUtils::singularCamelCase($model) .") ? ' required' : '' }}" : '' ], GeneratorUtils::getStub('views/forms/input-password') ); diff --git a/stubs/generators/views/forms/input-password.stub b/stubs/generators/views/forms/input-password.stub index 14e3984b..d4ae021c 100644 --- a/stubs/generators/views/forms/input-password.stub +++ b/stubs/generators/views/forms/input-password.stub @@ -1,7 +1,7 @@
    - + @error('{{fieldSnakeCase}}') {{ $message }} @@ -18,6 +18,6 @@
    - +
    {{ __('$fieldUcWords') }} - @if (" . $default['form_code'] . ") - \"$fieldUcWords\" - @else - \"$fieldUcWords\" - @endif -
    {{ __('$fieldUcWords') }}{{ $" . $modelNameSingularCamelCase . "->" . $fieldSnakeCase . " == 1 ? 'True' : 'False' }}
    {{ __('" . GeneratorUtils::cleanSingularUcWords($constrainModel) . "') }}{{ $" . $modelNameSingularCamelCase . "->" . GeneratorUtils::singularSnakeCase($constrainModel) . " ? $" . $modelNameSingularCamelCase . "->" . GeneratorUtils::singularSnakeCase($constrainModel) . "->" . GeneratorUtils::getColumnAfterId($constrainModel) . " : '' }}
    {{ __('$fieldUcWords') }}{{ isset($" . $modelNameSingularCamelCase . "->" . $fieldSnakeCase . ") ? $" . $modelNameSingularCamelCase . "->" . $fieldSnakeCase . "->format('$dateFormat') : '' }}
    {{ __('$fieldUcWords') }}{{ isset($" . $modelNameSingularCamelCase . "->" . $fieldSnakeCase . ") ? $" . $modelNameSingularCamelCase . "->" . $fieldSnakeCase . "->format('$dateTimeFormat') : '' }}
    {{ __('$fieldUcWords') }}{{ isset($" . $modelNameSingularCamelCase . "->" . $fieldSnakeCase . ") ? $" . $modelNameSingularCamelCase . "->" . $fieldSnakeCase . "->format('$timeFormat') : '' }}
    {{ __('$fieldUcWords') }}{{ $" . $modelNameSingularCamelCase . "->" . $fieldSnakeCase . " }}
    {{ __('$fieldUcWords') }}{{ $" . $modelNameSingularCamelCase . "->$fieldSnakeCase == 1 ? 'True' : 'False' }}
    {{ __('$fieldUcWords') }}{{ isset($" . $modelNameSingularCamelCase . "->$fieldSnakeCase) ? $" . $modelNameSingularCamelCase . "->" . $fieldSnakeCase . "?->format(\"$dateTimeFormat\") : '' }}
    {{ __('$fieldUcWords') }}{{ isset($" . $modelNameSingularCamelCase . "->$fieldSnakeCase) ? $" . $modelNameSingularCamelCase . "->" . $fieldSnakeCase . "?->format(\"$weekFormat\") : '' }}
    {{ __('$fieldUcWords') }}{{ $" . $modelNameSingularCamelCase . "->$fieldSnakeCase }}
    {{ __('$fieldUcWords') }} + @if (" . $default['form_code'] . ") + \"$fieldUcWords\" + @else + \"$fieldUcWords\" + @endif +
    {{ __('" . GeneratorUtils::cleanSingularUcWords($constrainModel) . "') }}{{ $" . $modelNameSingularCamelCase . "->" . GeneratorUtils::singularSnakeCase($constrainModel) . " ? $" . $modelNameSingularCamelCase . "->" . GeneratorUtils::singularSnakeCase($constrainModel) . "->" . GeneratorUtils::getColumnAfterId($constrainModel) . " : '' }}
    {{ __('$fieldUcWords') }}{{ isset($" . $modelNameSingularCamelCase . "->$fieldSnakeCase) ? $" . $modelNameSingularCamelCase . "->" . $fieldSnakeCase . "?->format(\"$dateFormat\") : '' }}
    {{ __('$fieldUcWords') }}{{ isset($" . $modelNameSingularCamelCase . "->$fieldSnakeCase) ? $" . $modelNameSingularCamelCase . "->" . $fieldSnakeCase . "?->format(\"$timeFormat\") : '' }}
    - @if ($user->avatar == null) - Avatar + @if (!$user->avatar) + Avatar @else - avatar") }}" alt="Avatar"> + Avatar @endif