|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace Gamer\Policies; |
|
4
|
|
|
|
|
5
|
|
|
use App\Models\User; |
|
6
|
|
|
use App\Post; |
|
7
|
|
|
use Illuminate\Auth\Access\HandlesAuthorization; |
|
8
|
|
|
|
|
9
|
|
|
class PostPolicy |
|
10
|
|
|
{ |
|
11
|
|
|
use HandlesAuthorization; |
|
12
|
|
|
|
|
13
|
|
|
/** |
|
14
|
|
|
* Determine whether the user can view the post. |
|
15
|
|
|
* |
|
16
|
|
|
* @param \App\Models\User $user |
|
17
|
|
|
* @param \App\Post $post |
|
18
|
|
|
* @return mixed |
|
19
|
|
|
*/ |
|
20
|
|
|
public function view(User $user, Post $post) |
|
21
|
|
|
{ |
|
22
|
|
|
if ($post->published) { |
|
23
|
|
|
return true; |
|
24
|
|
|
} |
|
25
|
|
|
|
|
26
|
|
|
// visitors cannot view unpublished items |
|
27
|
|
|
if ($user === null) { |
|
28
|
|
|
return false; |
|
29
|
|
|
} |
|
30
|
|
|
|
|
31
|
|
|
// admin overrides published status |
|
32
|
|
|
if ($user->can('view unpublished posts')) { |
|
33
|
|
|
return true; |
|
34
|
|
|
} |
|
35
|
|
|
|
|
36
|
|
|
// authors can view their own unpublished posts |
|
37
|
|
|
return $user->id === $post->user_id; |
|
38
|
|
|
} |
|
39
|
|
|
|
|
40
|
|
|
/** |
|
41
|
|
|
* Determine whether the user can create posts. |
|
42
|
|
|
* |
|
43
|
|
|
* @param \App\Models\User $user |
|
44
|
|
|
* @return mixed |
|
45
|
|
|
*/ |
|
46
|
|
|
public function create(User $user) |
|
47
|
|
|
{ |
|
48
|
|
|
if ($user->can('create posts')) { |
|
49
|
|
|
return true; |
|
50
|
|
|
} |
|
51
|
|
|
} |
|
52
|
|
|
|
|
53
|
|
|
/** |
|
54
|
|
|
* Determine whether the user can update the post. |
|
55
|
|
|
* |
|
56
|
|
|
* @param \App\Models\User $user |
|
57
|
|
|
* @param \App\Post $post |
|
58
|
|
|
* @return mixed |
|
59
|
|
|
*/ |
|
60
|
|
View Code Duplication |
public function update(User $user, Post $post) |
|
|
|
|
|
|
61
|
|
|
{ |
|
62
|
|
|
if ($user->can('edit own posts')) { |
|
63
|
|
|
return $user->id === $post->user_id; |
|
64
|
|
|
} |
|
65
|
|
|
|
|
66
|
|
|
if ($user->can('edit all posts')) { |
|
67
|
|
|
return true; |
|
68
|
|
|
} |
|
69
|
|
|
} |
|
70
|
|
|
|
|
71
|
|
|
/** |
|
72
|
|
|
* Determine whether the user can delete the post. |
|
73
|
|
|
* |
|
74
|
|
|
* @param \App\Models\User $user |
|
75
|
|
|
* @param \App\Post $post |
|
76
|
|
|
* @return mixed |
|
77
|
|
|
*/ |
|
78
|
|
View Code Duplication |
public function delete(User $user, Post $post) |
|
|
|
|
|
|
79
|
|
|
{ |
|
80
|
|
|
if ($user->can('delete own posts')) { |
|
81
|
|
|
return $user->id === $post->user_id; |
|
82
|
|
|
} |
|
83
|
|
|
|
|
84
|
|
|
if ($user->can('delete any post')) { |
|
85
|
|
|
return true; |
|
86
|
|
|
} |
|
87
|
|
|
} |
|
88
|
|
|
} |
|
89
|
|
|
|
Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.
You can also find more detailed suggestions in the “Code” section of your repository.