Completed
Push — master ( aae44d...5e2102 )
by WEBEWEB
07:32
created

UserHelper   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 40
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 1

Importance

Changes 0
Metric Value
wmc 7
lcom 0
cbo 1
dl 0
loc 40
c 0
b 0
f 0
rs 10

1 Method

Rating   Name   Duplication   Size   Complexity  
B hasRoles() 0 28 7
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\Helper;
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\Helper
21
 */
22
class UserHelper {
23
24
    /**
25
     * Determines if the connected user entity has role $roles.
26
     *
27
     * @param UserInterface|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, $or = true) {
33
34
        // Check the user.
35
        if (null === $user || false === ($user instanceof UserInterface)) {
36
            return false;
37
        }
38
39
        // Check the roles.
40
        if (false === is_array($roles)) {
41
            $roles = [$roles];
42
        }
43
44
        // Initialize the result.
45
        $result = 1 <= count($roles);
46
47
        // Handle each role.
48
        foreach ($roles as $role) {
49
            $buffer = in_array($role, $user->getRoles());
50
            if (true === $buffer && true === $or) {
51
                $result = $buffer;
52
                break;
53
            }
54
            $result &= $buffer;
55
        }
56
57
        // Return the result.
58
        return boolval($result);
59
    }
60
61
}
62