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 * Box service.
15 *
16 * @author Antoine Corcy <contact@sbin.dk>
17 * @link https://developers.box.com/oauth/
18 */
19class Box extends AbstractService
20{
21    public function __construct(
22        CredentialsInterface $credentials,
23        ClientInterface $httpClient,
24        TokenStorageInterface $storage,
25        $scopes = array(),
26        UriInterface $baseApiUri = null
27    ) {
28        parent::__construct($credentials, $httpClient, $storage, $scopes, $baseApiUri, true);
29
30        if (null === $baseApiUri) {
31            $this->baseApiUri = new Uri('https://api.box.com/2.0/');
32        }
33    }
34
35    /**
36     * {@inheritdoc}
37     */
38    public function getAuthorizationEndpoint()
39    {
40        return new Uri('https://www.box.com/api/oauth2/authorize');
41    }
42
43    /**
44     * {@inheritdoc}
45     */
46    public function getAccessTokenEndpoint()
47    {
48        return new Uri('https://www.box.com/api/oauth2/token');
49    }
50
51    /**
52     * {@inheritdoc}
53     */
54    protected function getAuthorizationMethod()
55    {
56        return static::AUTHORIZATION_METHOD_HEADER_BEARER;
57    }
58
59    /**
60     * {@inheritdoc}
61     */
62    protected function parseAccessTokenResponse($responseBody)
63    {
64        $data = json_decode($responseBody, true);
65
66        if (null === $data || !is_array($data)) {
67            throw new TokenResponseException('Unable to parse response.');
68        } elseif (isset($data['error'])) {
69            throw new TokenResponseException('Error in retrieving token: "' . $data['error'] . '"');
70        }
71
72        $token = new StdOAuth2Token();
73        $token->setAccessToken($data['access_token']);
74        $token->setLifeTime($data['expires_in']);
75
76        if (isset($data['refresh_token'])) {
77            $token->setRefreshToken($data['refresh_token']);
78            unset($data['refresh_token']);
79        }
80
81        unset($data['access_token']);
82        unset($data['expires_in']);
83
84        $token->setExtraParams($data);
85
86        return $token;
87    }
88}
89