SettingService.php
1 <?php 2 3 namespace App\Http\Services; 4 5 use App\Models\Setting; 6 use Cache; 7 use Exception; 8 use Illuminate\Support\Facades\DB; 9 use Illuminate\Support\Facades\Storage; 10 use Livewire\TemporaryUploadedFile; 11 use Log; 12 13 class SettingService 14 { 15 /** 16 * Retrieve an instance of the "Setting" model. 17 * 18 * @return \Illuminate\Database\Eloquent\Model|null The instance of the "Setting" model or null if no records were found. 19 */ 20 public static function getAll() 21 { 22 return Setting::all()->first(); 23 } 24 25 public static function getCustomStyles() 26 { 27 $setting = Setting::firstOrFail()->get(['primary_color', 'secondary_color'])->first(); 28 $primaryColor = explode(',', $setting->primary_color); 29 $secondaryColor = explode(',', $setting->secondary_color); 30 31 return [ 32 'primary-color' => [ 33 'light' => $primaryColor[0] ?? '', 34 'default' => $primaryColor[1] ?? '', 35 'dark' => $primaryColor[2] ?? '' 36 ], 37 'secondary-color' => [ 38 'light' => $secondaryColor[0] ?? '', 39 'default' => $secondaryColor[1] ?? '', 40 'dark' => $secondaryColor[2] ?? '' 41 ], 42 ]; 43 } 44 45 /** 46 * Create a resource 47 * 48 * @return \Illuminate\Http\Response 49 */ 50 public static function updateOrCreate(array $data, ?TemporaryUploadedFile $file, ?int $id): bool|Exception 51 { 52 try { 53 DB::beginTransaction(); 54 55 $primaryColor = implode(',', $data['primaryColor']); 56 $secondaryColor = implode(',', $data['secondaryColor']); 57 58 $setting = Setting::firstOrNew(['id' => $id]); 59 self::setLogo($setting, $file); 60 $setting->head = $data['head']; 61 $setting->sub_head = $data['sub_head']; 62 $setting->title_certifier = $data['title_certifier']; 63 $setting->email = $data['email']; 64 $setting->primary_color = (string)$primaryColor; 65 $setting->secondary_color = (string)$secondaryColor; 66 67 $setting->save(); 68 Cache::forever('report_styles', self::getCustomStyles()); 69 70 DB::commit(); 71 72 if (!is_null($file)) 73 $file->storeAs('/', $setting->logo, ['disk' => 'public']); 74 75 return true; 76 } catch (Exception $e) { 77 DB::rollBack(); 78 throw new Exception($e->getMessage()); 79 Log::error($e); 80 } 81 } 82 83 public static function resetColors() 84 { 85 try { 86 DB::beginTransaction(); 87 88 Setting::firstOrFail()->update([ 89 'primary_color' => null, 90 'secondary_color' => null, 91 ]); 92 93 Cache::forever('report_styles', self::getCustomStyles()); 94 95 DB::commit(); 96 97 return true; 98 } catch (Exception $e) { 99 DB::rollBack(); 100 throw new Exception($e->getMessage()); 101 } 102 } 103 104 private static function setLogo(Setting $setting, $file): Setting 105 { 106 if ($file) { 107 if (Storage::disk('public')->exists($setting->logo)) { 108 Storage::disk('public')->delete($setting->logo); 109 } 110 $setting->logo = 'SGOC/' . $file->getClientOriginalName(); 111 } else { 112 $setting->logo = $setting->logo; 113 } 114 115 return $setting; 116 } 117 }