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