UserHelper   A
last analyzed

Complexity

Total Complexity 6

Size/Duplication

Total Lines 35
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 6
eloc 13
dl 0
loc 35
rs 10
c 0
b 0
f 0

1 Method

Rating   Name   Duplication   Size   Complexity  
A hasRoles() 0 25 6
1
<?php
2
3
/*
4
 * This file is part of the core-bundle package.
5
 *
6
 * (c) 2018 WEBEWEB
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 WBW\Bundle\CoreBundle\Security\Core\User;
13
14
use Symfony\Component\Security\Core\User\UserInterface;
15
16
/**
17
 * User helper.
18
 *
19
 * @author webeweb <https://github.com/webeweb>
20
 * @package WBW\Bundle\CoreBundle\Security\Core\User
21
 */
22
class UserHelper {
23
24
    /**
25
     * Determine if the connected user entity has roles.
26
     *
27
     * @param mixed|null $user The user.
28
     * @param string|array $roles The role or roles.
29
     * @param bool $or OR ? If true, matches a role cause a break and the method returns true.
30
     * @return bool Returns true in case of success, false otherwise.
31
     */
32
    public static function hasRoles($user, $roles, bool $or = true): bool {
33
34
        if (false === ($user instanceof UserInterface)) {
35
            return false;
36
        }
37
38
        if (false === is_array($roles)) {
39
            $roles = [$roles];
40
        }
41
42
        $result = 1 <= count($roles);
0 ignored issues
show
Bug introduced by
It seems like $roles can also be of type string; however, parameter $value of count() does only seem to accept Countable|array, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

42
        $result = 1 <= count(/** @scrutinizer ignore-type */ $roles);
Loading history...
43
44
        foreach ($roles as $role) {
45
46
            $buffer = in_array($role, $user->getRoles());
47
48
            if (true === $buffer && true === $or) {
49
                $result = $buffer;
50
                break;
51
            }
52
53
            $result &= $buffer;
54
        }
55
56
        return $result;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $result could return the type integer which is incompatible with the type-hinted return boolean. Consider adding an additional type-check to rule them out.
Loading history...
57
    }
58
}
59