RoleStat   A
last analyzed

Complexity

Total Complexity 4

Size/Duplication

Total Lines 23
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 4
eloc 10
c 0
b 0
f 0
dl 0
loc 23
rs 10

2 Methods

Rating   Name   Duplication   Size   Complexity  
A getUsersByRole() 0 3 1
A insertUsersByRole() 0 11 3
1
<?php
2
3
namespace App\Models;
4
5
use Illuminate\Database\Eloquent\Factories\HasFactory;
6
use Illuminate\Database\Eloquent\Model;
7
use Spatie\Permission\Models\Role;
8
9
class RoleStat extends Model
10
{
11
    use HasFactory;
0 ignored issues
show
Bug introduced by
The trait Illuminate\Database\Eloquent\Factories\HasFactory requires the property $factoryClass which is not provided by App\Models\RoleStat.
Loading history...
12
13
    protected $guarded = [];
14
15
    public static function insertUsersByRole(): void
16
    {
17
        $roles = Role::query()->select(['name'])->withCount('users')->groupBy('name')->having('users_count', '>', 0)->orderByDesc('users_count')->get();
0 ignored issues
show
Bug introduced by
'users_count' of type string is incompatible with the type Closure|Illuminate\Datab...\Database\Query\Builder expected by parameter $column of Illuminate\Database\Query\Builder::orderByDesc(). ( Ignorable by Annotation )

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

17
        $roles = Role::query()->select(['name'])->withCount('users')->groupBy('name')->having('users_count', '>', 0)->orderByDesc(/** @scrutinizer ignore-type */ 'users_count')->get();
Loading history...
18
        foreach ($roles as $role) {
19
            // Check if we already have the information and if we do just update the count
20
            if (self::query()->where('role', $role->name)->exists()) {
21
                self::query()->where('role', $role->name)->update(['users' => $role->users_count]);
22
23
                continue;
24
            }
25
            self::query()->create(['role' => $role->name, 'users' => $role->users_count]);
26
        }
27
    }
28
29
    public static function getUsersByRole(): array
30
    {
31
        return self::query()->select(['role', 'users'])->get()->toArray();
32
    }
33
}
34