1<?php
2
3namespace OAuth\OAuth2\Service;
4
5use OAuth\OAuth2\Token\StdOAuth2Token;
6use OAuth\Common\Http\Exception\TokenResponseException;
7use OAuth\Common\Http\Uri\Uri;
8use OAuth\Common\Consumer\CredentialsInterface;
9use OAuth\Common\Http\Client\ClientInterface;
10use OAuth\Common\Storage\TokenStorageInterface;
11use OAuth\Common\Http\Uri\UriInterface;
12
13class Ustream extends AbstractService
14{
15    /**
16     * Scopes
17     *
18     * @var string
19     */
20    const SCOPE_OFFLINE     = 'offline';
21    const SCOPE_BROADCASTER = 'broadcaster';
22
23    public function __construct(
24        CredentialsInterface $credentials,
25        ClientInterface $httpClient,
26        TokenStorageInterface $storage,
27        $scopes = array(),
28        UriInterface $baseApiUri = null
29    ) {
30        parent::__construct($credentials, $httpClient, $storage, $scopes, $baseApiUri, true);
31
32        if (null === $baseApiUri) {
33            $this->baseApiUri = new Uri('https://api.ustream.tv/');
34        }
35    }
36
37    /**
38     * {@inheritdoc}
39     */
40    public function getAuthorizationEndpoint()
41    {
42        return new Uri('https://www.ustream.tv/oauth2/authorize');
43    }
44
45    /**
46     * {@inheritdoc}
47     */
48    public function getAccessTokenEndpoint()
49    {
50        return new Uri('https://www.ustream.tv/oauth2/token');
51    }
52
53    /**
54     * {@inheritdoc}
55     */
56    protected function getAuthorizationMethod()
57    {
58        return static::AUTHORIZATION_METHOD_HEADER_BEARER;
59    }
60
61    /**
62     * {@inheritdoc}
63     */
64    protected function parseAccessTokenResponse($responseBody)
65    {
66        $data = json_decode($responseBody, true);
67
68        if (null === $data || !is_array($data)) {
69            throw new TokenResponseException('Unable to parse response.');
70        } elseif (isset($data['error'])) {
71            throw new TokenResponseException('Error in retrieving token: "' . $data['error'] . '"');
72        }
73
74        $token = new StdOAuth2Token();
75        $token->setAccessToken($data['access_token']);
76        $token->setLifeTime($data['expires_in']);
77
78        if (isset($data['refresh_token'])) {
79            $token->setRefreshToken($data['refresh_token']);
80            unset($data['refresh_token']);
81        }
82
83        unset($data['access_token']);
84        unset($data['expires_in']);
85
86        $token->setExtraParams($data);
87
88        return $token;
89    }
90
91    /**
92     * {@inheritdoc}
93     */
94    protected function getExtraOAuthHeaders()
95    {
96        return array('Authorization' => 'Basic ' . $this->credentials->getConsumerSecret());
97    }
98}
99