Passed
Push — master ( 4a474d...df1b75 )
by Stephen
02:14
created

activeUserRole()   A

Complexity

Conditions 6
Paths 4

Size

Total Lines 15
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 1 Features 0
Metric Value
cc 6
eloc 6
c 1
b 1
f 0
nc 4
nop 1
dl 0
loc 15
rs 9.2222
1
<?php
2
3
use Illuminate\Contracts\Auth\Authenticatable;
4
5
// todo: create package
6
/**
7
 * Retrieve the active User.
8
 *
9
 * @return Authenticatable|null
10
 */
11
function activeUser()
12
{
13
    return auth()->user();
14
}
15
16
/**
17
 * Retrieve the active user's user_id.
18
 *
19
 * @return int|string|null
20
 */
21
function activeUserID()
22
{
23
    return (auth()->user()) ? auth()->id() : null;
24
}
25
26
/**
27
 * Retrieve the active user's name.
28
 *
29
 * @return string|null
30
 */
31
function activeUserName()
32
{
33
    return (auth()->user()) ? auth()->user()->name : null;
34
}
35
36
/**
37
 * Check if the active user has a particular role or retrieve the active user's role name.
38
 *
39
 * @param string|int|null $role
40
 *
41
 * @return string|bool|null
42
 */
43
function activeUserRole($role = null)
44
{
45
    // Determine if the active user has a particular 'role name'
46
    if (isset($role) && is_int($role)) {
47
        return activeUser()->isRoleId($role);
48
    }
49
50
    // Determine if the active user has a particular 'role_id'
51
    elseif (isset($role) && is_string($role)) {
52
        return activeUser()->isRole($role);
53
    }
54
55
    // Return Active User's role name
56
    else {
57
        return (activeUser()) ? activeUser()->role->name : null;
0 ignored issues
show
Bug introduced by
Accessing role on the interface Illuminate\Contracts\Auth\Authenticatable suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
58
    }
59
}
60
61
/**
62
 * Determine if a User is an admin or is the active user.
63
 *
64
 * @param int $user_id
65
 *
66
 * @return bool
67
 */
68
function isAdminOrActiveUser(int $user_id): bool
69
{
70
    return activeUser()->isAdmin() || activeUserID() == $user_id;
71
}
72