Passed
Push — fix_coverage_in_scrutinizer ( cd0379...a04ba4 )
by Herberto
13:22
created

PostVoter   A

Complexity

Total Complexity 4

Size/Duplication

Total Lines 35
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 2

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 4
lcom 0
cbo 2
dl 0
loc 35
ccs 7
cts 7
cp 1
rs 10
c 0
b 0
f 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
A supports() 0 5 2
A voteOnAttribute() 0 14 2
1
<?php
2
3
/*
4
 * This file is part of the Symfony package.
5
 *
6
 * (c) Fabien Potencier <[email protected]>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
namespace App\Security;
13
14
use App\Entity\Post;
15
use App\Entity\User;
16
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
17
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
18
19
/**
20
 * It grants or denies permissions for actions related to blog posts (such as
21
 * showing, editing and deleting posts).
22
 *
23
 * See https://symfony.com/doc/current/security/voters.html
24
 *
25
 * @author Yonel Ceruto <[email protected]>
26
 */
27
class PostVoter extends Voter
28
{
29
    // Defining these constants is overkill for this simple application, but for real
30
    // applications, it's a recommended practice to avoid relying on "magic strings"
31
    const SHOW = 'show';
32
    const EDIT = 'edit';
33
    const DELETE = 'delete';
34
35
    /**
36
     * {@inheritdoc}
37
     */
38 16
    protected function supports($attribute, $subject): bool
39
    {
40
        // this voter is only executed for three specific permissions on Post objects
41 16
        return $subject instanceof Post && in_array($attribute, [self::SHOW, self::EDIT, self::DELETE], true);
42
    }
43
44
    /**
45
     * {@inheritdoc}
46
     */
47 5
    protected function voteOnAttribute($attribute, $post, TokenInterface $token): bool
48
    {
49 5
        $user = $token->getUser();
50
51
        // the user must be logged in; if not, deny permission
52 5
        if (!$user instanceof User) {
53 1
            return false;
54
        }
55
56
        // the logic of this voter is pretty simple: if the logged user is the
57
        // author of the given blog post, grant permission; otherwise, deny it.
58
        // (the supports() method guarantees that $post is a Post object)
59 4
        return $user === $post->getAuthor();
60
    }
61
}
62