File manager - Edit - /var/www/html/portalHomolog/app/Console/Commands/MakeFormEmailCommand.php
Back
<?php namespace App\Console\Commands; use Illuminate\Console\Command; use Illuminate\Support\Facades\File; use Illuminate\Support\Str; class MakeFormEmailCommand extends Command { protected $signature = 'form:email {name : Nome do formulário (ex: Contato ou Formularios/InscricaoEvento)} {--route-prefix= : Prefixo da URL (padrão: derivado do nome)} {--layout=layouts.pmar.theme : Layout Blade para o formulário} {--remetente= : E-mail remetente (ex: ouvidoria@angra.rj.gov.br ou "Ouvidoria <ouvidoria@angra.rj.gov.br>")} {--force : Sobrescrever arquivos existentes}'; protected $description = 'Gera formulário público que apenas envia e-mail (Request, Controller, Mailable, views, rotas)'; public function handle(): int { $name = trim($this->argument('name')); if (empty($name) || !preg_match('/^[a-zA-Z][a-zA-Z0-9\/]*$/', $name)) { $this->error('Nome inválido. Use apenas letras, números e "/" (ex: Contato ou Formularios/InscricaoEvento).'); return self::FAILURE; } $parts = explode('/', $name); $parts = array_filter(array_map('trim', $parts)); $className = array_pop($parts); $routeParts = array_merge($parts, [$className]); $routeBase = implode('.', array_map(fn ($p) => Str::kebab($p), $routeParts)); $routePrefix = $this->option('route-prefix') ?? implode('/', array_map(fn ($p) => Str::kebab($p), $routeParts)); // Chaves personalizadas com o nome completo do formulário (evita conflitos e nomes genéricos) $formSlug = implode('_', array_map(fn ($p) => Str::snake($p), $routeParts)); $configKeyDestino = $formSlug . '_destino'; $configKeyRemetente = $formSlug . '_remetente'; $envKeyDestino = 'MAIL_FORM_' . strtoupper($formSlug) . '_DESTINO'; $envKeyRemetente = 'MAIL_FORM_' . strtoupper($formSlug) . '_REMETENTE'; $namespace = 'Paginas\\Formularios'; $requestClass = $className . 'Request'; $controllerClass = $className . 'Controller'; $mailClass = $className . 'Mail'; $namespaceRequest = 'App\\Http\\Requests\\' . $namespace; $namespaceController = 'App\\Http\\Controllers\\' . $namespace; $routeCreate = 'paginas.' . $routeBase . '.create'; $routeStore = 'paginas.' . $routeBase . '.store'; $viewForm = 'paginas.formularios.' . Str::kebab($className); $viewEmail = 'emails.formularios.' . Str::kebab($className); $configDestino = 'mail.formularios.' . $configKeyDestino; $configRemetente = 'mail.formularios.' . $configKeyRemetente; $layout = $this->option('layout'); $remetenteOption = $this->option('remetente'); $requestPath = app_path('Http/Requests/Paginas/Formularios/' . $requestClass . '.php'); $controllerPath = app_path('Http/Controllers/Paginas/Formularios/' . $controllerClass . '.php'); $mailPath = app_path('Mail/' . $mailClass . '.php'); $emailViewPath = resource_path('views/emails/formularios/' . Str::kebab($className) . '.blade.php'); $formViewPath = resource_path('views/paginas/formularios/' . Str::kebab($className) . '.blade.php'); $paths = [$requestPath, $controllerPath, $mailPath, $emailViewPath, $formViewPath]; $existing = array_filter($paths, fn ($p) => File::exists($p)); if (!empty($existing) && !$this->option('force')) { $this->warn('Arquivos já existem: ' . implode(', ', $existing)); if (!$this->confirm('Deseja sobrescrever?', false)) { return self::FAILURE; } } $replacements = [ '{{ namespace_request }}' => $namespaceRequest, '{{ namespace_controller }}' => $namespaceController, '{{ class_request }}' => $requestClass, '{{ class_controller }}' => $controllerClass, '{{ class_mail }}' => $mailClass, '{{ route_create }}' => $routeCreate, '{{ route_store }}' => $routeStore, '{{ view_form }}' => $viewForm, '{{ view_email }}' => $viewEmail, '{{ config_destino }}' => $configDestino, '{{ config_remetente }}' => $configRemetente, '{{ layout }}' => $layout, ]; foreach ([ 'Http/Requests/Paginas/Formularios', 'Http/Controllers/Paginas/Formularios', 'Mail', ] as $dir) { $full = app_path($dir); if (!File::exists($full)) { File::makeDirectory($full, 0755, true); } } foreach (['emails/formularios', 'paginas/formularios'] as $dir) { $full = resource_path('views/' . $dir); if (!File::exists($full)) { File::makeDirectory($full, 0755, true); } } $stubDir = base_path('stubs/form-email'); $stubs = [ 'request.stub' => $requestPath, 'controller.stub' => $controllerPath, 'mailable.stub' => $mailPath, 'email-view.stub' => $emailViewPath, 'form-view.stub' => $formViewPath, ]; foreach ($stubs as $stub => $path) { $content = File::get($stubDir . '/' . $stub); $content = str_replace(array_keys($replacements), array_values($replacements), $content); File::put($path, $content); } $this->addRoutes($routePrefix, $namespaceController, $controllerClass, $routeCreate, $routeStore); $defaultEmail = str_replace('_', '-', $formSlug) . '@angra.rj.gov.br'; $this->addMailConfig($configKeyDestino, $configKeyRemetente, $envKeyDestino, $envKeyRemetente, $defaultEmail, $remetenteOption); $this->info('Formulário criado com sucesso.'); $this->table( ['Arquivo', 'Caminho'], [ ['Request', $requestPath], ['Controller', $controllerPath], ['Mailable', $mailPath], ['View e-mail', $emailViewPath], ['View formulário', $formViewPath], ] ); $this->newLine(); $this->comment('Próximos passos:'); $this->line("1. Adicione no .env: {$envKeyDestino}={$defaultEmail}"); if ($remetenteOption) { $this->line(" {$envKeyRemetente}={$remetenteOption}"); } else { $this->line(" (opcional) {$envKeyRemetente}=remetente@angra.rj.gov.br — se não informado, usa mail.from"); } $this->line("2. Acesse: /" . ltrim($routePrefix, '/')); $this->line("3. Rotas: {$routeCreate} (GET), {$routeStore} (POST)"); return self::SUCCESS; } private function addRoutes(string $routePrefix, string $namespaceController, string $controllerClass, string $routeCreate, string $routeStore): void { $routePrefix = '/' . ltrim($routePrefix, '/'); $controller = $namespaceController . '\\' . $controllerClass; $snippet = "\n// Formulário e-mail (form:email)\nRoute::get('{$routePrefix}', '{$controller}@create')->name('{$routeCreate}');\nRoute::post('{$routePrefix}', '{$controller}@store')->name('{$routeStore}');\n"; $webPath = base_path('routes/web.php'); $content = File::get($webPath); if (str_contains($content, $routeCreate)) { $this->warn('Rotas já existem em web.php.'); return; } $insertBefore = "Route::get('/{source}'"; if (str_contains($content, $insertBefore)) { $content = str_replace( $insertBefore, $snippet . "\n" . $insertBefore, $content ); } else { $content .= $snippet; } File::put($webPath, $content); } private function addMailConfig( string $configKeyDestino, string $configKeyRemetente, string $envKeyDestino, string $envKeyRemetente, string $defaultEmail, ?string $remetenteOption ): void { $mailPath = config_path('mail.php'); $content = File::get($mailPath); $defaultRemetente = $remetenteOption ? "'{$remetenteOption}'" : 'null'; $destinoLine = "'{$configKeyDestino}' => env('{$envKeyDestino}', '{$defaultEmail}'),"; $remetenteLine = "\n '{$configKeyRemetente}' => env('{$envKeyRemetente}', {$defaultRemetente}),"; if (str_contains($content, $configKeyDestino)) { if (!str_contains($content, $configKeyRemetente)) { $content = preg_replace( "/(\s*'{$configKeyDestino}'\s*=>\s*env\([^)]+\),)/", '$1' . $remetenteLine, $content, 1 ); } return; } $insert = "\n {$destinoLine}{$remetenteLine}"; if (str_contains($content, "'formularios'")) { $content = str_replace( "\n ],\n\n 'markdown'", $insert . "\n ],\n\n 'markdown'", $content ); } else { $formBlock = "\n\n 'formularios' => [{$insert}\n ],"; $content = str_replace( " 'markdown' => [", $formBlock . "\n\n 'markdown' => [", $content ); } File::put($mailPath, $content); } }
| ver. 1.4 |
Github
|
.
| PHP 8.3.28 | Generation time: 0.11 |
proxy
|
phpinfo
|
Settings