-
Notifications
You must be signed in to change notification settings - Fork 9
/
JWTPayload.php
108 lines (93 loc) · 2.51 KB
/
JWTPayload.php
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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
<?php
declare(strict_types=1);
namespace AstrotechLabs\JWTTools;
use DateInterval;
use DateTime;
use InvalidArgumentException;
final class JWTPayload
{
private int $exp;
private string $iss;
private string $aud;
private string|int $sub;
private int $iat;
private string $jti;
private array $extraAttributes = [];
private function __construct(array $payloadAttrs = [])
{
$now = new DateTime();
$this->iat = $payloadAttrs['iat'] ?? $now->getTimestamp();
$this->exp = $payloadAttrs['exp'] ?? $now->add(new DateInterval("PT3600S"))->getTimestamp();
$this->iss = $payloadAttrs['iss'] ?? '';
$this->aud = $payloadAttrs['aud'] ?? '';
$this->sub = $payloadAttrs['sub'] ?? $this->generateHash();
$this->jti = $payloadAttrs['jti'] ?? $this->generateHash();
if (!isset($payloadAttrs['extraParams'])) {
return;
}
foreach ($payloadAttrs['extraParams'] as $name => $value) {
$this->addExtraAttribute($name, $value);
}
}
/**
* @param array $payloadAttrs
* @return static
*/
public static function build(array $payloadAttrs = []): self
{
return new self($payloadAttrs);
}
/**
* @param string $attribute
* @throws InvalidArgumentException
* @return string | int
*/
public function get(string $attribute)
{
if (!property_exists($this, $attribute)) {
throw new InvalidArgumentException("Payload attribute '{$attribute}' doesn't exists.");
}
return $this->{$attribute};
}
/**
* @param string $name
* @param $value
* @return $this
*/
public function addExtraAttribute(string $name, $value): self
{
$this->extraAttributes[$name] = $value;
return $this;
}
/**
* @param string | int $sub
* @return JWTPayload
*/
public function setSub($sub): JWTPayload
{
$this->sub = $sub;
return $this;
}
/**
* @return array
*/
public function getData(): array
{
return array_merge([
'sub' => $this->sub,
'iss' => $this->iss,
'aud' => $this->aud,
'iat' => $this->iat,
'exp' => $this->exp,
'jti' => $this->jti
], $this->extraAttributes);
}
/**
* @return string
*/
private function generateHash(): string
{
$hash = md5(uniqid(rand() . "", true));
return substr($hash, 0, 15);
}
}