Completed
Push — master ( f4905c...6812a9 )
by WEBEWEB
01:49
created

UserHelper::hasRoles()   B

Complexity

Conditions 7
Paths 7

Size

Total Lines 26

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 26
rs 8.5706
cc 7
nc 7
nop 3
1
<?php
2
3
/**
4
 * This file is part of the bootstrap-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\BootstrapBundle\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\BootstrapBundle\Helper
21
 */
22
class UserHelper {
23
24
    /**
25
     * Determines if the connected user entity has role $roles.
26
     *
27
     * @param object $user The user.
28
     * @param string|array $roles The role or roles.
29
     * @param boolean $or OR ? If true, matches a role cause a break and the method returns true.
30
     * @return boolean Returns true in case of success, false otherwise.
31
     */
32
    public 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
            $result &= in_array($role, $user->getRoles());
50
            if (true == $result && true === $or) {
0 ignored issues
show
Coding Style Best Practice introduced by
It seems like you are loosely comparing two booleans. Considering using the strict comparison === instead.

When comparing two booleans, it is generally considered safer to use the strict comparison operator.

Loading history...
51
                break;
52
            }
53
        }
54
55
        // Return the result.
56
        return boolval($result);
57
    }
58
59
}
60