]> BookStack Code Mirror - bookstack/blob - app/Http/Controllers/Api/RecycleBinApiController.php
Complete list endpoint and add some tests
[bookstack] / app / Http / Controllers / Api / RecycleBinApiController.php
1 <?php
2
3 namespace BookStack\Http\Controllers\Api;
4
5 use BookStack\Entities\Models\Book;
6 use BookStack\Entities\Models\Chapter;
7 use BookStack\Entities\Models\Deletion;
8 use BookStack\Entities\Repos\DeletionRepo;
9 use Closure;
10
11 class RecycleBinApiController extends ApiController
12 {
13     public function __construct()
14     {
15         $this->middleware(function ($request, $next) {
16             $this->checkPermission('settings-manage');
17             $this->checkPermission('restrictions-manage-all');
18
19             return $next($request);
20         });
21     }
22
23     public function list()
24     {
25         return $this->apiListingResponse(Deletion::query(), [
26             'id',
27             'deleted_by',
28             'created_at',
29             'updated_at',
30             'deletable_type',
31             'deletable_id',
32         ], [Closure::fromCallable([$this, 'listFormatter'])]);
33     }
34
35     public function restore(DeletionRepo $deletionRepo, string $id)
36     {
37         $restoreCount = $deletionRepo->restore((int) $id);
38
39         return response()->json(['restore_count' => $restoreCount]);
40     }
41
42     public function destroy(DeletionRepo $deletionRepo, string $id)
43     {
44         $deleteCount = $deletionRepo->destroy((int) $id);
45
46         return response()->json(['delete_count' => $deleteCount]);
47     }
48
49     protected function listFormatter(Deletion $deletion)
50     {
51         $deletable = $deletion->deletable;
52         $isBook = $deletable instanceof Book;
53         $parent = null;
54         $children = null;
55
56         if ($isBook) {
57             $chapterCount = $deletable->chapters()->withTrashed()->count();       
58             $children['Bookstack\Chapter'] = $chapterCount;
59         }
60
61         if ($isBook || $deletion->deletable instanceof Chapter) {
62             $pageCount = $deletable->pages()->withTrashed()->count();     
63             $children['Bookstack\Page'] = $pageCount;
64         }
65
66         $parentEntity = $deletable->getParent();
67         $parent = [];
68
69         if ($parentEntity) {
70             $parent['type'] = $parentEntity->getMorphClass();
71             $parent['id'] = $parentEntity->getKey();
72         }
73
74         $deletion->setAttribute('parent', $parent);
75         $deletion->setAttribute('children', $children);
76     }
77 }