]> BookStack Code Mirror - bookstack/blob - app/Activity/Controllers/WatchController.php
Notifications: Linked watch functionality to UI
[bookstack] / app / Activity / Controllers / WatchController.php
1 <?php
2
3 namespace BookStack\Activity\Controllers;
4
5 use BookStack\Activity\Models\Watch;
6 use BookStack\Activity\Tools\UserWatchOptions;
7 use BookStack\App\Model;
8 use BookStack\Entities\Models\Entity;
9 use BookStack\Http\Controller;
10 use Exception;
11 use Illuminate\Http\Request;
12 use Illuminate\Validation\ValidationException;
13
14 class WatchController extends Controller
15 {
16     public function update(Request $request)
17     {
18         $requestData = $this->validate($request, [
19             'level' => ['required', 'string'],
20         ]);
21
22         $watchable = $this->getValidatedModelFromRequest($request);
23         $watchOptions = new UserWatchOptions(user());
24         $watchOptions->updateEntityWatchLevel($watchable, $requestData['level']);
25
26         $this->showSuccessNotification(trans('activities.watch_update_level_notification'));
27
28         return redirect()->back();
29     }
30
31     /**
32      * @throws ValidationException
33      * @throws Exception
34      */
35     protected function getValidatedModelFromRequest(Request $request): Entity
36     {
37         $modelInfo = $this->validate($request, [
38             'type' => ['required', 'string'],
39             'id'   => ['required', 'integer'],
40         ]);
41
42         if (!class_exists($modelInfo['type'])) {
43             throw new Exception('Model not found');
44         }
45
46         /** @var Model $model */
47         $model = new $modelInfo['type']();
48         if (!$model instanceof Entity) {
49             throw new Exception('Model not an entity');
50         }
51
52         $modelInstance = $model->newQuery()
53             ->where('id', '=', $modelInfo['id'])
54             ->first(['id', 'name', 'owned_by']);
55
56         $inaccessibleEntity = ($modelInstance instanceof Entity && !userCan('view', $modelInstance));
57         if (is_null($modelInstance) || $inaccessibleEntity) {
58             throw new Exception('Model instance not found');
59         }
60
61         return $modelInstance;
62     }
63 }