|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace MacropaySolutions\LaravelCrudWizardGenerator\Services; |
| 4 | + |
| 5 | +use Illuminate\Console\Concerns\InteractsWithIO; |
| 6 | +use Illuminate\Contracts\Foundation\Application; |
| 7 | +use Illuminate\Support\Facades\File; |
| 8 | +use Illuminate\Support\Str; |
| 9 | +use Symfony\Component\Console\Output\ConsoleOutput; |
| 10 | + |
| 11 | +class MakeMiddlewareService |
| 12 | +{ |
| 13 | + use InteractsWithIO; |
| 14 | + |
| 15 | + public function __construct( |
| 16 | + protected PathsAndNamespacesService $pathsAndNamespacesService, |
| 17 | + protected Application $application, |
| 18 | + ConsoleOutput $consoleOutput, |
| 19 | + ) { |
| 20 | + $this->output = $consoleOutput; |
| 21 | + } |
| 22 | + |
| 23 | + public function makeCompleteMiddlewareFile(string $resourceName, string $laravelNamespace): void |
| 24 | + { |
| 25 | + $this->createMiddlewareFile( |
| 26 | + $this->replaceContentMiddlewareStub($resourceName, $laravelNamespace), |
| 27 | + $resourceName |
| 28 | + ); |
| 29 | + } |
| 30 | + |
| 31 | + protected function replaceContentMiddlewareStub(string $resourceName, string $laravelNamespace): string |
| 32 | + { |
| 33 | + return \str_replace([ |
| 34 | + 'DummyNamespace', |
| 35 | + 'DummyModel', |
| 36 | + 'DummyClass', |
| 37 | + ], [ |
| 38 | + \trim($laravelNamespace, '\\'), |
| 39 | + \ucfirst(Str::camel(Str::singular($resourceName))), |
| 40 | + \ucfirst(Str::camel(Str::plural($resourceName))) . 'Middleware', |
| 41 | + ], File::get($this->pathsAndNamespacesService->getMiddlewareStubPath())); |
| 42 | + } |
| 43 | + |
| 44 | + protected function createMiddlewareFile(string $middlewareStub, string $resourceName): void |
| 45 | + { |
| 46 | + if (!File::exists($path = $this->pathsAndNamespacesService->getRealpathBaseMiddleware())) { |
| 47 | + File::makeDirectory($path); |
| 48 | + } |
| 49 | + |
| 50 | + if (!File::exists($path = $this->pathsAndNamespacesService->getRealpathBaseCustomMiddleware($resourceName))) { |
| 51 | + File::put($path, $middlewareStub); |
| 52 | + $this->line('<info>Created Middleware:</info> ' . $path); |
| 53 | + $this->info('TODO:'); |
| 54 | + $this->info('- Fill the decorator,'); |
| 55 | + $this->info('- Register middleware decorator as route middleware,'); |
| 56 | + $this->info('- Use the middleware alias as middleware in your crud route definition for each method.'); |
| 57 | + |
| 58 | + return; |
| 59 | + } |
| 60 | + |
| 61 | + $this->error('Middleware ' . $path . ' already exists'); |
| 62 | + } |
| 63 | +} |
0 commit comments