]> BookStack Code Mirror - bookstack/blob - app/Activity/Controllers/WatchController.php
Notifications: Added testing to cover controls
[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\UserEntityWatchOptions;
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         // TODO - Require notification permission
19         $requestData = $this->validate($request, [
20             'level' => ['required', 'string'],
21         ]);
22
23         $watchable = $this->getValidatedModelFromRequest($request);
24         $watchOptions = new UserEntityWatchOptions(user(), $watchable);
25         $watchOptions->updateWatchLevel($requestData['level']);
26
27         $this->showSuccessNotification(trans('activities.watch_update_level_notification'));
28
29         return redirect()->back();
30     }
31
32     /**
33      * @throws ValidationException
34      * @throws Exception
35      */
36     protected function getValidatedModelFromRequest(Request $request): Entity
37     {
38         $modelInfo = $this->validate($request, [
39             'type' => ['required', 'string'],
40             'id'   => ['required', 'integer'],
41         ]);
42
43         if (!class_exists($modelInfo['type'])) {
44             throw new Exception('Model not found');
45         }
46
47         /** @var Model $model */
48         $model = new $modelInfo['type']();
49         if (!$model instanceof Entity) {
50             throw new Exception('Model not an entity');
51         }
52
53         $modelInstance = $model->newQuery()
54             ->where('id', '=', $modelInfo['id'])
55             ->first(['id', 'name', 'owned_by']);
56
57         $inaccessibleEntity = ($modelInstance instanceof Entity && !userCan('view', $modelInstance));
58         if (is_null($modelInstance) || $inaccessibleEntity) {
59             throw new Exception('Model instance not found');
60         }
61
62         return $modelInstance;
63     }
64 }