WishlistVoter::canUpdate()   A
last analyzed

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
/*
4
 * This file was created by developers working at BitBag
5
 * Do you need more information about us and what we do? Visit our https://bitbag.io website!
6
 * We are hiring developers from all over the world. Join us and start your new, exciting adventure and become part of us: https://bitbag.io/career
7
*/
8
9
declare(strict_types=1);
10
11
namespace BitBag\SyliusWishlistPlugin\Voter;
12
13
use BitBag\SyliusWishlistPlugin\Entity\WishlistInterface;
14
use Sylius\Component\Core\Model\ShopUserInterface;
15
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
16
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
17
use Symfony\Component\Security\Core\Security;
18
19
final class WishlistVoter extends Voter
20
{
21
    public const UPDATE = 'update';
22
23
    public const DELETE = 'delete';
24
25
    private Security $security;
26
27
    public function __construct(Security $security)
28
    {
29
        $this->security = $security;
30
    }
31
32
    protected function supports($attribute, $subject): bool
33
    {
34
        $attributes = [
35
            self::UPDATE,
36
            self::DELETE,
37
        ];
38
39
        if (!in_array($attribute, $attributes, true) ||
40
            !$subject instanceof WishlistInterface) {
41
            return false;
42
        }
43
44
        return true;
45
    }
46
47
    /** @param string $attribute */
48
    protected function voteOnAttribute(
49
        $attribute,
50
        $subject,
51
        TokenInterface $token
52
    ): bool {
53
        $user = $token->getUser();
54
55
        if (!$user instanceof ShopUserInterface) {
56
            $user = null;
57
        }
58
59
        /** @var WishlistInterface $wishlist */
60
        $wishlist = $subject;
61
62
        switch ($attribute) {
63
            case self::UPDATE:
64
                return $this->canUpdate($wishlist, $user);
65
            case self::DELETE:
66
                return $this->canDelete($wishlist, $user);
67
        }
68
69
        throw new \LogicException(sprintf('Unsupported attribute: "%s"', $attribute));
70
    }
71
72
    public function canUpdate(WishlistInterface $wishlist, ?ShopUserInterface $user): bool
73
    {
74
        if (!$this->security->isGranted('ROLE_USER') && null === $wishlist->getShopUser()) {
75
            return true;
76
        }
77
78
        if ($this->security->isGranted('ROLE_USER') && $wishlist->getShopUser() === $user) {
79
            return true;
80
        }
81
82
        return false;
83
    }
84
85
    public function canDelete(WishlistInterface $wishlist, ?ShopUserInterface $user): bool
86
    {
87
        return $this->canUpdate($wishlist, $user);
88
    }
89
}
90