|
2 | 2 |
|
3 | 3 | namespace Sensson\Moneybird\Casts; |
4 | 4 |
|
| 5 | +use DateTimeImmutable; |
5 | 6 | use Saloon\Http\Auth\AccessTokenAuthenticator; |
6 | 7 |
|
7 | 8 | class MoneybirdAuth |
8 | 9 | { |
9 | | - /** |
10 | | - * Cast the given value. |
11 | | - */ |
12 | 10 | public function get($model, string $key, $value, array $attributes): ?AccessTokenAuthenticator |
13 | 11 | { |
14 | 12 | if (is_null($value)) { |
15 | 13 | return null; |
16 | 14 | } |
17 | 15 |
|
18 | | - return unserialize($value, ['allowed_classes' => true]); |
| 16 | + $data = json_decode($value, true); |
| 17 | + |
| 18 | + if (json_last_error() !== JSON_ERROR_NONE) { |
| 19 | + $legacy = unserialize($value, [ |
| 20 | + 'allowed_classes' => [AccessTokenAuthenticator::class, DateTimeImmutable::class], |
| 21 | + ]); |
| 22 | + |
| 23 | + return new AccessTokenAuthenticator( |
| 24 | + accessToken: $legacy->getAccessToken(), |
| 25 | + refreshToken: $legacy->getRefreshToken(), |
| 26 | + expiresAt: $legacy->getExpiresAt(), |
| 27 | + ); |
| 28 | + } |
| 29 | + |
| 30 | + return new AccessTokenAuthenticator( |
| 31 | + accessToken: $data['access_token'], |
| 32 | + refreshToken: $data['refresh_token'] ?? null, |
| 33 | + expiresAt: isset($data['expires_at']) ? new DateTimeImmutable($data['expires_at']) : null, |
| 34 | + ); |
19 | 35 | } |
20 | 36 |
|
21 | | - /** |
22 | | - * Prepare the given value for storage. |
23 | | - */ |
24 | 37 | public function set($model, string $key, $value, array $attributes): mixed |
25 | 38 | { |
26 | 39 | if (is_null($value)) { |
27 | 40 | return null; |
28 | 41 | } |
29 | 42 |
|
30 | | - return serialize($value); |
| 43 | + return json_encode([ |
| 44 | + 'access_token' => $value->getAccessToken(), |
| 45 | + 'refresh_token' => $value->getRefreshToken(), |
| 46 | + 'expires_at' => $value->getExpiresAt()?->format(DateTimeImmutable::ATOM), |
| 47 | + ]); |
31 | 48 | } |
32 | 49 | } |
0 commit comments