|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace ProjetNormandie\TwitchBundle\DataProvider; |
|
4
|
|
|
|
|
5
|
|
|
use Exception; |
|
6
|
|
|
use GuzzleHttp\Exception\GuzzleException; |
|
7
|
|
|
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface; |
|
8
|
|
|
use TwitchApi\HelixGuzzleClient; |
|
9
|
|
|
use TwitchApi\TwitchApi; |
|
10
|
|
|
|
|
11
|
|
|
final class TwitchItemDataProvider |
|
12
|
|
|
{ |
|
13
|
|
|
private ?TwitchApi $client = null; |
|
14
|
|
|
|
|
15
|
|
|
private ?string $accessToken = null; |
|
16
|
|
|
|
|
17
|
|
|
private string $twitchScopes = ''; |
|
18
|
|
|
|
|
19
|
|
|
public function __construct(private readonly ParameterBagInterface $params,) |
|
20
|
|
|
{ |
|
21
|
|
|
} |
|
22
|
|
|
|
|
23
|
|
|
private function getClient(): TwitchApi |
|
24
|
|
|
{ |
|
25
|
|
|
if (null === $this->client) { |
|
26
|
|
|
$helixGuzzleClient = new HelixGuzzleClient($this->params->get('pn.twitch.client_id')); |
|
27
|
|
|
$this->client = new TwitchApi( |
|
28
|
|
|
$helixGuzzleClient, |
|
29
|
|
|
$this->params->get('pn.twitch.client_id'), |
|
30
|
|
|
$this->params->get('pn.twitch.client_secret') |
|
31
|
|
|
); |
|
32
|
|
|
} |
|
33
|
|
|
return $this->client; |
|
34
|
|
|
} |
|
35
|
|
|
|
|
36
|
|
|
|
|
37
|
|
|
private function getAccessToken(): string |
|
38
|
|
|
{ |
|
39
|
|
|
if (null === $this->accessToken) { |
|
40
|
|
|
$oauth = $this->getClient()->getOauthApi(); |
|
41
|
|
|
try { |
|
42
|
|
|
$token = $oauth->getAppAccessToken($this->twitchScopes ?? ''); |
|
43
|
|
|
$data = json_decode($token->getBody()->getContents()); |
|
44
|
|
|
|
|
45
|
|
|
// Your bearer token |
|
46
|
|
|
$this->accessToken = $data->access_token ?? null; |
|
47
|
|
|
} catch (Exception $e) { |
|
48
|
|
|
//TODO: Handle Error |
|
49
|
|
|
} catch (GuzzleException $e) { |
|
|
|
|
|
|
50
|
|
|
} |
|
51
|
|
|
} |
|
52
|
|
|
|
|
53
|
|
|
return $this->accessToken; |
|
54
|
|
|
} |
|
55
|
|
|
|
|
56
|
|
|
public function getStream(string $username) |
|
57
|
|
|
{ |
|
58
|
|
|
$response = $this->getClient()->getStreamsApi()->getStreamForUsername($this->getAccessToken(), $username); |
|
59
|
|
|
return json_decode($response->getBody()->getContents()); |
|
60
|
|
|
} |
|
61
|
|
|
} |
|
62
|
|
|
|