File manager - Edit - /var/www/html/portal/app/Http/Services/Admin/ThemeService.php
Back
<?php namespace App\Http\Services\Admin; use App\Http\Controllers\Controller; use App\Http\Resources\Admin\ThemeResource; use App\Models\Admin\Theme; use Illuminate\Contracts\Pagination\LengthAwarePaginator; use Illuminate\Database\Eloquent\Collection; use Illuminate\Database\Eloquent\ModelNotFoundException; use Illuminate\Http\RedirectResponse; use Illuminate\Support\Arr; use Illuminate\Support\Facades\DB; use Illuminate\Support\Str; class ThemeService extends Controller { /** * Retorna todos os temas paginados. */ public function paginateThemes(int $perPage = 15): LengthAwarePaginator { return Theme::orderBy('is_default', 'desc') ->orderBy('nome') ->paginate($perPage); } /** * Lista simples de todos os temas. */ public function all(): Collection { return Theme::orderBy('is_default', 'desc') ->orderBy('nome') ->get(); } /** * Cria um novo tema. * * @param array<string, mixed> $data * @return RedirectResponse */ public function create(array $data): RedirectResponse { try { DB::beginTransaction(); $colors = ThemeResource::normalizeColors(Arr::get($data, 'colors', [])); $theme = new Theme(); $theme->name = Arr::get($data, 'name'); $theme->slug = Str::slug(Arr::get($data, 'name', ''), '-'); $theme->is_default = false; $theme->is_active_public = false; $theme->is_active_admin = false; $theme->colors = $colors; $theme->default_colors = $colors; $theme->logo = Arr::get($data, 'logo'); $theme->accessibility_logo = Arr::get($data, 'accessibility_logo'); $theme->save(); DB::commit(); return redirect() ->route('admin.temas.index') ->with('success', __('Tema criado com sucesso.')); } catch (\Exception $e) { DB::rollBack(); return redirect() ->back() ->withInput() ->with('error', __('Erro ao tentar criar este tema: ') . $e->getMessage()); } } /** * Atualiza um tema existente. * * @param Theme $theme * @param array<string, mixed> $data * @return RedirectResponse */ public function update(Theme $theme, array $data): RedirectResponse { try { DB::beginTransaction(); if (!$theme->is_default) { $theme->name = Arr::get($data, 'name', $theme->name); $theme->slug = Str::slug($theme->name, '-'); } // Processa as cores enviadas no formulário $colors = ThemeResource::normalizeColors(Arr::get($data, 'colors', [])); $theme->colors = $colors; // Atualiza a logo se fornecida if (Arr::has($data, 'logo')) { $theme->logo = Arr::get($data, 'logo'); } // Atualiza a logo de acessibilidade se fornecida if (Arr::has($data, 'accessibility_logo')) { $theme->accessibility_logo = Arr::get($data, 'accessibility_logo'); } // Obtém o estado desejado dos checkboxes $wantsPublic = (bool) Arr::get($data, 'apply_public', false); $wantsAdmin = (bool) Arr::get($data, 'apply_admin', false); // Guarda o estado anterior $wasPublic = $theme->is_active_public; $wasAdmin = $theme->is_active_admin; // Só ativa se o checkbox está marcado E o tema NÃO estava ativo antes $shouldActivatePublic = $wantsPublic && !$wasPublic; $shouldActivateAdmin = $wantsAdmin && !$wasAdmin; if ($shouldActivatePublic || $shouldActivateAdmin) { $this->activateInternal($theme, $shouldActivatePublic, $shouldActivateAdmin, false); } // Só desativa se o checkbox NÃO está marcado E o tema estava ativo antes $shouldDeactivatePublic = !$wantsPublic && $wasPublic; $shouldDeactivateAdmin = !$wantsAdmin && $wasAdmin; if ($shouldDeactivatePublic || $shouldDeactivateAdmin) { // Desativa o tema atual if ($shouldDeactivatePublic) { $theme->is_active_public = false; } if ($shouldDeactivateAdmin) { $theme->is_active_admin = false; } // Ativa automaticamente o tema padrão para os escopos desativados $this->activateDefaultTheme($shouldDeactivatePublic, $shouldDeactivateAdmin); } $theme->save(); DB::commit(); return redirect() ->route('admin.temas.index') ->with('success', __('Tema atualizado com sucesso.')); } catch (\Exception $e) { DB::rollBack(); return redirect() ->route('admin.temas.edit', $theme->id) ->withInput() ->with('error', $e->getMessage()); } } /** * Ativa ou desativa um tema para os escopos selecionados. * Se desativar, ativa automaticamente o tema padrão. * Chamado do controller - retorna RedirectResponse. * * @param Theme $theme * @param bool $forPublic * @param bool $forAdmin * @return RedirectResponse */ public function activate(Theme $theme, bool $forPublic = true, bool $forAdmin = true): RedirectResponse { try { $this->activateInternal($theme, $forPublic, $forAdmin, true); $message = ($forPublic || $forAdmin) ? __('Tema ativado com sucesso.') : __('Tema desativado com sucesso. O tema padrão foi ativado automaticamente.'); return redirect() ->route('admin.temas.index') ->with('success', $message); } catch (\Exception $e) { return redirect() ->route('admin.temas.index') ->with('error', __('Erro ao tentar ativar/desativar este tema: ') . $e->getMessage()); } } /** * Método interno para ativar/desativar tema (usado internamente). * * @param Theme $theme * @param bool $forPublic * @param bool $forAdmin * @param bool $save * @return Theme * @throws \Exception */ protected function activateInternal(Theme $theme, bool $forPublic = true, bool $forAdmin = true, bool $save = true): Theme { try { DB::beginTransaction(); // Guarda o estado anterior $wasPublic = $theme->is_active_public; $wasAdmin = $theme->is_active_admin; // Ativação if ($forPublic) { // Desativa todos os OUTROS temas, excluindo o tema atual Theme::where('is_active_public', true) ->where('id', '!=', $theme->id) ->update(['is_active_public' => false]); $theme->is_active_public = true; } if ($forAdmin) { // Desativa todos os OUTROS temas, excluindo o tema atual Theme::where('is_active_admin', true) ->where('id', '!=', $theme->id) ->update(['is_active_admin' => false]); $theme->is_active_admin = true; } // Desativação: se recebeu false e o tema estava ativo, desativa e ativa o padrão $shouldDeactivatePublic = !$forPublic && $wasPublic; $shouldDeactivateAdmin = !$forAdmin && $wasAdmin; if ($shouldDeactivatePublic || $shouldDeactivateAdmin) { // Desativa o tema atual if ($shouldDeactivatePublic) { $theme->is_active_public = false; } if ($shouldDeactivateAdmin) { $theme->is_active_admin = false; } // Ativa automaticamente o tema padrão para os escopos desativados $this->activateDefaultTheme($shouldDeactivatePublic, $shouldDeactivateAdmin); } if ($save) { $theme->save(); } DB::commit(); return $theme; } catch (\Exception $e) { DB::rollBack(); throw new \Exception(__('Erro ao tentar ativar/desativar este tema: ') . $e->getMessage()); } } /** * Remove um tema, garantindo que ele não seja padrão nem esteja ativo. * * @param Theme $theme * @return RedirectResponse */ public function delete(Theme $theme): RedirectResponse { try { DB::beginTransaction(); if ($theme->is_default) { throw new \RuntimeException(__('Não é possível excluir o tema padrão do sistema.')); } if ($theme->is_active_public || $theme->is_active_admin) { throw new \RuntimeException(__('Não é possível excluir um tema que está ativo.')); } // Remove logos se existirem ThemeResource::deleteLogo($theme); ThemeResource::deleteAccessibilityLogo($theme); $theme->delete(); DB::commit(); return redirect() ->route('admin.temas.index') ->with('success', __('Tema excluído com sucesso.')); } catch (\Exception $e) { DB::rollBack(); return redirect() ->route('admin.temas.index') ->with('error', $e->getMessage()); } } /** * Restaura as cores originais de um tema (snapshot salvo em default_colors ou padrões do sistema). * * @param Theme $theme * @return Theme * @throws \Exception */ public function resetThemeToOriginal(Theme $theme): RedirectResponse { try { DB::beginTransaction(); // Se o tema tem cores padrão salvas, usa elas if (!empty($theme->default_colors)) { $theme->colors = $theme->default_colors; } else { // Caso contrário, usa os padrões do sistema $theme->colors = ThemeResource::getSystemDefaultColors(); // Salva como default_colors para futuros resets $theme->default_colors = $theme->colors; } $theme->save(); DB::commit(); return redirect() ->route('admin.temas.edit', $theme) ->with('success', __('Tema restaurado para os valores originais.')); } catch (\Exception $e) { DB::rollBack(); return redirect() ->route('admin.temas.edit', $theme) ->with('error', __('Erro ao tentar restaurar este tema: ') . $e->getMessage()); } } /** * Ativa automaticamente o tema padrão para os escopos especificados. * Usado quando um tema é desativado para garantir que sempre haja um tema ativo. * * @param bool $forPublic * @param bool $forAdmin * @return Theme * @throws \Exception */ protected function activateDefaultTheme(bool $forPublic = false, bool $forAdmin = false): Theme { /** @var Theme|null $default */ $default = Theme::where('is_default', true)->first(); if (!$default) { throw new ModelNotFoundException(__('Tema padrão não encontrado.')); } // Ativa o tema padrão apenas para os escopos que foram desativados if ($forPublic) { $default->is_active_public = true; // Desativa outros temas para o escopo público Theme::where('is_active_public', true) ->where('id', '!=', $default->id) ->update(['is_active_public' => false]); } if ($forAdmin) { $default->is_active_admin = true; // Desativa outros temas para o escopo admin Theme::where('is_active_admin', true) ->where('id', '!=', $default->id) ->update(['is_active_admin' => false]); } $default->save(); return $default; } /** * Reativa o tema padrão do sistema para os escopos selecionados. * * @param bool $forPublic * @param bool $forAdmin * @return RedirectResponse */ public function resetToSystemDefault(bool $forPublic = true, bool $forAdmin = true): RedirectResponse { try { DB::beginTransaction(); /** @var Theme|null $default */ $default = Theme::where('is_default', true)->first(); if (!$default) { throw new ModelNotFoundException(__('Tema padrão não encontrado.')); } if (!empty($default->default_colors)) { $default->colors = $default->default_colors; } $this->activateInternal($default, $forPublic, $forAdmin, false); $default->save(); DB::commit(); return redirect() ->route('admin.temas.index') ->with('success', __('Tema padrão reativado com sucesso.')); } catch (ModelNotFoundException $e) { DB::rollBack(); return redirect() ->route('admin.temas.index') ->with('error', $e->getMessage()); } catch (\Exception $e) { DB::rollBack(); return redirect() ->route('admin.temas.index') ->with('error', __('Erro ao tentar reativar o tema padrão: ') . $e->getMessage()); } } }
| ver. 1.4 |
Github
|
.
| PHP 8.3.28 | Generation time: 0.03 |
proxy
|
phpinfo
|
Settings