AppClient::boot()   A
last analyzed

Complexity

Conditions 5
Paths 1

Size

Total Lines 29
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 13
c 1
b 0
f 0
dl 0
loc 29
rs 9.5222
cc 5
nc 1
nop 0
1
<?php
2
3
namespace ArcherZdip\LaravelApiAuth\Models;
4
5
use Illuminate\Support\Str;
0 ignored issues
show
Bug introduced by
The type Illuminate\Support\Str was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
6
use Illuminate\Support\Facades\Cache;
0 ignored issues
show
Bug introduced by
The type Illuminate\Support\Facades\Cache was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
7
use Illuminate\Database\Eloquent\Model;
0 ignored issues
show
Bug introduced by
The type Illuminate\Database\Eloquent\Model was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
8
use Illuminate\Database\Eloquent\SoftDeletes;
0 ignored issues
show
Bug introduced by
The type Illuminate\Database\Eloquent\SoftDeletes was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
9
10
class AppClient extends Model
11
{
12
    use SoftDeletes;
13
14
    const EVENT_NAME_CREATED     = 'created';
15
    const EVENT_NAME_ACTIVATED   = 'activated';
16
    const EVENT_NAME_DEACTIVATED = 'deactivated';
17
    const EVENT_NAME_DELETED     = 'deleted';
18
19
    /** @var int activate status */
20
    const ACTIVATE = 1;
21
    const DEACTIVATE = 0;
22
23
    protected static $nameRegex = '/^[a-z0-9-]{1,255}$/';
24
25
    /**
26
     * The attributes that are mass assignable.
27
     *
28
     * @var array
29
     */
30
    protected $fillable = [
31
        'name',
32
        'appid',
33
        'secret',
34
        'active'
35
    ];
36
37
    /**
38
     * The attributes that should be hidden for arrays.
39
     *
40
     * @var array
41
     */
42
    protected $hidden = [];
43
44
    public static function boot()
45
    {
46
        parent::boot();
47
48
        static::created(function(AppClient $appClient) {
49
            self::logApiAuthOprateEvent($appClient, self::EVENT_NAME_CREATED);
50
        });
51
52
        static::updated(function(AppClient $appClient) {
53
54
            $changed = $appClient->getDirty();
55
56
            if (isset($changed) && $changed['active'] === self::ACTIVATE) {
57
                self::logApiAuthOprateEvent($appClient, self::EVENT_NAME_ACTIVATED);
58
            }
59
60
            if (isset($changed) && $changed['active'] === self::DEACTIVATE) {
61
                self::logApiAuthOprateEvent($appClient, self::EVENT_NAME_DEACTIVATED);
62
            }
63
64
            // flush cache
65
            self::flushCache($appClient->name);
66
        });
67
68
        static::deleted(function(AppClient $appClient) {
69
            self::logApiAuthOprateEvent($appClient, self::EVENT_NAME_DELETED);
70
71
            // flush cache
72
            self::flushCache($appClient->name);
73
        });
74
75
    }
76
77
    /**
78
     * AppClient constructor.
79
     * @param array $attributes
80
     */
81
    public function __construct(array $attributes = [])
82
    {
83
        parent::__construct($attributes);
84
85
        $this->setTable(config('apikey.table_name.app_clients'));
0 ignored issues
show
Bug introduced by
The function config was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

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

85
        $this->setTable(/** @scrutinizer ignore-call */ config('apikey.table_name.app_clients'));
Loading history...
86
    }
87
88
    /**
89
     * Get secret by appid
90
     *
91
     * @param $appid
92
     * @return mixed
93
     */
94
    public static function getSecretByAppId($appid)
95
    {
96
        // cache false
97
        if (!config('apikey.cache.is_taken', false)) {
0 ignored issues
show
Bug introduced by
The function config was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

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

97
        if (!/** @scrutinizer ignore-call */ config('apikey.cache.is_taken', false)) {
Loading history...
98
            return self::getValueById($appid);
99
        }
100
101
        return Cache::rememberForever(config('apikey.cache.cache_key', 'apikey:clients:') . $appid, function () use ($appid) {
102
            return self::getValueById($appid);
103
        });
104
    }
105
106
    /**
107
     * Get model by appid
108
     *
109
     * @param $appid
110
     * @return mixed
111
     */
112
    public static function getValueById($appid)
113
    {
114
        return self::where([
115
            'active' => self::ACTIVATE,
116
            'appid'  => $appid
117
        ])->first();
118
    }
119
120
    /**
121
     * Generate AppId
122
     *
123
     * @return string
124
     */
125
    public static function generateAppId()
126
    {
127
        do {
128
            $appId = Str::random(config('apikey.appid_length', 16));
0 ignored issues
show
Bug introduced by
The function config was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

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

128
            $appId = Str::random(/** @scrutinizer ignore-call */ config('apikey.appid_length', 16));
Loading history...
129
        } while (self::appIdExists($appId));
130
131
        return $appId;
132
    }
133
134
    /**
135
     * Generate secret
136
     *
137
     * @return string
138
     */
139
    public static function generateSecret()
140
    {
141
        return Str::random(config('apikey.secret_length', 64));
0 ignored issues
show
Bug introduced by
The function config was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

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

141
        return Str::random(/** @scrutinizer ignore-call */ config('apikey.secret_length', 64));
Loading history...
142
    }
143
144
    /**
145
     * Check name is valid format
146
     *
147
     * @param $name
148
     * @return bool
149
     */
150
    public static function isValidName($name)
151
    {
152
        return (bool)preg_match(self::$nameRegex, $name);
153
    }
154
155
    /**
156
     * Check name is or not exists
157
     *
158
     * @param $name
159
     * @return bool
160
     */
161
    public static function nameExists($name)
162
    {
163
        return self::where('name', '=', $name)->first() instanceof self;
164
    }
165
166
    /**
167
     * Check AppId is or not exists
168
     *
169
     * @param $secret
170
     * @return bool
171
     */
172
    public static function appIdExists($appId)
173
    {
174
        return self::where('appid', $appId)->withTrashed()->first() instanceof self;
175
    }
176
177
    /**
178
     * Flush the key cache
179
     *
180
     * @param $cacheKey
181
     */
182
    public function flushCache($cacheKey)
183
    {
184
        Cache::forget($cacheKey);
185
    }
186
187
    /**
188
     * Log an app oprate admin event
189
     *
190
     * @param AppClient $appClient
191
     * @param string $eventName
192
     */
193
    protected static function logApiAuthOprateEvent(AppClient $appClient, $eventName)
194
    {
195
        $event = new ApiAuthOprateEvent();
196
        $event->app_client_id = $appClient->id;
197
        $event->ip_address = request()->ip();
0 ignored issues
show
Bug introduced by
The function request was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

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

197
        $event->ip_address = /** @scrutinizer ignore-call */ request()->ip();
Loading history...
198
        $event->event = $eventName;
199
        $event->save();
200
    }
201
}