PostDelete.php 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. <?php
  2. namespace App\Http\Middleware\Board;
  3. use Closure;
  4. use Illuminate\Http\Request;
  5. use Illuminate\Support\Facades\Gate;
  6. use App\Services\BoardService;
  7. use App\Services\PostService;
  8. use App\Models\DTO\ResponseData;
  9. use Exception;
  10. class PostDelete
  11. {
  12. public function handle(Request $request, Closure $next)
  13. {
  14. try{
  15. $code = $request->route('code');
  16. $postID = $request->route('postID');
  17. // 게시판 코드 확인
  18. if (!$code || !$postID) {
  19. throw new Exception('잘못된 접근입니다.', 404);
  20. }
  21. $boardService = new BoardService();
  22. // 게시판 정보 조회
  23. $board = $boardService->find($code);
  24. // 게시판 존재 유무
  25. if (!$board->exists) {
  26. throw new Exception('존재하지 않는 게시판입니다.');
  27. }
  28. // 게시판 사용 여부
  29. if ($board->is_display == 0) {
  30. throw new Exception('더 이상 사용하지 않는 게시판입니다.');
  31. }
  32. $postService = new PostService();
  33. // 게시글 조회
  34. $post = $postService->find($postID);
  35. if(!$post->exists) {
  36. throw new Exception('존재하지 않는 게시글입니다.');
  37. }
  38. $user = $request->user();
  39. // 비회원 게시글은 비밀번호 확인
  40. if(!$user && !$post->user_id) {
  41. $passwd = $request->input('passwd');
  42. if(!$passwd || $passwd != $post->password) {
  43. throw new Exception('권한이 없습니다.');
  44. }
  45. }
  46. $boardMeta = $boardService->meta($board->id);
  47. // 삭제 권한 확인
  48. $response = Gate::inspect('delete', [$post, $boardMeta]);
  49. if($response->denied()) {
  50. throw new Exception($response->message(), $response->code());
  51. }
  52. // 관리자만 삭제 가능
  53. $response = Gate::inspect('forceDelete', [$post, $boardMeta]);
  54. if($response->denied()) {
  55. throw new Exception($response->message());
  56. }
  57. $request->merge([
  58. 'board' => $board,
  59. 'boardMeta' => $boardMeta,
  60. 'post' => $post
  61. ]);
  62. }catch(Exception $e) {
  63. return ResponseData::fromException($e);
  64. }
  65. return $next($request);
  66. }
  67. }