Passed
Branch master (249862)
by Adam
07:51
created

FlagController::getPermissionName()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 4
nc 2
nop 1
dl 0
loc 9
rs 9.6666
c 0
b 0
f 0
1
<?php
2
3
namespace Coyote\Http\Controllers;
4
5
use Carbon\Carbon;
6
use Coyote\Flag\Type;
7
use Coyote\Notifications\FlagCreatedNotification;
8
use Coyote\Repositories\Contracts\FlagRepositoryInterface as FlagRepository;
9
use Coyote\Repositories\Contracts\ForumRepositoryInterface as ForumRepository;
10
use Coyote\Repositories\Contracts\UserRepositoryInterface as UserRepository;
11
use Coyote\Repositories\Criteria\HasPermission;
12
use Illuminate\Contracts\Encryption\Encrypter;
13
use Illuminate\Http\Request;
14
use Coyote\Services\Stream\Objects\Flag as Stream_Flag;
15
use Coyote\Services\Stream\Activities\Create as Stream_Create;
16
use Coyote\Services\Stream\Activities\Delete as Stream_Delete;
17
18
class FlagController extends Controller
19
{
20
    /**
21
     * @var FlagRepository
22
     */
23
    private $flag;
24
25
    /**
26
     * @var ForumRepository
27
     */
28
    private $forum;
29
30
    /**
31
     * @var UserRepository
32
     */
33
    private $user;
34
35
    /**
36
     * @param FlagRepository $flag
37
     * @param ForumRepository $forum
38
     * @param UserRepository $user
39
     */
40
    public function __construct(FlagRepository $flag, ForumRepository $forum, UserRepository $user)
41
    {
42
        parent::__construct();
43
44
        $this->flag = $flag;
45
        $this->forum = $forum;
46
        $this->user = $user;
47
    }
48
49
    /**
50
     * @param Request $request
51
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
52
     */
53
    public function index(Request $request)
54
    {
55
        return view('flag', [
56
            'types'         => Type::all(),
57
            'url'           => $request->query('url'),
58
            'metadata'      => $request->query('metadata')
59
        ]);
60
    }
61
62
    /**
63
     * @param Request $request
64
     */
65
    public function save(Request $request)
66
    {
67
        $rules = [
68
            'url'           => 'required|string',
69
            'metadata'      => 'required',
70
            'type_id'       => 'integer|exists:flag_types,id',
71
            'text'          => 'string',
72
            '_token'        => 'throttle'
73
        ];
74
75
        $validator = $this->getValidationFactory()->make($request->all(), $rules);
76
        $validator->after(function ($validator) use ($request) {
77
            $metadata = $this->decrypt($request->get('metadata'));
78
79
            if (empty($metadata['permission'])) {
80
                $validator->errors()->add('metadata', trans('validation.string', ['attribute' => 'string']));
81
            }
82
        });
83
84
        $this->validateWith($validator);
85
86
        $this->transaction(function () use ($request) {
87
            $data = $request->all() + ['user_id' => $this->userId];
88
            $data['metadata'] = $this->decrypt($data['metadata']);
89
90
            $flag = $this->flag->create($data);
91
92
            $this->user->pushCriteria(new HasPermission($this->getPermissionName($flag)));
93
94
            $users = $this
95
                ->user
96
                ->all()
97
                ->sortByDesc(function ($user) {
98
                    /** @var \Coyote\User $user */
99
                    return $user->id == $this->userId ? -1
100
                        : ($user->is_online ? Carbon::now()->timestamp : $user->visited_at->timestamp);
101
                })
102
                ->splice(0, 5);
103
104
            /** @var \Coyote\User $user */
105
            foreach ($users as $user) {
106
                $user->notify(new FlagCreatedNotification($flag));
107
            }
108
109
            stream(Stream_Create::class, (new Stream_Flag())->map($flag));
110
        });
111
    }
112
113
    /**
114
     * @param $id
115
     * @return \Illuminate\Contracts\Routing\ResponseFactory|\Symfony\Component\HttpFoundation\Response|null
116
     */
117
    public function delete($id)
118
    {
119
        $flag = $this->flag->findOrFail($id);
120
        $object = new Stream_Flag(['id' => $flag->id]);
121
122
        if (!$this->isAuthorized($flag)) {
123
            return response('Unauthorized.', 401);
124
        }
125
126
        $this->transaction(function () use ($flag, $object) {
127
            $flag->moderator_id = $this->userId;
128
            $flag->save();
129
130
            $flag->delete();
131
            stream(Stream_Delete::class, $object);
132
        });
133
    }
134
135
    /**
136
     * @return mixed
137
     */
138
    public function modal()
139
    {
140
        return view('flag.modal');
141
    }
142
143
    /**
144
     * @return Encrypter
145
     */
146
    protected function getCryptFactory()
147
    {
148
        return app(Encrypter::class);
149
    }
150
151
    /**
152
     * @param $metadata
153
     * @return string
154
     */
155
    protected function decrypt($metadata)
156
    {
157
        return $this->getCryptFactory()->decrypt($metadata);
158
    }
159
160
    /**
161
     * @param \Coyote\Flag $flag
162
     * @return bool
163
     */
164
    private function isAuthorized($flag)
165
    {
166
        $gate = $this->getGateFactory();
167
168
        if (isset($flag->metadata->forum_id)) {
169
            $forum = $this->forum->findOrFail($flag->metadata->forum_id);
170
171
            return $gate->allows($flag->metadata->permission, $forum);
172
        } elseif (isset($flag->metadata->permission)) {
173
            return $gate->allows($flag->metadata->permission);
174
        } else {
175
            return false;
176
        }
177
    }
178
179
    /**
180
     * @param \Coyote\Flag $flag
181
     * @return string
182
     */
183
    private function getPermissionName($flag)
184
    {
185
        $permission = $flag->metadata->permission;
186
187
        if (isset($flag->metadata->forum_id)) {
188
            $permission = "forum-$permission";
189
        }
190
191
        return $permission;
192
    }
193
}
194