-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathTokenable.php
More file actions
72 lines (59 loc) · 2.17 KB
/
Copy pathTokenable.php
File metadata and controls
72 lines (59 loc) · 2.17 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
<?php
declare(strict_types=1);
namespace KDuma\Eloquent;
use Hashids\Hashids;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Casts\Attribute;
use KDuma\Eloquent\Attributes\HasToken;
trait Tokenable
{
private function getHashingInstance(): Hashids
{
$salt = config('app.key') . (
$this->resolveTokenableConfig('salt', 'salt', null)
?? $this->getTable()
);
$minHashLength = $this->resolveTokenableConfig('length', 'length', 10);
$alphabet = $this->resolveTokenableConfig('alphabet', 'alphabet', 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890');
return new Hashids($salt, $minHashLength, $alphabet);
}
protected function token(): Attribute
{
return Attribute::make(
get: fn (): string => $this->getHashingInstance()->encode($this->id),
);
}
public function scopeWhereToken(Builder $query, string $token): Builder
{
$hashids = $this->getHashingInstance();
$id = $hashids->decode($token);
if ($id === []) {
return $query->whereRaw('1 = 0');
}
return $query->where('id', $id[0]);
}
private function resolveTokenableConfig(string $attrProperty, string $legacyProperty, mixed $default): mixed
{
$value = static::resolveClassAttribute(HasToken::class, $attrProperty);
if ($value !== null) {
return $value;
}
if (property_exists($this, $legacyProperty)) {
static $fired = [];
$key = static::class . '::$' . $legacyProperty;
if (!isset($fired[$key])) {
$fired[$key] = true;
trigger_error(
"Using \${$legacyProperty} on " . static::class . ' is deprecated. Use #[HasToken] attribute instead.',
E_USER_DEPRECATED,
);
}
$value = $this->{$legacyProperty};
// Treat 0 and '' as "use default" to preserve pre-deprecation behaviour (legacy used ?: operator)
if ($value !== 0 && $value !== '') {
return $value;
}
}
return $default;
}
}