1<?php
2/**
3 * Nest service.
4 *
5 * @author  Pedro Amorim <contact@pamorim.fr>
6 * @license http://www.opensource.org/licenses/mit-license.html MIT License
7 * @link    https://developer.nest.com/documentation
8 */
9
10namespace OAuth\OAuth2\Service;
11
12use OAuth\OAuth2\Token\StdOAuth2Token;
13use OAuth\Common\Http\Exception\TokenResponseException;
14use OAuth\Common\Http\Uri\Uri;
15use OAuth\Common\Consumer\CredentialsInterface;
16use OAuth\Common\Http\Client\ClientInterface;
17use OAuth\Common\Storage\TokenStorageInterface;
18use OAuth\Common\Http\Uri\UriInterface;
19
20/**
21 * Nest service.
22 *
23 * @author  Pedro Amorim <contact@pamorim.fr>
24 * @license http://www.opensource.org/licenses/mit-license.html MIT License
25 * @link    https://developer.nest.com/documentation
26 */
27class Nest extends AbstractService
28{
29
30    public function __construct(
31        CredentialsInterface $credentials,
32        ClientInterface $httpClient,
33        TokenStorageInterface $storage,
34        $scopes = array(),
35        UriInterface $baseApiUri = null
36    ) {
37        parent::__construct(
38            $credentials,
39            $httpClient,
40            $storage,
41            $scopes,
42            $baseApiUri,
43            true
44        );
45
46        if (null === $baseApiUri) {
47            $this->baseApiUri = new Uri('https://developer-api.nest.com/');
48        }
49    }
50
51    /**
52     * {@inheritdoc}
53     */
54    public function getAuthorizationEndpoint()
55    {
56        return new Uri('https://home.nest.com/login/oauth2');
57    }
58
59    /**
60     * {@inheritdoc}
61     */
62    public function getAccessTokenEndpoint()
63    {
64        return new Uri('https://api.home.nest.com/oauth2/access_token');
65    }
66
67    /**
68     * {@inheritdoc}
69     */
70    protected function getAuthorizationMethod()
71    {
72        return static::AUTHORIZATION_METHOD_QUERY_STRING_V4;
73    }
74
75    /**
76     * {@inheritdoc}
77     */
78    protected function parseAccessTokenResponse($responseBody)
79    {
80        $data = json_decode($responseBody, true);
81
82        if (null === $data || !is_array($data)) {
83            throw new TokenResponseException('Unable to parse response.');
84        } elseif (isset($data['error'])) {
85            throw new TokenResponseException(
86                'Error in retrieving token: "' . $data['error'] . '"'
87            );
88        }
89
90        $token = new StdOAuth2Token();
91        $token->setAccessToken($data['access_token']);
92        $token->setLifeTime($data['expires_in']);
93
94        if (isset($data['refresh_token'])) {
95            $token->setRefreshToken($data['refresh_token']);
96            unset($data['refresh_token']);
97        }
98
99        unset($data['access_token']);
100        unset($data['expires_in']);
101
102        $token->setExtraParams($data);
103
104        return $token;
105    }
106}
107