|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
declare(strict_types=1); |
|
4
|
|
|
|
|
5
|
|
|
namespace BitBag\SyliusWishlistPlugin\Voter; |
|
6
|
|
|
|
|
7
|
|
|
use BitBag\SyliusWishlistPlugin\Entity\WishlistInterface; |
|
8
|
|
|
use Sylius\Component\Core\Model\ShopUserInterface; |
|
9
|
|
|
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface; |
|
10
|
|
|
use Symfony\Component\Security\Core\Authorization\Voter\Voter; |
|
11
|
|
|
use Symfony\Component\Security\Core\Security; |
|
12
|
|
|
|
|
13
|
|
|
final class WishlistVoter extends Voter |
|
14
|
|
|
{ |
|
15
|
|
|
public const UPDATE = 'update'; |
|
16
|
|
|
|
|
17
|
|
|
public const DELETE = 'delete'; |
|
18
|
|
|
|
|
19
|
|
|
private Security $security; |
|
20
|
|
|
|
|
21
|
|
|
public function __construct(Security $security) |
|
22
|
|
|
{ |
|
23
|
|
|
$this->security = $security; |
|
24
|
|
|
} |
|
25
|
|
|
|
|
26
|
|
|
protected function supports($attribute, $subject): bool |
|
27
|
|
|
{ |
|
28
|
|
|
$attributes = [ |
|
29
|
|
|
self::UPDATE, |
|
30
|
|
|
self::DELETE, |
|
31
|
|
|
]; |
|
32
|
|
|
|
|
33
|
|
|
if (!in_array($attribute, $attributes, true) || |
|
34
|
|
|
!$subject instanceof WishlistInterface) { |
|
35
|
|
|
return false; |
|
36
|
|
|
} |
|
37
|
|
|
|
|
38
|
|
|
return true; |
|
39
|
|
|
} |
|
40
|
|
|
|
|
41
|
|
|
protected function voteOnAttribute($attribute, $subject, TokenInterface $token): bool |
|
42
|
|
|
{ |
|
43
|
|
|
$user = $token->getUser(); |
|
44
|
|
|
|
|
45
|
|
|
if (!$user instanceof ShopUserInterface) { |
|
46
|
|
|
$user = null; |
|
47
|
|
|
} |
|
48
|
|
|
|
|
49
|
|
|
/** @var WishlistInterface $wishlist */ |
|
50
|
|
|
$wishlist = $subject; |
|
51
|
|
|
|
|
52
|
|
|
switch ($attribute) { |
|
53
|
|
|
case self::UPDATE: |
|
54
|
|
|
return $this->canUpdate($wishlist, $user); |
|
55
|
|
|
case self::DELETE: |
|
56
|
|
|
return $this->canDelete($wishlist, $user); |
|
57
|
|
|
} |
|
58
|
|
|
|
|
59
|
|
|
throw new \LogicException(sprintf('Unsupported attribute: "%s"', $attribute)); |
|
60
|
|
|
} |
|
61
|
|
|
|
|
62
|
|
|
public function canUpdate(WishlistInterface $wishlist, ?ShopUserInterface $user): bool |
|
63
|
|
|
{ |
|
64
|
|
|
if (!$this->security->isGranted('ROLE_USER') && null === $wishlist->getShopUser()) { |
|
65
|
|
|
return true; |
|
66
|
|
|
} |
|
67
|
|
|
|
|
68
|
|
|
if ($this->security->isGranted('ROLE_USER') && $wishlist->getShopUser() === $user) { |
|
69
|
|
|
return true; |
|
70
|
|
|
} |
|
71
|
|
|
|
|
72
|
|
|
return false; |
|
73
|
|
|
} |
|
74
|
|
|
|
|
75
|
|
|
public function canDelete(WishlistInterface $wishlist, ?ShopUserInterface $user): bool |
|
76
|
|
|
{ |
|
77
|
|
|
return $this->canUpdate($wishlist, $user); |
|
78
|
|
|
} |
|
79
|
|
|
} |
|
80
|
|
|
|