WorkbookService.php
1 <?php 2 3 declare(strict_types=1); 4 5 namespace App\Http\Services; 6 7 use App\Http\Resources\WorkBookResource; 8 use App\Models\Workbook; 9 use Exception; 10 use Illuminate\Support\Facades\DB; 11 12 class WorkbookService 13 { 14 /** 15 * Display a listing of the resource. 16 * 17 * @return \Illuminate\Http\Response 18 */ 19 public static function index(int $normId) 20 { 21 return WorkBookResource::collection(Workbook::where('norm_id', $normId)->orderBy('name', 'asc')->paginate(10)); 22 } 23 24 /** 25 * Create a resource 26 * 27 * @return \Illuminate\Http\Response 28 */ 29 public static function create(array $data, array $scopes) 30 { 31 try { 32 DB::beginTransaction(); 33 34 $workbook = WorkBook::withTrashed()->where([ 35 'name' => $data['name'], 36 'norm_id' => $data['norm_id'] 37 ])->first(); 38 39 if ($workbook && $workbook->trashed()) { 40 $workbook->restore(); 41 } else { 42 $workbook = Workbook::create($data); 43 } 44 45 $workbook->normScope()->sync($scopes); 46 47 DB::commit(); 48 49 return true; 50 } catch (Exception $e) { 51 DB::rollBack(); 52 log_exception($e); 53 throw new Exception(__('norms.norm.workbook.notifications.create.error.message')); 54 } 55 } 56 57 /** 58 * Destroy a resource 59 * 60 * @return \Illuminate\Http\Response 61 */ 62 public static function remove(int $entityId) 63 { 64 DB::beginTransaction(); 65 66 if (Workbook::destroy($entityId)) { 67 DB::commit(); 68 69 return true; 70 } else { 71 DB::rollBack(); 72 throw new Exception(__('norms.norm.workbook.notifications.remove.error.message')); 73 } 74 } 75 76 /** 77 * Update a resource 78 * 79 * @return \Illuminate\Http\Response 80 */ 81 public static function update(array $data, int $entityId, array $scopes) 82 { 83 try { 84 DB::beginTransaction(); 85 $workbook = Workbook::findOrFail($entityId); 86 $workbook->name = $data['name']; 87 $workbook->save(); 88 $workbook->normScope()->sync($scopes); 89 90 DB::commit(); 91 92 return true; 93 } catch (Exception $e) { 94 DB::rollBack(); 95 throw new Exception(__('norms.norm.workbook.notifications.update.error.message')); 96 } 97 } 98 99 /** 100 * Display a listing of the resource. 101 * 102 * @return \Illuminate\Http\Response 103 */ 104 public static function find(int $entityId) 105 { 106 return Workbook::findOrFail($entityId); 107 } 108 }