Passed
Push — develop ( 5b9941...3aaa0d )
by BENARD
08:32
created

TwitchItemDataProvider   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 49
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 22
c 1
b 0
f 0
dl 0
loc 49
rs 10
wmc 8

4 Methods

Rating   Name   Duplication   Size   Complexity  
A getAccessToken() 0 17 4
A __construct() 0 2 1
A getClient() 0 11 2
A getStream() 0 4 1
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) {
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment why this CATCH block is empty.
Loading history...
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