|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace Koba\Informat\AccessToken; |
| 4 | + |
| 5 | +use Koba\Informat\Exceptions\AccessTokenException; |
| 6 | +use Koba\Informat\Scopes\ScopeStrategyInterface; |
| 7 | +use Psr\Http\Client\ClientInterface; |
| 8 | +use Psr\Http\Message\RequestFactoryInterface; |
| 9 | +use Psr\Http\Message\StreamFactoryInterface; |
| 10 | + |
| 11 | +class AccessTokenFetcher |
| 12 | +{ |
| 13 | + public function __construct( |
| 14 | + protected string $clientId, |
| 15 | + protected string $clientSecret, |
| 16 | + protected ScopeStrategyInterface $scopeStrategy, |
| 17 | + protected ClientInterface $httpClient, |
| 18 | + protected RequestFactoryInterface $requestFactory, |
| 19 | + protected StreamFactoryInterface $streamFactory |
| 20 | + ) { |
| 21 | + } |
| 22 | + |
| 23 | + public function fetch(): AccessToken |
| 24 | + { |
| 25 | + $request = $this->requestFactory |
| 26 | + ->createRequest( |
| 27 | + 'post', |
| 28 | + 'https://www.identityserver.be/connect/token' |
| 29 | + ) |
| 30 | + ->withAddedHeader('Content-Type', 'application/x-www-form-urlencoded') |
| 31 | + ->withBody($this->streamFactory->createStream( |
| 32 | + http_build_query([ |
| 33 | + 'client_id' => $this->clientId, |
| 34 | + 'client_secret' => $this->clientSecret, |
| 35 | + 'scope' => implode(' ', $this->scopeStrategy->getScopes()), |
| 36 | + 'grant_type' => 'client_credentials' |
| 37 | + ]) |
| 38 | + )); |
| 39 | + |
| 40 | + $response = $this->httpClient->sendRequest($request); |
| 41 | + if ($response->getStatusCode() !== 200) { |
| 42 | + throw new AccessTokenException('Fetching access token failed.'); |
| 43 | + } |
| 44 | + |
| 45 | + $decoded = json_decode( |
| 46 | + $response->getBody()->getContents(), |
| 47 | + true |
| 48 | + ); |
| 49 | + |
| 50 | + if ( |
| 51 | + is_array($decoded) |
| 52 | + && array_key_exists('access_token', $decoded) |
| 53 | + && array_key_exists('expires_in', $decoded) |
| 54 | + ) { |
| 55 | + return new AccessToken($decoded['access_token'], $decoded['expires_in']); |
| 56 | + } |
| 57 | + |
| 58 | + throw new AccessTokenException('Invalid access token'); |
| 59 | + } |
| 60 | +} |
0 commit comments