Guard::getDefaultName()   A
last analyzed

Complexity

Conditions 2
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 2
c 1
b 0
f 0
nc 1
nop 1
dl 0
loc 4
ccs 0
cts 0
cp 0
crap 6
rs 10
1
<?php
2
3
namespace Maklad\Permission;
4
5
use Illuminate\Support\Collection;
6
7
/**
8
 * Class Guard
9
 * @package Maklad\Permission
10
 */
11
class Guard
12
{
13
    /**
14
     * return collection of (guard_name) property if exist on class or object
15
     * otherwise will return collection of guards names that exists in config/auth.php.
16
     *
17
     * @param $model
18
     *
19
     * @return Collection
20
     * @throws \ReflectionException
21
     */
22 123
    public function getNames($model) : Collection
23
    {
24 123
        $guardName = null;
25 98
        $class = null;
26
27
        if (\is_object($model)) {
28 123
            $guardName = $model->guard_name ?? null;
29 123
        }
30 123
31
        if ($guardName === null) {
32
            $class = \is_object($model) ? \get_class($model) : $model;
33 123
            $guardName = (new \ReflectionClass($class))->getDefaultProperties()['guard_name'] ?? null;
34 35
        }
35
36 123
        if ($guardName) {
37 123
            return collect($guardName);
38 123
        }
39 1
40
        return collect(config('auth.guards'))
41 123
            ->map(function ($guard) {
42 123
                if (! isset($guard['provider'])) {
43 123
                    return;
44 123
                }
45 123
                return config("auth.providers.{$guard['provider']}.model");
46 123
            })
47
            ->filter(function ($model) use ($class) {
48
                return $class === $model;
49
            })
50
            ->keys();
51
    }
52
53
    /**
54
     * Return Default Guard name
55
     *
56
     * @param $class
57 123
     *
58
     * @return string
59 123
     * @throws \ReflectionException
60 123
     */
61
    public function getDefaultName($class): string
62
    {
63
        $default = config('auth.defaults.guard');
64
        return $this->getNames($class)->first() ?: $default;
65
    }
66
}
67