Passed
Pull Request — master (#58)
by
unknown
04:47
created

WishlistVoter::canUpdate()   A

Complexity

Conditions 5
Paths 3

Size

Total Lines 11
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
cc 5
eloc 5
c 2
b 0
f 0
nc 3
nop 2
dl 0
loc 11
rs 9.6111
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
            return false;
35
        }
36
37
        if (!$subject instanceof WishlistInterface) {
38
            return false;
39
        }
40
41
        return true;
42
    }
43
44
    protected function voteOnAttribute($attribute, $subject, TokenInterface $token): bool
45
    {
46
        $user = $token->getUser();
47
48
        if (!$user instanceof ShopUserInterface) {
49
            $user = null;
50
        }
51
52
        /** @var WishlistInterface $wishlist */
53
        $wishlist = $subject;
54
55
        switch ($attribute) {
56
            case self::UPDATE:
57
                return $this->canUpdate($wishlist, $user);
58
            case self::DELETE:
59
                return $this->canDelete($wishlist, $user);
60
        }
61
62
        throw new \LogicException(sprintf('Unsupported attribute: "%s"', $attribute));
63
    }
64
65
    public function canUpdate(WishlistInterface $wishlist, ?ShopUserInterface $user): bool
66
    {
67
        if (!$this->security->isGranted('ROLE_USER') && null === $wishlist->getShopUser()) {
68
            return true;
69
        }
70
71
        if ($this->security->isGranted('ROLE_USER') && $wishlist->getShopUser() === $user) {
72
            return true;
73
        }
74
75
        return false;
76
    }
77
78
    public function canDelete(WishlistInterface $wishlist, ?ShopUserInterface $user): bool
79
    {
80
        return $this->canUpdate($wishlist, $user);
81
    }
82
}
83