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 Foursquare extends AbstractService
14{
15    private $apiVersionDate = '20130829';
16
17    public function __construct(
18        CredentialsInterface $credentials,
19        ClientInterface $httpClient,
20        TokenStorageInterface $storage,
21        $scopes = array(),
22        UriInterface $baseApiUri = null
23    ) {
24        parent::__construct($credentials, $httpClient, $storage, $scopes, $baseApiUri);
25
26        if (null === $baseApiUri) {
27            $this->baseApiUri = new Uri('https://api.foursquare.com/v2/');
28        }
29    }
30
31    /**
32     * {@inheritdoc}
33     */
34    public function getAuthorizationEndpoint()
35    {
36        return new Uri('https://foursquare.com/oauth2/authenticate');
37    }
38
39    /**
40     * {@inheritdoc}
41     */
42    public function getAccessTokenEndpoint()
43    {
44        return new Uri('https://foursquare.com/oauth2/access_token');
45    }
46
47    /**
48     * {@inheritdoc}
49     */
50    protected function parseAccessTokenResponse($responseBody)
51    {
52        $data = json_decode($responseBody, true);
53
54        if (null === $data || !is_array($data)) {
55            throw new TokenResponseException('Unable to parse response.');
56        } elseif (isset($data['error'])) {
57            throw new TokenResponseException('Error in retrieving token: "' . $data['error'] . '"');
58        }
59
60        $token = new StdOAuth2Token();
61        $token->setAccessToken($data['access_token']);
62        // Foursquare tokens evidently never expire...
63        $token->setEndOfLife(StdOAuth2Token::EOL_NEVER_EXPIRES);
64        unset($data['access_token']);
65
66        $token->setExtraParams($data);
67
68        return $token;
69    }
70
71    /**
72     * {@inheritdoc}
73     */
74    public function request($path, $method = 'GET', $body = null, array $extraHeaders = array())
75    {
76        $uri = $this->determineRequestUriFromPath($path, $this->baseApiUri);
77        $uri->addToQuery('v', $this->apiVersionDate);
78
79        return parent::request($uri, $method, $body, $extraHeaders);
80    }
81}
82