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
13/**
14 * RunKeeper service.
15 *
16 * @link http://runkeeper.com/developer/healthgraph/registration-authorization
17 */
18class RunKeeper extends AbstractService
19{
20    public function __construct(
21        CredentialsInterface $credentials,
22        ClientInterface $httpClient,
23        TokenStorageInterface $storage,
24        $scopes = array(),
25        UriInterface $baseApiUri = null
26    ) {
27        parent::__construct($credentials, $httpClient, $storage, $scopes, $baseApiUri);
28
29        if (null === $baseApiUri) {
30            $this->baseApiUri = new Uri('https://api.runkeeper.com/');
31        }
32    }
33
34    /**
35     * {@inheritdoc}
36     */
37    public function getAuthorizationUri(array $additionalParameters = array())
38    {
39        $parameters = array_merge(
40            $additionalParameters,
41            array(
42                'client_id'     => $this->credentials->getConsumerId(),
43                'redirect_uri'  => $this->credentials->getCallbackUrl(),
44                'response_type' => 'code',
45            )
46        );
47
48        $parameters['scope'] = implode(' ', $this->scopes);
49
50        // Build the url
51        $url = clone $this->getAuthorizationEndpoint();
52        foreach ($parameters as $key => $val) {
53            $url->addToQuery($key, $val);
54        }
55
56        return $url;
57    }
58
59    /**
60     * {@inheritdoc}
61     */
62    public function getAuthorizationEndpoint()
63    {
64        return new Uri('https://runkeeper.com/apps/authorize');
65    }
66
67    /**
68     * {@inheritdoc}
69     */
70    public function getAccessTokenEndpoint()
71    {
72        return new Uri('https://runkeeper.com/apps/token');
73    }
74
75    /**
76     * {@inheritdoc}
77     */
78    protected function getAuthorizationMethod()
79    {
80        return static::AUTHORIZATION_METHOD_HEADER_BEARER;
81    }
82
83    /**
84     * {@inheritdoc}
85     */
86    protected function parseAccessTokenResponse($responseBody)
87    {
88        $data = json_decode($responseBody, true);
89
90        if (null === $data || !is_array($data)) {
91            throw new TokenResponseException('Unable to parse response.');
92        } elseif (isset($data['error'])) {
93            throw new TokenResponseException('Error in retrieving token: "' . $data['error'] . '"');
94        }
95
96        $token = new StdOAuth2Token();
97        $token->setAccessToken($data['access_token']);
98
99        unset($data['access_token']);
100
101        $token->setExtraParams($data);
102
103        return $token;
104    }
105}
106